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/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.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/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 //===----------------------------------------------------------------------===// 224 // SCEV class definitions 225 //===----------------------------------------------------------------------===// 226 227 //===----------------------------------------------------------------------===// 228 // Implementation of the SCEV class. 229 // 230 231 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 232 LLVM_DUMP_METHOD void SCEV::dump() const { 233 print(dbgs()); 234 dbgs() << '\n'; 235 } 236 #endif 237 238 void SCEV::print(raw_ostream &OS) const { 239 switch (static_cast<SCEVTypes>(getSCEVType())) { 240 case scConstant: 241 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 242 return; 243 case scTruncate: { 244 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 245 const SCEV *Op = Trunc->getOperand(); 246 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 247 << *Trunc->getType() << ")"; 248 return; 249 } 250 case scZeroExtend: { 251 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 252 const SCEV *Op = ZExt->getOperand(); 253 OS << "(zext " << *Op->getType() << " " << *Op << " to " 254 << *ZExt->getType() << ")"; 255 return; 256 } 257 case scSignExtend: { 258 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 259 const SCEV *Op = SExt->getOperand(); 260 OS << "(sext " << *Op->getType() << " " << *Op << " to " 261 << *SExt->getType() << ")"; 262 return; 263 } 264 case scAddRecExpr: { 265 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 266 OS << "{" << *AR->getOperand(0); 267 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 268 OS << ",+," << *AR->getOperand(i); 269 OS << "}<"; 270 if (AR->hasNoUnsignedWrap()) 271 OS << "nuw><"; 272 if (AR->hasNoSignedWrap()) 273 OS << "nsw><"; 274 if (AR->hasNoSelfWrap() && 275 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 276 OS << "nw><"; 277 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 278 OS << ">"; 279 return; 280 } 281 case scAddExpr: 282 case scMulExpr: 283 case scUMaxExpr: 284 case scSMaxExpr: 285 case scUMinExpr: 286 case scSMinExpr: { 287 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 288 const char *OpStr = nullptr; 289 switch (NAry->getSCEVType()) { 290 case scAddExpr: OpStr = " + "; break; 291 case scMulExpr: OpStr = " * "; break; 292 case scUMaxExpr: OpStr = " umax "; break; 293 case scSMaxExpr: OpStr = " smax "; break; 294 case scUMinExpr: 295 OpStr = " umin "; 296 break; 297 case scSMinExpr: 298 OpStr = " smin "; 299 break; 300 } 301 OS << "("; 302 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 303 I != E; ++I) { 304 OS << **I; 305 if (std::next(I) != E) 306 OS << OpStr; 307 } 308 OS << ")"; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: 311 case scMulExpr: 312 if (NAry->hasNoUnsignedWrap()) 313 OS << "<nuw>"; 314 if (NAry->hasNoSignedWrap()) 315 OS << "<nsw>"; 316 } 317 return; 318 } 319 case scUDivExpr: { 320 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 321 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 322 return; 323 } 324 case scUnknown: { 325 const SCEVUnknown *U = cast<SCEVUnknown>(this); 326 Type *AllocTy; 327 if (U->isSizeOf(AllocTy)) { 328 OS << "sizeof(" << *AllocTy << ")"; 329 return; 330 } 331 if (U->isAlignOf(AllocTy)) { 332 OS << "alignof(" << *AllocTy << ")"; 333 return; 334 } 335 336 Type *CTy; 337 Constant *FieldNo; 338 if (U->isOffsetOf(CTy, FieldNo)) { 339 OS << "offsetof(" << *CTy << ", "; 340 FieldNo->printAsOperand(OS, false); 341 OS << ")"; 342 return; 343 } 344 345 // Otherwise just print it normally. 346 U->getValue()->printAsOperand(OS, false); 347 return; 348 } 349 case scCouldNotCompute: 350 OS << "***COULDNOTCOMPUTE***"; 351 return; 352 } 353 llvm_unreachable("Unknown SCEV kind!"); 354 } 355 356 Type *SCEV::getType() const { 357 switch (static_cast<SCEVTypes>(getSCEVType())) { 358 case scConstant: 359 return cast<SCEVConstant>(this)->getType(); 360 case scTruncate: 361 case scZeroExtend: 362 case scSignExtend: 363 return cast<SCEVCastExpr>(this)->getType(); 364 case scAddRecExpr: 365 case scMulExpr: 366 case scUMaxExpr: 367 case scSMaxExpr: 368 case scUMinExpr: 369 case scSMinExpr: 370 return cast<SCEVNAryExpr>(this)->getType(); 371 case scAddExpr: 372 return cast<SCEVAddExpr>(this)->getType(); 373 case scUDivExpr: 374 return cast<SCEVUDivExpr>(this)->getType(); 375 case scUnknown: 376 return cast<SCEVUnknown>(this)->getType(); 377 case scCouldNotCompute: 378 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 379 } 380 llvm_unreachable("Unknown SCEV kind!"); 381 } 382 383 bool SCEV::isZero() const { 384 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 385 return SC->getValue()->isZero(); 386 return false; 387 } 388 389 bool SCEV::isOne() const { 390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 391 return SC->getValue()->isOne(); 392 return false; 393 } 394 395 bool SCEV::isAllOnesValue() const { 396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 397 return SC->getValue()->isMinusOne(); 398 return false; 399 } 400 401 bool SCEV::isNonConstantNegative() const { 402 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 403 if (!Mul) return false; 404 405 // If there is a constant factor, it will be first. 406 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 407 if (!SC) return false; 408 409 // Return true if the value is negative, this matches things like (-42 * V). 410 return SC->getAPInt().isNegative(); 411 } 412 413 SCEVCouldNotCompute::SCEVCouldNotCompute() : 414 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 415 416 bool SCEVCouldNotCompute::classof(const SCEV *S) { 417 return S->getSCEVType() == scCouldNotCompute; 418 } 419 420 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 421 FoldingSetNodeID ID; 422 ID.AddInteger(scConstant); 423 ID.AddPointer(V); 424 void *IP = nullptr; 425 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 426 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 427 UniqueSCEVs.InsertNode(S, IP); 428 return S; 429 } 430 431 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 432 return getConstant(ConstantInt::get(getContext(), Val)); 433 } 434 435 const SCEV * 436 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 437 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 438 return getConstant(ConstantInt::get(ITy, V, isSigned)); 439 } 440 441 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 442 unsigned SCEVTy, const SCEV *op, Type *ty) 443 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 444 445 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 446 const SCEV *op, Type *ty) 447 : SCEVCastExpr(ID, scTruncate, op, ty) { 448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 449 "Cannot truncate non-integer value!"); 450 } 451 452 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 453 const SCEV *op, Type *ty) 454 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 456 "Cannot zero extend non-integer value!"); 457 } 458 459 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 460 const SCEV *op, Type *ty) 461 : SCEVCastExpr(ID, scSignExtend, op, ty) { 462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 463 "Cannot sign extend non-integer value!"); 464 } 465 466 void SCEVUnknown::deleted() { 467 // Clear this SCEVUnknown from various maps. 468 SE->forgetMemoizedResults(this); 469 470 // Remove this SCEVUnknown from the uniquing map. 471 SE->UniqueSCEVs.RemoveNode(this); 472 473 // Release the value. 474 setValPtr(nullptr); 475 } 476 477 void SCEVUnknown::allUsesReplacedWith(Value *New) { 478 // Remove this SCEVUnknown from the uniquing map. 479 SE->UniqueSCEVs.RemoveNode(this); 480 481 // Update this SCEVUnknown to point to the new value. This is needed 482 // because there may still be outstanding SCEVs which still point to 483 // this SCEVUnknown. 484 setValPtr(New); 485 } 486 487 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 488 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 489 if (VCE->getOpcode() == Instruction::PtrToInt) 490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 491 if (CE->getOpcode() == Instruction::GetElementPtr && 492 CE->getOperand(0)->isNullValue() && 493 CE->getNumOperands() == 2) 494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 495 if (CI->isOne()) { 496 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 497 ->getElementType(); 498 return true; 499 } 500 501 return false; 502 } 503 504 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 505 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 506 if (VCE->getOpcode() == Instruction::PtrToInt) 507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 508 if (CE->getOpcode() == Instruction::GetElementPtr && 509 CE->getOperand(0)->isNullValue()) { 510 Type *Ty = 511 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 512 if (StructType *STy = dyn_cast<StructType>(Ty)) 513 if (!STy->isPacked() && 514 CE->getNumOperands() == 3 && 515 CE->getOperand(1)->isNullValue()) { 516 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 517 if (CI->isOne() && 518 STy->getNumElements() == 2 && 519 STy->getElementType(0)->isIntegerTy(1)) { 520 AllocTy = STy->getElementType(1); 521 return true; 522 } 523 } 524 } 525 526 return false; 527 } 528 529 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 530 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 531 if (VCE->getOpcode() == Instruction::PtrToInt) 532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 533 if (CE->getOpcode() == Instruction::GetElementPtr && 534 CE->getNumOperands() == 3 && 535 CE->getOperand(0)->isNullValue() && 536 CE->getOperand(1)->isNullValue()) { 537 Type *Ty = 538 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 539 // Ignore vector types here so that ScalarEvolutionExpander doesn't 540 // emit getelementptrs that index into vectors. 541 if (Ty->isStructTy() || Ty->isArrayTy()) { 542 CTy = Ty; 543 FieldNo = CE->getOperand(2); 544 return true; 545 } 546 } 547 548 return false; 549 } 550 551 //===----------------------------------------------------------------------===// 552 // SCEV Utilities 553 //===----------------------------------------------------------------------===// 554 555 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 556 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 557 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 558 /// have been previously deemed to be "equally complex" by this routine. It is 559 /// intended to avoid exponential time complexity in cases like: 560 /// 561 /// %a = f(%x, %y) 562 /// %b = f(%a, %a) 563 /// %c = f(%b, %b) 564 /// 565 /// %d = f(%x, %y) 566 /// %e = f(%d, %d) 567 /// %f = f(%e, %e) 568 /// 569 /// CompareValueComplexity(%f, %c) 570 /// 571 /// Since we do not continue running this routine on expression trees once we 572 /// have seen unequal values, there is no need to track them in the cache. 573 static int 574 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 575 const LoopInfo *const LI, Value *LV, Value *RV, 576 unsigned Depth) { 577 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 578 return 0; 579 580 // Order pointer values after integer values. This helps SCEVExpander form 581 // GEPs. 582 bool LIsPointer = LV->getType()->isPointerTy(), 583 RIsPointer = RV->getType()->isPointerTy(); 584 if (LIsPointer != RIsPointer) 585 return (int)LIsPointer - (int)RIsPointer; 586 587 // Compare getValueID values. 588 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 589 if (LID != RID) 590 return (int)LID - (int)RID; 591 592 // Sort arguments by their position. 593 if (const auto *LA = dyn_cast<Argument>(LV)) { 594 const auto *RA = cast<Argument>(RV); 595 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 596 return (int)LArgNo - (int)RArgNo; 597 } 598 599 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 600 const auto *RGV = cast<GlobalValue>(RV); 601 602 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 603 auto LT = GV->getLinkage(); 604 return !(GlobalValue::isPrivateLinkage(LT) || 605 GlobalValue::isInternalLinkage(LT)); 606 }; 607 608 // Use the names to distinguish the two values, but only if the 609 // names are semantically important. 610 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 611 return LGV->getName().compare(RGV->getName()); 612 } 613 614 // For instructions, compare their loop depth, and their operand count. This 615 // is pretty loose. 616 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 617 const auto *RInst = cast<Instruction>(RV); 618 619 // Compare loop depths. 620 const BasicBlock *LParent = LInst->getParent(), 621 *RParent = RInst->getParent(); 622 if (LParent != RParent) { 623 unsigned LDepth = LI->getLoopDepth(LParent), 624 RDepth = LI->getLoopDepth(RParent); 625 if (LDepth != RDepth) 626 return (int)LDepth - (int)RDepth; 627 } 628 629 // Compare the number of operands. 630 unsigned LNumOps = LInst->getNumOperands(), 631 RNumOps = RInst->getNumOperands(); 632 if (LNumOps != RNumOps) 633 return (int)LNumOps - (int)RNumOps; 634 635 for (unsigned Idx : seq(0u, LNumOps)) { 636 int Result = 637 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 638 RInst->getOperand(Idx), Depth + 1); 639 if (Result != 0) 640 return Result; 641 } 642 } 643 644 EqCacheValue.unionSets(LV, RV); 645 return 0; 646 } 647 648 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 649 // than RHS, respectively. A three-way result allows recursive comparisons to be 650 // more efficient. 651 static int CompareSCEVComplexity( 652 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 653 EquivalenceClasses<const Value *> &EqCacheValue, 654 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 655 DominatorTree &DT, unsigned Depth = 0) { 656 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 657 if (LHS == RHS) 658 return 0; 659 660 // Primarily, sort the SCEVs by their getSCEVType(). 661 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 662 if (LType != RType) 663 return (int)LType - (int)RType; 664 665 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 666 return 0; 667 // Aside from the getSCEVType() ordering, the particular ordering 668 // isn't very important except that it's beneficial to be consistent, 669 // so that (a + b) and (b + a) don't end up as different expressions. 670 switch (static_cast<SCEVTypes>(LType)) { 671 case scUnknown: { 672 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 673 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 674 675 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 676 RU->getValue(), Depth + 1); 677 if (X == 0) 678 EqCacheSCEV.unionSets(LHS, RHS); 679 return X; 680 } 681 682 case scConstant: { 683 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 684 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 685 686 // Compare constant values. 687 const APInt &LA = LC->getAPInt(); 688 const APInt &RA = RC->getAPInt(); 689 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 690 if (LBitWidth != RBitWidth) 691 return (int)LBitWidth - (int)RBitWidth; 692 return LA.ult(RA) ? -1 : 1; 693 } 694 695 case scAddRecExpr: { 696 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 697 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 698 699 // There is always a dominance between two recs that are used by one SCEV, 700 // so we can safely sort recs by loop header dominance. We require such 701 // order in getAddExpr. 702 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 703 if (LLoop != RLoop) { 704 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 705 assert(LHead != RHead && "Two loops share the same header?"); 706 if (DT.dominates(LHead, RHead)) 707 return 1; 708 else 709 assert(DT.dominates(RHead, LHead) && 710 "No dominance between recurrences used by one SCEV?"); 711 return -1; 712 } 713 714 // Addrec complexity grows with operand count. 715 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 716 if (LNumOps != RNumOps) 717 return (int)LNumOps - (int)RNumOps; 718 719 // Lexicographically compare. 720 for (unsigned i = 0; i != LNumOps; ++i) { 721 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 722 LA->getOperand(i), RA->getOperand(i), DT, 723 Depth + 1); 724 if (X != 0) 725 return X; 726 } 727 EqCacheSCEV.unionSets(LHS, RHS); 728 return 0; 729 } 730 731 case scAddExpr: 732 case scMulExpr: 733 case scSMaxExpr: 734 case scUMaxExpr: 735 case scSMinExpr: 736 case scUMinExpr: { 737 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 738 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 739 740 // Lexicographically compare n-ary expressions. 741 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 742 if (LNumOps != RNumOps) 743 return (int)LNumOps - (int)RNumOps; 744 745 for (unsigned i = 0; i != LNumOps; ++i) { 746 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 747 LC->getOperand(i), RC->getOperand(i), DT, 748 Depth + 1); 749 if (X != 0) 750 return X; 751 } 752 EqCacheSCEV.unionSets(LHS, RHS); 753 return 0; 754 } 755 756 case scUDivExpr: { 757 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 758 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 759 760 // Lexicographically compare udiv expressions. 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 762 RC->getLHS(), DT, Depth + 1); 763 if (X != 0) 764 return X; 765 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 766 RC->getRHS(), DT, Depth + 1); 767 if (X == 0) 768 EqCacheSCEV.unionSets(LHS, RHS); 769 return X; 770 } 771 772 case scTruncate: 773 case scZeroExtend: 774 case scSignExtend: { 775 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 776 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 777 778 // Compare cast expressions by operand. 779 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 780 LC->getOperand(), RC->getOperand(), DT, 781 Depth + 1); 782 if (X == 0) 783 EqCacheSCEV.unionSets(LHS, RHS); 784 return X; 785 } 786 787 case scCouldNotCompute: 788 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 789 } 790 llvm_unreachable("Unknown SCEV kind!"); 791 } 792 793 /// Given a list of SCEV objects, order them by their complexity, and group 794 /// objects of the same complexity together by value. When this routine is 795 /// finished, we know that any duplicates in the vector are consecutive and that 796 /// complexity is monotonically increasing. 797 /// 798 /// Note that we go take special precautions to ensure that we get deterministic 799 /// results from this routine. In other words, we don't want the results of 800 /// this to depend on where the addresses of various SCEV objects happened to 801 /// land in memory. 802 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 803 LoopInfo *LI, DominatorTree &DT) { 804 if (Ops.size() < 2) return; // Noop 805 806 EquivalenceClasses<const SCEV *> EqCacheSCEV; 807 EquivalenceClasses<const Value *> EqCacheValue; 808 if (Ops.size() == 2) { 809 // This is the common case, which also happens to be trivially simple. 810 // Special case it. 811 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 812 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 813 std::swap(LHS, RHS); 814 return; 815 } 816 817 // Do the rough sort by complexity. 818 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 819 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 820 0; 821 }); 822 823 // Now that we are sorted by complexity, group elements of the same 824 // complexity. Note that this is, at worst, N^2, but the vector is likely to 825 // be extremely short in practice. Note that we take this approach because we 826 // do not want to depend on the addresses of the objects we are grouping. 827 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 828 const SCEV *S = Ops[i]; 829 unsigned Complexity = S->getSCEVType(); 830 831 // If there are any objects of the same complexity and same value as this 832 // one, group them. 833 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 834 if (Ops[j] == S) { // Found a duplicate. 835 // Move it to immediately after i'th element. 836 std::swap(Ops[i+1], Ops[j]); 837 ++i; // no need to rescan it. 838 if (i == e-2) return; // Done! 839 } 840 } 841 } 842 } 843 844 // Returns the size of the SCEV S. 845 static inline int sizeOfSCEV(const SCEV *S) { 846 struct FindSCEVSize { 847 int Size = 0; 848 849 FindSCEVSize() = default; 850 851 bool follow(const SCEV *S) { 852 ++Size; 853 // Keep looking at all operands of S. 854 return true; 855 } 856 857 bool isDone() const { 858 return false; 859 } 860 }; 861 862 FindSCEVSize F; 863 SCEVTraversal<FindSCEVSize> ST(F); 864 ST.visitAll(S); 865 return F.Size; 866 } 867 868 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 869 /// nodes. 870 static bool isHugeExpression(const SCEV *S) { 871 return S->getExpressionSize() >= HugeExprThreshold; 872 } 873 874 /// Returns true of \p Ops contains a huge SCEV (see definition above). 875 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 876 return any_of(Ops, isHugeExpression); 877 } 878 879 namespace { 880 881 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 882 public: 883 // Computes the Quotient and Remainder of the division of Numerator by 884 // Denominator. 885 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 886 const SCEV *Denominator, const SCEV **Quotient, 887 const SCEV **Remainder) { 888 assert(Numerator && Denominator && "Uninitialized SCEV"); 889 890 SCEVDivision D(SE, Numerator, Denominator); 891 892 // Check for the trivial case here to avoid having to check for it in the 893 // rest of the code. 894 if (Numerator == Denominator) { 895 *Quotient = D.One; 896 *Remainder = D.Zero; 897 return; 898 } 899 900 if (Numerator->isZero()) { 901 *Quotient = D.Zero; 902 *Remainder = D.Zero; 903 return; 904 } 905 906 // A simple case when N/1. The quotient is N. 907 if (Denominator->isOne()) { 908 *Quotient = Numerator; 909 *Remainder = D.Zero; 910 return; 911 } 912 913 // Split the Denominator when it is a product. 914 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 915 const SCEV *Q, *R; 916 *Quotient = Numerator; 917 for (const SCEV *Op : T->operands()) { 918 divide(SE, *Quotient, Op, &Q, &R); 919 *Quotient = Q; 920 921 // Bail out when the Numerator is not divisible by one of the terms of 922 // the Denominator. 923 if (!R->isZero()) { 924 *Quotient = D.Zero; 925 *Remainder = Numerator; 926 return; 927 } 928 } 929 *Remainder = D.Zero; 930 return; 931 } 932 933 D.visit(Numerator); 934 *Quotient = D.Quotient; 935 *Remainder = D.Remainder; 936 } 937 938 // Except in the trivial case described above, we do not know how to divide 939 // Expr by Denominator for the following functions with empty implementation. 940 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 941 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 942 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 943 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 944 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 945 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 946 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 947 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 948 void visitUnknown(const SCEVUnknown *Numerator) {} 949 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 950 951 void visitConstant(const SCEVConstant *Numerator) { 952 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 953 APInt NumeratorVal = Numerator->getAPInt(); 954 APInt DenominatorVal = D->getAPInt(); 955 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 956 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 957 958 if (NumeratorBW > DenominatorBW) 959 DenominatorVal = DenominatorVal.sext(NumeratorBW); 960 else if (NumeratorBW < DenominatorBW) 961 NumeratorVal = NumeratorVal.sext(DenominatorBW); 962 963 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 964 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 965 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 966 Quotient = SE.getConstant(QuotientVal); 967 Remainder = SE.getConstant(RemainderVal); 968 return; 969 } 970 } 971 972 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 973 const SCEV *StartQ, *StartR, *StepQ, *StepR; 974 if (!Numerator->isAffine()) 975 return cannotDivide(Numerator); 976 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 977 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 978 // Bail out if the types do not match. 979 Type *Ty = Denominator->getType(); 980 if (Ty != StartQ->getType() || Ty != StartR->getType() || 981 Ty != StepQ->getType() || Ty != StepR->getType()) 982 return cannotDivide(Numerator); 983 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 984 Numerator->getNoWrapFlags()); 985 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 986 Numerator->getNoWrapFlags()); 987 } 988 989 void visitAddExpr(const SCEVAddExpr *Numerator) { 990 SmallVector<const SCEV *, 2> Qs, Rs; 991 Type *Ty = Denominator->getType(); 992 993 for (const SCEV *Op : Numerator->operands()) { 994 const SCEV *Q, *R; 995 divide(SE, Op, Denominator, &Q, &R); 996 997 // Bail out if types do not match. 998 if (Ty != Q->getType() || Ty != R->getType()) 999 return cannotDivide(Numerator); 1000 1001 Qs.push_back(Q); 1002 Rs.push_back(R); 1003 } 1004 1005 if (Qs.size() == 1) { 1006 Quotient = Qs[0]; 1007 Remainder = Rs[0]; 1008 return; 1009 } 1010 1011 Quotient = SE.getAddExpr(Qs); 1012 Remainder = SE.getAddExpr(Rs); 1013 } 1014 1015 void visitMulExpr(const SCEVMulExpr *Numerator) { 1016 SmallVector<const SCEV *, 2> Qs; 1017 Type *Ty = Denominator->getType(); 1018 1019 bool FoundDenominatorTerm = false; 1020 for (const SCEV *Op : Numerator->operands()) { 1021 // Bail out if types do not match. 1022 if (Ty != Op->getType()) 1023 return cannotDivide(Numerator); 1024 1025 if (FoundDenominatorTerm) { 1026 Qs.push_back(Op); 1027 continue; 1028 } 1029 1030 // Check whether Denominator divides one of the product operands. 1031 const SCEV *Q, *R; 1032 divide(SE, Op, Denominator, &Q, &R); 1033 if (!R->isZero()) { 1034 Qs.push_back(Op); 1035 continue; 1036 } 1037 1038 // Bail out if types do not match. 1039 if (Ty != Q->getType()) 1040 return cannotDivide(Numerator); 1041 1042 FoundDenominatorTerm = true; 1043 Qs.push_back(Q); 1044 } 1045 1046 if (FoundDenominatorTerm) { 1047 Remainder = Zero; 1048 if (Qs.size() == 1) 1049 Quotient = Qs[0]; 1050 else 1051 Quotient = SE.getMulExpr(Qs); 1052 return; 1053 } 1054 1055 if (!isa<SCEVUnknown>(Denominator)) 1056 return cannotDivide(Numerator); 1057 1058 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1059 ValueToValueMap RewriteMap; 1060 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1061 cast<SCEVConstant>(Zero)->getValue(); 1062 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1063 1064 if (Remainder->isZero()) { 1065 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1066 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1067 cast<SCEVConstant>(One)->getValue(); 1068 Quotient = 1069 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1070 return; 1071 } 1072 1073 // Quotient is (Numerator - Remainder) divided by Denominator. 1074 const SCEV *Q, *R; 1075 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1076 // This SCEV does not seem to simplify: fail the division here. 1077 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1078 return cannotDivide(Numerator); 1079 divide(SE, Diff, Denominator, &Q, &R); 1080 if (R != Zero) 1081 return cannotDivide(Numerator); 1082 Quotient = Q; 1083 } 1084 1085 private: 1086 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1087 const SCEV *Denominator) 1088 : SE(S), Denominator(Denominator) { 1089 Zero = SE.getZero(Denominator->getType()); 1090 One = SE.getOne(Denominator->getType()); 1091 1092 // We generally do not know how to divide Expr by Denominator. We 1093 // initialize the division to a "cannot divide" state to simplify the rest 1094 // of the code. 1095 cannotDivide(Numerator); 1096 } 1097 1098 // Convenience function for giving up on the division. We set the quotient to 1099 // be equal to zero and the remainder to be equal to the numerator. 1100 void cannotDivide(const SCEV *Numerator) { 1101 Quotient = Zero; 1102 Remainder = Numerator; 1103 } 1104 1105 ScalarEvolution &SE; 1106 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1107 }; 1108 1109 } // end anonymous namespace 1110 1111 //===----------------------------------------------------------------------===// 1112 // Simple SCEV method implementations 1113 //===----------------------------------------------------------------------===// 1114 1115 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1116 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1117 ScalarEvolution &SE, 1118 Type *ResultTy) { 1119 // Handle the simplest case efficiently. 1120 if (K == 1) 1121 return SE.getTruncateOrZeroExtend(It, ResultTy); 1122 1123 // We are using the following formula for BC(It, K): 1124 // 1125 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1126 // 1127 // Suppose, W is the bitwidth of the return value. We must be prepared for 1128 // overflow. Hence, we must assure that the result of our computation is 1129 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1130 // safe in modular arithmetic. 1131 // 1132 // However, this code doesn't use exactly that formula; the formula it uses 1133 // is something like the following, where T is the number of factors of 2 in 1134 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1135 // exponentiation: 1136 // 1137 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1138 // 1139 // This formula is trivially equivalent to the previous formula. However, 1140 // this formula can be implemented much more efficiently. The trick is that 1141 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1142 // arithmetic. To do exact division in modular arithmetic, all we have 1143 // to do is multiply by the inverse. Therefore, this step can be done at 1144 // width W. 1145 // 1146 // The next issue is how to safely do the division by 2^T. The way this 1147 // is done is by doing the multiplication step at a width of at least W + T 1148 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1149 // when we perform the division by 2^T (which is equivalent to a right shift 1150 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1151 // truncated out after the division by 2^T. 1152 // 1153 // In comparison to just directly using the first formula, this technique 1154 // is much more efficient; using the first formula requires W * K bits, 1155 // but this formula less than W + K bits. Also, the first formula requires 1156 // a division step, whereas this formula only requires multiplies and shifts. 1157 // 1158 // It doesn't matter whether the subtraction step is done in the calculation 1159 // width or the input iteration count's width; if the subtraction overflows, 1160 // the result must be zero anyway. We prefer here to do it in the width of 1161 // the induction variable because it helps a lot for certain cases; CodeGen 1162 // isn't smart enough to ignore the overflow, which leads to much less 1163 // efficient code if the width of the subtraction is wider than the native 1164 // register width. 1165 // 1166 // (It's possible to not widen at all by pulling out factors of 2 before 1167 // the multiplication; for example, K=2 can be calculated as 1168 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1169 // extra arithmetic, so it's not an obvious win, and it gets 1170 // much more complicated for K > 3.) 1171 1172 // Protection from insane SCEVs; this bound is conservative, 1173 // but it probably doesn't matter. 1174 if (K > 1000) 1175 return SE.getCouldNotCompute(); 1176 1177 unsigned W = SE.getTypeSizeInBits(ResultTy); 1178 1179 // Calculate K! / 2^T and T; we divide out the factors of two before 1180 // multiplying for calculating K! / 2^T to avoid overflow. 1181 // Other overflow doesn't matter because we only care about the bottom 1182 // W bits of the result. 1183 APInt OddFactorial(W, 1); 1184 unsigned T = 1; 1185 for (unsigned i = 3; i <= K; ++i) { 1186 APInt Mult(W, i); 1187 unsigned TwoFactors = Mult.countTrailingZeros(); 1188 T += TwoFactors; 1189 Mult.lshrInPlace(TwoFactors); 1190 OddFactorial *= Mult; 1191 } 1192 1193 // We need at least W + T bits for the multiplication step 1194 unsigned CalculationBits = W + T; 1195 1196 // Calculate 2^T, at width T+W. 1197 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1198 1199 // Calculate the multiplicative inverse of K! / 2^T; 1200 // this multiplication factor will perform the exact division by 1201 // K! / 2^T. 1202 APInt Mod = APInt::getSignedMinValue(W+1); 1203 APInt MultiplyFactor = OddFactorial.zext(W+1); 1204 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1205 MultiplyFactor = MultiplyFactor.trunc(W); 1206 1207 // Calculate the product, at width T+W 1208 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1209 CalculationBits); 1210 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1211 for (unsigned i = 1; i != K; ++i) { 1212 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1213 Dividend = SE.getMulExpr(Dividend, 1214 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1215 } 1216 1217 // Divide by 2^T 1218 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1219 1220 // Truncate the result, and divide by K! / 2^T. 1221 1222 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1223 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1224 } 1225 1226 /// Return the value of this chain of recurrences at the specified iteration 1227 /// number. We can evaluate this recurrence by multiplying each element in the 1228 /// chain by the binomial coefficient corresponding to it. In other words, we 1229 /// can evaluate {A,+,B,+,C,+,D} as: 1230 /// 1231 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1232 /// 1233 /// where BC(It, k) stands for binomial coefficient. 1234 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1235 ScalarEvolution &SE) const { 1236 const SCEV *Result = getStart(); 1237 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1238 // The computation is correct in the face of overflow provided that the 1239 // multiplication is performed _after_ the evaluation of the binomial 1240 // coefficient. 1241 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1242 if (isa<SCEVCouldNotCompute>(Coeff)) 1243 return Coeff; 1244 1245 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1246 } 1247 return Result; 1248 } 1249 1250 //===----------------------------------------------------------------------===// 1251 // SCEV Expression folder implementations 1252 //===----------------------------------------------------------------------===// 1253 1254 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1255 unsigned Depth) { 1256 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1257 "This is not a truncating conversion!"); 1258 assert(isSCEVable(Ty) && 1259 "This is not a conversion to a SCEVable type!"); 1260 Ty = getEffectiveSCEVType(Ty); 1261 1262 FoldingSetNodeID ID; 1263 ID.AddInteger(scTruncate); 1264 ID.AddPointer(Op); 1265 ID.AddPointer(Ty); 1266 void *IP = nullptr; 1267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1268 1269 // Fold if the operand is constant. 1270 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1271 return getConstant( 1272 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1273 1274 // trunc(trunc(x)) --> trunc(x) 1275 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1276 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1277 1278 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1279 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1280 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1281 1282 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1283 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1284 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1285 1286 if (Depth > MaxCastDepth) { 1287 SCEV *S = 1288 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1289 UniqueSCEVs.InsertNode(S, IP); 1290 addToLoopUseLists(S); 1291 return S; 1292 } 1293 1294 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1295 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1296 // if after transforming we have at most one truncate, not counting truncates 1297 // that replace other casts. 1298 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1299 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1300 SmallVector<const SCEV *, 4> Operands; 1301 unsigned numTruncs = 0; 1302 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1303 ++i) { 1304 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1305 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1306 numTruncs++; 1307 Operands.push_back(S); 1308 } 1309 if (numTruncs < 2) { 1310 if (isa<SCEVAddExpr>(Op)) 1311 return getAddExpr(Operands); 1312 else if (isa<SCEVMulExpr>(Op)) 1313 return getMulExpr(Operands); 1314 else 1315 llvm_unreachable("Unexpected SCEV type for Op."); 1316 } 1317 // Although we checked in the beginning that ID is not in the cache, it is 1318 // possible that during recursion and different modification ID was inserted 1319 // into the cache. So if we find it, just return it. 1320 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1321 return S; 1322 } 1323 1324 // If the input value is a chrec scev, truncate the chrec's operands. 1325 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1326 SmallVector<const SCEV *, 4> Operands; 1327 for (const SCEV *Op : AddRec->operands()) 1328 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1329 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1330 } 1331 1332 // The cast wasn't folded; create an explicit cast node. We can reuse 1333 // the existing insert position since if we get here, we won't have 1334 // made any changes which would invalidate it. 1335 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1336 Op, Ty); 1337 UniqueSCEVs.InsertNode(S, IP); 1338 addToLoopUseLists(S); 1339 return S; 1340 } 1341 1342 // Get the limit of a recurrence such that incrementing by Step cannot cause 1343 // signed overflow as long as the value of the recurrence within the 1344 // loop does not exceed this limit before incrementing. 1345 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1346 ICmpInst::Predicate *Pred, 1347 ScalarEvolution *SE) { 1348 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1349 if (SE->isKnownPositive(Step)) { 1350 *Pred = ICmpInst::ICMP_SLT; 1351 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1352 SE->getSignedRangeMax(Step)); 1353 } 1354 if (SE->isKnownNegative(Step)) { 1355 *Pred = ICmpInst::ICMP_SGT; 1356 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1357 SE->getSignedRangeMin(Step)); 1358 } 1359 return nullptr; 1360 } 1361 1362 // Get the limit of a recurrence such that incrementing by Step cannot cause 1363 // unsigned overflow as long as the value of the recurrence within the loop does 1364 // not exceed this limit before incrementing. 1365 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1366 ICmpInst::Predicate *Pred, 1367 ScalarEvolution *SE) { 1368 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1369 *Pred = ICmpInst::ICMP_ULT; 1370 1371 return SE->getConstant(APInt::getMinValue(BitWidth) - 1372 SE->getUnsignedRangeMax(Step)); 1373 } 1374 1375 namespace { 1376 1377 struct ExtendOpTraitsBase { 1378 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1379 unsigned); 1380 }; 1381 1382 // Used to make code generic over signed and unsigned overflow. 1383 template <typename ExtendOp> struct ExtendOpTraits { 1384 // Members present: 1385 // 1386 // static const SCEV::NoWrapFlags WrapType; 1387 // 1388 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1389 // 1390 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1391 // ICmpInst::Predicate *Pred, 1392 // ScalarEvolution *SE); 1393 }; 1394 1395 template <> 1396 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1397 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1398 1399 static const GetExtendExprTy GetExtendExpr; 1400 1401 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1402 ICmpInst::Predicate *Pred, 1403 ScalarEvolution *SE) { 1404 return getSignedOverflowLimitForStep(Step, Pred, SE); 1405 } 1406 }; 1407 1408 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1409 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1410 1411 template <> 1412 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1413 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1414 1415 static const GetExtendExprTy GetExtendExpr; 1416 1417 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1418 ICmpInst::Predicate *Pred, 1419 ScalarEvolution *SE) { 1420 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1421 } 1422 }; 1423 1424 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1425 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1426 1427 } // end anonymous namespace 1428 1429 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1430 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1431 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1432 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1433 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1434 // expression "Step + sext/zext(PreIncAR)" is congruent with 1435 // "sext/zext(PostIncAR)" 1436 template <typename ExtendOpTy> 1437 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1438 ScalarEvolution *SE, unsigned Depth) { 1439 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1440 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1441 1442 const Loop *L = AR->getLoop(); 1443 const SCEV *Start = AR->getStart(); 1444 const SCEV *Step = AR->getStepRecurrence(*SE); 1445 1446 // Check for a simple looking step prior to loop entry. 1447 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1448 if (!SA) 1449 return nullptr; 1450 1451 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1452 // subtraction is expensive. For this purpose, perform a quick and dirty 1453 // difference, by checking for Step in the operand list. 1454 SmallVector<const SCEV *, 4> DiffOps; 1455 for (const SCEV *Op : SA->operands()) 1456 if (Op != Step) 1457 DiffOps.push_back(Op); 1458 1459 if (DiffOps.size() == SA->getNumOperands()) 1460 return nullptr; 1461 1462 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1463 // `Step`: 1464 1465 // 1. NSW/NUW flags on the step increment. 1466 auto PreStartFlags = 1467 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1468 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1469 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1470 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1471 1472 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1473 // "S+X does not sign/unsign-overflow". 1474 // 1475 1476 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1477 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1478 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1479 return PreStart; 1480 1481 // 2. Direct overflow check on the step operation's expression. 1482 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1483 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1484 const SCEV *OperandExtendedStart = 1485 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1486 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1487 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1488 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1489 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1490 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1491 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1492 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1493 } 1494 return PreStart; 1495 } 1496 1497 // 3. Loop precondition. 1498 ICmpInst::Predicate Pred; 1499 const SCEV *OverflowLimit = 1500 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1501 1502 if (OverflowLimit && 1503 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1504 return PreStart; 1505 1506 return nullptr; 1507 } 1508 1509 // Get the normalized zero or sign extended expression for this AddRec's Start. 1510 template <typename ExtendOpTy> 1511 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1512 ScalarEvolution *SE, 1513 unsigned Depth) { 1514 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1515 1516 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1517 if (!PreStart) 1518 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1519 1520 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1521 Depth), 1522 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1523 } 1524 1525 // Try to prove away overflow by looking at "nearby" add recurrences. A 1526 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1527 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1528 // 1529 // Formally: 1530 // 1531 // {S,+,X} == {S-T,+,X} + T 1532 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1533 // 1534 // If ({S-T,+,X} + T) does not overflow ... (1) 1535 // 1536 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1537 // 1538 // If {S-T,+,X} does not overflow ... (2) 1539 // 1540 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1541 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1542 // 1543 // If (S-T)+T does not overflow ... (3) 1544 // 1545 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1546 // == {Ext(S),+,Ext(X)} == LHS 1547 // 1548 // Thus, if (1), (2) and (3) are true for some T, then 1549 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1550 // 1551 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1552 // does not overflow" restricted to the 0th iteration. Therefore we only need 1553 // to check for (1) and (2). 1554 // 1555 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1556 // is `Delta` (defined below). 1557 template <typename ExtendOpTy> 1558 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1559 const SCEV *Step, 1560 const Loop *L) { 1561 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1562 1563 // We restrict `Start` to a constant to prevent SCEV from spending too much 1564 // time here. It is correct (but more expensive) to continue with a 1565 // non-constant `Start` and do a general SCEV subtraction to compute 1566 // `PreStart` below. 1567 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1568 if (!StartC) 1569 return false; 1570 1571 APInt StartAI = StartC->getAPInt(); 1572 1573 for (unsigned Delta : {-2, -1, 1, 2}) { 1574 const SCEV *PreStart = getConstant(StartAI - Delta); 1575 1576 FoldingSetNodeID ID; 1577 ID.AddInteger(scAddRecExpr); 1578 ID.AddPointer(PreStart); 1579 ID.AddPointer(Step); 1580 ID.AddPointer(L); 1581 void *IP = nullptr; 1582 const auto *PreAR = 1583 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1584 1585 // Give up if we don't already have the add recurrence we need because 1586 // actually constructing an add recurrence is relatively expensive. 1587 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1588 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1589 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1590 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1591 DeltaS, &Pred, this); 1592 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1593 return true; 1594 } 1595 } 1596 1597 return false; 1598 } 1599 1600 // Finds an integer D for an expression (C + x + y + ...) such that the top 1601 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1602 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1603 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1604 // the (C + x + y + ...) expression is \p WholeAddExpr. 1605 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1606 const SCEVConstant *ConstantTerm, 1607 const SCEVAddExpr *WholeAddExpr) { 1608 const APInt C = ConstantTerm->getAPInt(); 1609 const unsigned BitWidth = C.getBitWidth(); 1610 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1611 uint32_t TZ = BitWidth; 1612 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1613 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1614 if (TZ) { 1615 // Set D to be as many least significant bits of C as possible while still 1616 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1617 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1618 } 1619 return APInt(BitWidth, 0); 1620 } 1621 1622 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1623 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1624 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1625 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1626 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1627 const APInt &ConstantStart, 1628 const SCEV *Step) { 1629 const unsigned BitWidth = ConstantStart.getBitWidth(); 1630 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1631 if (TZ) 1632 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1633 : ConstantStart; 1634 return APInt(BitWidth, 0); 1635 } 1636 1637 const SCEV * 1638 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1639 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1640 "This is not an extending conversion!"); 1641 assert(isSCEVable(Ty) && 1642 "This is not a conversion to a SCEVable type!"); 1643 Ty = getEffectiveSCEVType(Ty); 1644 1645 // Fold if the operand is constant. 1646 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1647 return getConstant( 1648 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1649 1650 // zext(zext(x)) --> zext(x) 1651 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1652 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1653 1654 // Before doing any expensive analysis, check to see if we've already 1655 // computed a SCEV for this Op and Ty. 1656 FoldingSetNodeID ID; 1657 ID.AddInteger(scZeroExtend); 1658 ID.AddPointer(Op); 1659 ID.AddPointer(Ty); 1660 void *IP = nullptr; 1661 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1662 if (Depth > MaxCastDepth) { 1663 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1664 Op, Ty); 1665 UniqueSCEVs.InsertNode(S, IP); 1666 addToLoopUseLists(S); 1667 return S; 1668 } 1669 1670 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1671 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1672 // It's possible the bits taken off by the truncate were all zero bits. If 1673 // so, we should be able to simplify this further. 1674 const SCEV *X = ST->getOperand(); 1675 ConstantRange CR = getUnsignedRange(X); 1676 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1677 unsigned NewBits = getTypeSizeInBits(Ty); 1678 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1679 CR.zextOrTrunc(NewBits))) 1680 return getTruncateOrZeroExtend(X, Ty, Depth); 1681 } 1682 1683 // If the input value is a chrec scev, and we can prove that the value 1684 // did not overflow the old, smaller, value, we can zero extend all of the 1685 // operands (often constants). This allows analysis of something like 1686 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1688 if (AR->isAffine()) { 1689 const SCEV *Start = AR->getStart(); 1690 const SCEV *Step = AR->getStepRecurrence(*this); 1691 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1692 const Loop *L = AR->getLoop(); 1693 1694 if (!AR->hasNoUnsignedWrap()) { 1695 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1696 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1697 } 1698 1699 // If we have special knowledge that this addrec won't overflow, 1700 // we don't need to do any further analysis. 1701 if (AR->hasNoUnsignedWrap()) 1702 return getAddRecExpr( 1703 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1704 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1705 1706 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1707 // Note that this serves two purposes: It filters out loops that are 1708 // simply not analyzable, and it covers the case where this code is 1709 // being called from within backedge-taken count analysis, such that 1710 // attempting to ask for the backedge-taken count would likely result 1711 // in infinite recursion. In the later case, the analysis code will 1712 // cope with a conservative value, and it will take care to purge 1713 // that value once it has finished. 1714 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1715 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1716 // Manually compute the final value for AR, checking for 1717 // overflow. 1718 1719 // Check whether the backedge-taken count can be losslessly casted to 1720 // the addrec's type. The count is always unsigned. 1721 const SCEV *CastedMaxBECount = 1722 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1723 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1724 CastedMaxBECount, MaxBECount->getType(), Depth); 1725 if (MaxBECount == RecastedMaxBECount) { 1726 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1727 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1728 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1729 SCEV::FlagAnyWrap, Depth + 1); 1730 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1731 SCEV::FlagAnyWrap, 1732 Depth + 1), 1733 WideTy, Depth + 1); 1734 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1735 const SCEV *WideMaxBECount = 1736 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1737 const SCEV *OperandExtendedAdd = 1738 getAddExpr(WideStart, 1739 getMulExpr(WideMaxBECount, 1740 getZeroExtendExpr(Step, WideTy, Depth + 1), 1741 SCEV::FlagAnyWrap, Depth + 1), 1742 SCEV::FlagAnyWrap, Depth + 1); 1743 if (ZAdd == OperandExtendedAdd) { 1744 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1745 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1746 // Return the expression with the addrec on the outside. 1747 return getAddRecExpr( 1748 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1749 Depth + 1), 1750 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1751 AR->getNoWrapFlags()); 1752 } 1753 // Similar to above, only this time treat the step value as signed. 1754 // This covers loops that count down. 1755 OperandExtendedAdd = 1756 getAddExpr(WideStart, 1757 getMulExpr(WideMaxBECount, 1758 getSignExtendExpr(Step, WideTy, Depth + 1), 1759 SCEV::FlagAnyWrap, Depth + 1), 1760 SCEV::FlagAnyWrap, Depth + 1); 1761 if (ZAdd == OperandExtendedAdd) { 1762 // Cache knowledge of AR NW, which is propagated to this AddRec. 1763 // Negative step causes unsigned wrap, but it still can't self-wrap. 1764 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1765 // Return the expression with the addrec on the outside. 1766 return getAddRecExpr( 1767 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1768 Depth + 1), 1769 getSignExtendExpr(Step, Ty, Depth + 1), L, 1770 AR->getNoWrapFlags()); 1771 } 1772 } 1773 } 1774 1775 // Normally, in the cases we can prove no-overflow via a 1776 // backedge guarding condition, we can also compute a backedge 1777 // taken count for the loop. The exceptions are assumptions and 1778 // guards present in the loop -- SCEV is not great at exploiting 1779 // these to compute max backedge taken counts, but can still use 1780 // these to prove lack of overflow. Use this fact to avoid 1781 // doing extra work that may not pay off. 1782 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1783 !AC.assumptions().empty()) { 1784 // If the backedge is guarded by a comparison with the pre-inc 1785 // value the addrec is safe. Also, if the entry is guarded by 1786 // a comparison with the start value and the backedge is 1787 // guarded by a comparison with the post-inc value, the addrec 1788 // is safe. 1789 if (isKnownPositive(Step)) { 1790 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1791 getUnsignedRangeMax(Step)); 1792 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1793 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1794 // Cache knowledge of AR NUW, which is propagated to this 1795 // AddRec. 1796 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1797 // Return the expression with the addrec on the outside. 1798 return getAddRecExpr( 1799 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1800 Depth + 1), 1801 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1802 AR->getNoWrapFlags()); 1803 } 1804 } else if (isKnownNegative(Step)) { 1805 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1806 getSignedRangeMin(Step)); 1807 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1808 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1809 // Cache knowledge of AR NW, which is propagated to this 1810 // AddRec. Negative step causes unsigned wrap, but it 1811 // still can't self-wrap. 1812 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1813 // Return the expression with the addrec on the outside. 1814 return getAddRecExpr( 1815 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1816 Depth + 1), 1817 getSignExtendExpr(Step, Ty, Depth + 1), L, 1818 AR->getNoWrapFlags()); 1819 } 1820 } 1821 } 1822 1823 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1824 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1825 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1826 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1827 const APInt &C = SC->getAPInt(); 1828 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1829 if (D != 0) { 1830 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1831 const SCEV *SResidual = 1832 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1833 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1834 return getAddExpr(SZExtD, SZExtR, 1835 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1836 Depth + 1); 1837 } 1838 } 1839 1840 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1842 return getAddRecExpr( 1843 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1844 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1845 } 1846 } 1847 1848 // zext(A % B) --> zext(A) % zext(B) 1849 { 1850 const SCEV *LHS; 1851 const SCEV *RHS; 1852 if (matchURem(Op, LHS, RHS)) 1853 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1854 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1855 } 1856 1857 // zext(A / B) --> zext(A) / zext(B). 1858 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1859 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1860 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1861 1862 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1863 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1864 if (SA->hasNoUnsignedWrap()) { 1865 // If the addition does not unsign overflow then we can, by definition, 1866 // commute the zero extension with the addition operation. 1867 SmallVector<const SCEV *, 4> Ops; 1868 for (const auto *Op : SA->operands()) 1869 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1870 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1871 } 1872 1873 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1874 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1875 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1876 // 1877 // Often address arithmetics contain expressions like 1878 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1879 // This transformation is useful while proving that such expressions are 1880 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1881 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1882 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1883 if (D != 0) { 1884 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1885 const SCEV *SResidual = 1886 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1887 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1888 return getAddExpr(SZExtD, SZExtR, 1889 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1890 Depth + 1); 1891 } 1892 } 1893 } 1894 1895 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1896 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1897 if (SM->hasNoUnsignedWrap()) { 1898 // If the multiply does not unsign overflow then we can, by definition, 1899 // commute the zero extension with the multiply operation. 1900 SmallVector<const SCEV *, 4> Ops; 1901 for (const auto *Op : SM->operands()) 1902 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1903 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1904 } 1905 1906 // zext(2^K * (trunc X to iN)) to iM -> 1907 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1908 // 1909 // Proof: 1910 // 1911 // zext(2^K * (trunc X to iN)) to iM 1912 // = zext((trunc X to iN) << K) to iM 1913 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1914 // (because shl removes the top K bits) 1915 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1916 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1917 // 1918 if (SM->getNumOperands() == 2) 1919 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1920 if (MulLHS->getAPInt().isPowerOf2()) 1921 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1922 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1923 MulLHS->getAPInt().logBase2(); 1924 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1925 return getMulExpr( 1926 getZeroExtendExpr(MulLHS, Ty), 1927 getZeroExtendExpr( 1928 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1929 SCEV::FlagNUW, Depth + 1); 1930 } 1931 } 1932 1933 // The cast wasn't folded; create an explicit cast node. 1934 // Recompute the insert position, as it may have been invalidated. 1935 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1936 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1937 Op, Ty); 1938 UniqueSCEVs.InsertNode(S, IP); 1939 addToLoopUseLists(S); 1940 return S; 1941 } 1942 1943 const SCEV * 1944 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1945 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1946 "This is not an extending conversion!"); 1947 assert(isSCEVable(Ty) && 1948 "This is not a conversion to a SCEVable type!"); 1949 Ty = getEffectiveSCEVType(Ty); 1950 1951 // Fold if the operand is constant. 1952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1953 return getConstant( 1954 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1955 1956 // sext(sext(x)) --> sext(x) 1957 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1958 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1959 1960 // sext(zext(x)) --> zext(x) 1961 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1962 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1963 1964 // Before doing any expensive analysis, check to see if we've already 1965 // computed a SCEV for this Op and Ty. 1966 FoldingSetNodeID ID; 1967 ID.AddInteger(scSignExtend); 1968 ID.AddPointer(Op); 1969 ID.AddPointer(Ty); 1970 void *IP = nullptr; 1971 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1972 // Limit recursion depth. 1973 if (Depth > MaxCastDepth) { 1974 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1975 Op, Ty); 1976 UniqueSCEVs.InsertNode(S, IP); 1977 addToLoopUseLists(S); 1978 return S; 1979 } 1980 1981 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1982 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1983 // It's possible the bits taken off by the truncate were all sign bits. If 1984 // so, we should be able to simplify this further. 1985 const SCEV *X = ST->getOperand(); 1986 ConstantRange CR = getSignedRange(X); 1987 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1988 unsigned NewBits = getTypeSizeInBits(Ty); 1989 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1990 CR.sextOrTrunc(NewBits))) 1991 return getTruncateOrSignExtend(X, Ty, Depth); 1992 } 1993 1994 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1995 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1996 if (SA->hasNoSignedWrap()) { 1997 // If the addition does not sign overflow then we can, by definition, 1998 // commute the sign extension with the addition operation. 1999 SmallVector<const SCEV *, 4> Ops; 2000 for (const auto *Op : SA->operands()) 2001 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2002 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2003 } 2004 2005 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2006 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2007 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2008 // 2009 // For instance, this will bring two seemingly different expressions: 2010 // 1 + sext(5 + 20 * %x + 24 * %y) and 2011 // sext(6 + 20 * %x + 24 * %y) 2012 // to the same form: 2013 // 2 + sext(4 + 20 * %x + 24 * %y) 2014 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2015 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2016 if (D != 0) { 2017 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2018 const SCEV *SResidual = 2019 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2020 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2021 return getAddExpr(SSExtD, SSExtR, 2022 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2023 Depth + 1); 2024 } 2025 } 2026 } 2027 // If the input value is a chrec scev, and we can prove that the value 2028 // did not overflow the old, smaller, value, we can sign extend all of the 2029 // operands (often constants). This allows analysis of something like 2030 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2031 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2032 if (AR->isAffine()) { 2033 const SCEV *Start = AR->getStart(); 2034 const SCEV *Step = AR->getStepRecurrence(*this); 2035 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2036 const Loop *L = AR->getLoop(); 2037 2038 if (!AR->hasNoSignedWrap()) { 2039 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2040 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2041 } 2042 2043 // If we have special knowledge that this addrec won't overflow, 2044 // we don't need to do any further analysis. 2045 if (AR->hasNoSignedWrap()) 2046 return getAddRecExpr( 2047 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2048 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2049 2050 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2051 // Note that this serves two purposes: It filters out loops that are 2052 // simply not analyzable, and it covers the case where this code is 2053 // being called from within backedge-taken count analysis, such that 2054 // attempting to ask for the backedge-taken count would likely result 2055 // in infinite recursion. In the later case, the analysis code will 2056 // cope with a conservative value, and it will take care to purge 2057 // that value once it has finished. 2058 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2059 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2060 // Manually compute the final value for AR, checking for 2061 // overflow. 2062 2063 // Check whether the backedge-taken count can be losslessly casted to 2064 // the addrec's type. The count is always unsigned. 2065 const SCEV *CastedMaxBECount = 2066 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2067 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2068 CastedMaxBECount, MaxBECount->getType(), Depth); 2069 if (MaxBECount == RecastedMaxBECount) { 2070 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2071 // Check whether Start+Step*MaxBECount has no signed overflow. 2072 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2073 SCEV::FlagAnyWrap, Depth + 1); 2074 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2075 SCEV::FlagAnyWrap, 2076 Depth + 1), 2077 WideTy, Depth + 1); 2078 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2079 const SCEV *WideMaxBECount = 2080 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2081 const SCEV *OperandExtendedAdd = 2082 getAddExpr(WideStart, 2083 getMulExpr(WideMaxBECount, 2084 getSignExtendExpr(Step, WideTy, Depth + 1), 2085 SCEV::FlagAnyWrap, Depth + 1), 2086 SCEV::FlagAnyWrap, Depth + 1); 2087 if (SAdd == OperandExtendedAdd) { 2088 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2089 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2090 // Return the expression with the addrec on the outside. 2091 return getAddRecExpr( 2092 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2093 Depth + 1), 2094 getSignExtendExpr(Step, Ty, Depth + 1), L, 2095 AR->getNoWrapFlags()); 2096 } 2097 // Similar to above, only this time treat the step value as unsigned. 2098 // This covers loops that count up with an unsigned step. 2099 OperandExtendedAdd = 2100 getAddExpr(WideStart, 2101 getMulExpr(WideMaxBECount, 2102 getZeroExtendExpr(Step, WideTy, Depth + 1), 2103 SCEV::FlagAnyWrap, Depth + 1), 2104 SCEV::FlagAnyWrap, Depth + 1); 2105 if (SAdd == OperandExtendedAdd) { 2106 // If AR wraps around then 2107 // 2108 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2109 // => SAdd != OperandExtendedAdd 2110 // 2111 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2112 // (SAdd == OperandExtendedAdd => AR is NW) 2113 2114 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2115 2116 // Return the expression with the addrec on the outside. 2117 return getAddRecExpr( 2118 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2119 Depth + 1), 2120 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2121 AR->getNoWrapFlags()); 2122 } 2123 } 2124 } 2125 2126 // Normally, in the cases we can prove no-overflow via a 2127 // backedge guarding condition, we can also compute a backedge 2128 // taken count for the loop. The exceptions are assumptions and 2129 // guards present in the loop -- SCEV is not great at exploiting 2130 // these to compute max backedge taken counts, but can still use 2131 // these to prove lack of overflow. Use this fact to avoid 2132 // doing extra work that may not pay off. 2133 2134 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2135 !AC.assumptions().empty()) { 2136 // If the backedge is guarded by a comparison with the pre-inc 2137 // value the addrec is safe. Also, if the entry is guarded by 2138 // a comparison with the start value and the backedge is 2139 // guarded by a comparison with the post-inc value, the addrec 2140 // is safe. 2141 ICmpInst::Predicate Pred; 2142 const SCEV *OverflowLimit = 2143 getSignedOverflowLimitForStep(Step, &Pred, this); 2144 if (OverflowLimit && 2145 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2146 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2147 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2148 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2149 return getAddRecExpr( 2150 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2151 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2152 } 2153 } 2154 2155 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2156 // if D + (C - D + Step * n) could be proven to not signed wrap 2157 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2158 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2159 const APInt &C = SC->getAPInt(); 2160 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2161 if (D != 0) { 2162 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2163 const SCEV *SResidual = 2164 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2165 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2166 return getAddExpr(SSExtD, SSExtR, 2167 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2168 Depth + 1); 2169 } 2170 } 2171 2172 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2173 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2174 return getAddRecExpr( 2175 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2176 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2177 } 2178 } 2179 2180 // If the input value is provably positive and we could not simplify 2181 // away the sext build a zext instead. 2182 if (isKnownNonNegative(Op)) 2183 return getZeroExtendExpr(Op, Ty, Depth + 1); 2184 2185 // The cast wasn't folded; create an explicit cast node. 2186 // Recompute the insert position, as it may have been invalidated. 2187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2188 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2189 Op, Ty); 2190 UniqueSCEVs.InsertNode(S, IP); 2191 addToLoopUseLists(S); 2192 return S; 2193 } 2194 2195 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2196 /// unspecified bits out to the given type. 2197 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2198 Type *Ty) { 2199 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2200 "This is not an extending conversion!"); 2201 assert(isSCEVable(Ty) && 2202 "This is not a conversion to a SCEVable type!"); 2203 Ty = getEffectiveSCEVType(Ty); 2204 2205 // Sign-extend negative constants. 2206 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2207 if (SC->getAPInt().isNegative()) 2208 return getSignExtendExpr(Op, Ty); 2209 2210 // Peel off a truncate cast. 2211 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2212 const SCEV *NewOp = T->getOperand(); 2213 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2214 return getAnyExtendExpr(NewOp, Ty); 2215 return getTruncateOrNoop(NewOp, Ty); 2216 } 2217 2218 // Next try a zext cast. If the cast is folded, use it. 2219 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2220 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2221 return ZExt; 2222 2223 // Next try a sext cast. If the cast is folded, use it. 2224 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2225 if (!isa<SCEVSignExtendExpr>(SExt)) 2226 return SExt; 2227 2228 // Force the cast to be folded into the operands of an addrec. 2229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2230 SmallVector<const SCEV *, 4> Ops; 2231 for (const SCEV *Op : AR->operands()) 2232 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2233 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2234 } 2235 2236 // If the expression is obviously signed, use the sext cast value. 2237 if (isa<SCEVSMaxExpr>(Op)) 2238 return SExt; 2239 2240 // Absent any other information, use the zext cast value. 2241 return ZExt; 2242 } 2243 2244 /// Process the given Ops list, which is a list of operands to be added under 2245 /// the given scale, update the given map. This is a helper function for 2246 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2247 /// that would form an add expression like this: 2248 /// 2249 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2250 /// 2251 /// where A and B are constants, update the map with these values: 2252 /// 2253 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2254 /// 2255 /// and add 13 + A*B*29 to AccumulatedConstant. 2256 /// This will allow getAddRecExpr to produce this: 2257 /// 2258 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2259 /// 2260 /// This form often exposes folding opportunities that are hidden in 2261 /// the original operand list. 2262 /// 2263 /// Return true iff it appears that any interesting folding opportunities 2264 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2265 /// the common case where no interesting opportunities are present, and 2266 /// is also used as a check to avoid infinite recursion. 2267 static bool 2268 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2269 SmallVectorImpl<const SCEV *> &NewOps, 2270 APInt &AccumulatedConstant, 2271 const SCEV *const *Ops, size_t NumOperands, 2272 const APInt &Scale, 2273 ScalarEvolution &SE) { 2274 bool Interesting = false; 2275 2276 // Iterate over the add operands. They are sorted, with constants first. 2277 unsigned i = 0; 2278 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2279 ++i; 2280 // Pull a buried constant out to the outside. 2281 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2282 Interesting = true; 2283 AccumulatedConstant += Scale * C->getAPInt(); 2284 } 2285 2286 // Next comes everything else. We're especially interested in multiplies 2287 // here, but they're in the middle, so just visit the rest with one loop. 2288 for (; i != NumOperands; ++i) { 2289 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2290 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2291 APInt NewScale = 2292 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2293 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2294 // A multiplication of a constant with another add; recurse. 2295 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2296 Interesting |= 2297 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2298 Add->op_begin(), Add->getNumOperands(), 2299 NewScale, SE); 2300 } else { 2301 // A multiplication of a constant with some other value. Update 2302 // the map. 2303 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2304 const SCEV *Key = SE.getMulExpr(MulOps); 2305 auto Pair = M.insert({Key, NewScale}); 2306 if (Pair.second) { 2307 NewOps.push_back(Pair.first->first); 2308 } else { 2309 Pair.first->second += NewScale; 2310 // The map already had an entry for this value, which may indicate 2311 // a folding opportunity. 2312 Interesting = true; 2313 } 2314 } 2315 } else { 2316 // An ordinary operand. Update the map. 2317 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2318 M.insert({Ops[i], Scale}); 2319 if (Pair.second) { 2320 NewOps.push_back(Pair.first->first); 2321 } else { 2322 Pair.first->second += Scale; 2323 // The map already had an entry for this value, which may indicate 2324 // a folding opportunity. 2325 Interesting = true; 2326 } 2327 } 2328 } 2329 2330 return Interesting; 2331 } 2332 2333 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2334 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2335 // can't-overflow flags for the operation if possible. 2336 static SCEV::NoWrapFlags 2337 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2338 const ArrayRef<const SCEV *> Ops, 2339 SCEV::NoWrapFlags Flags) { 2340 using namespace std::placeholders; 2341 2342 using OBO = OverflowingBinaryOperator; 2343 2344 bool CanAnalyze = 2345 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2346 (void)CanAnalyze; 2347 assert(CanAnalyze && "don't call from other places!"); 2348 2349 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2350 SCEV::NoWrapFlags SignOrUnsignWrap = 2351 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2352 2353 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2354 auto IsKnownNonNegative = [&](const SCEV *S) { 2355 return SE->isKnownNonNegative(S); 2356 }; 2357 2358 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2359 Flags = 2360 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2361 2362 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2363 2364 if (SignOrUnsignWrap != SignOrUnsignMask && 2365 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2366 isa<SCEVConstant>(Ops[0])) { 2367 2368 auto Opcode = [&] { 2369 switch (Type) { 2370 case scAddExpr: 2371 return Instruction::Add; 2372 case scMulExpr: 2373 return Instruction::Mul; 2374 default: 2375 llvm_unreachable("Unexpected SCEV op."); 2376 } 2377 }(); 2378 2379 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2380 2381 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2382 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2384 Opcode, C, OBO::NoSignedWrap); 2385 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2387 } 2388 2389 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2390 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2391 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2392 Opcode, C, OBO::NoUnsignedWrap); 2393 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2395 } 2396 } 2397 2398 return Flags; 2399 } 2400 2401 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2402 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2403 } 2404 2405 /// Get a canonical add expression, or something simpler if possible. 2406 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2407 SCEV::NoWrapFlags Flags, 2408 unsigned Depth) { 2409 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2410 "only nuw or nsw allowed"); 2411 assert(!Ops.empty() && "Cannot get empty add!"); 2412 if (Ops.size() == 1) return Ops[0]; 2413 #ifndef NDEBUG 2414 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2415 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2416 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2417 "SCEVAddExpr operand types don't match!"); 2418 #endif 2419 2420 // Sort by complexity, this groups all similar expression types together. 2421 GroupByComplexity(Ops, &LI, DT); 2422 2423 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2424 2425 // If there are any constants, fold them together. 2426 unsigned Idx = 0; 2427 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2428 ++Idx; 2429 assert(Idx < Ops.size()); 2430 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2431 // We found two constants, fold them together! 2432 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2433 if (Ops.size() == 2) return Ops[0]; 2434 Ops.erase(Ops.begin()+1); // Erase the folded element 2435 LHSC = cast<SCEVConstant>(Ops[0]); 2436 } 2437 2438 // If we are left with a constant zero being added, strip it off. 2439 if (LHSC->getValue()->isZero()) { 2440 Ops.erase(Ops.begin()); 2441 --Idx; 2442 } 2443 2444 if (Ops.size() == 1) return Ops[0]; 2445 } 2446 2447 // Limit recursion calls depth. 2448 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2449 return getOrCreateAddExpr(Ops, Flags); 2450 2451 // Okay, check to see if the same value occurs in the operand list more than 2452 // once. If so, merge them together into an multiply expression. Since we 2453 // sorted the list, these values are required to be adjacent. 2454 Type *Ty = Ops[0]->getType(); 2455 bool FoundMatch = false; 2456 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2457 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2458 // Scan ahead to count how many equal operands there are. 2459 unsigned Count = 2; 2460 while (i+Count != e && Ops[i+Count] == Ops[i]) 2461 ++Count; 2462 // Merge the values into a multiply. 2463 const SCEV *Scale = getConstant(Ty, Count); 2464 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2465 if (Ops.size() == Count) 2466 return Mul; 2467 Ops[i] = Mul; 2468 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2469 --i; e -= Count - 1; 2470 FoundMatch = true; 2471 } 2472 if (FoundMatch) 2473 return getAddExpr(Ops, Flags, Depth + 1); 2474 2475 // Check for truncates. If all the operands are truncated from the same 2476 // type, see if factoring out the truncate would permit the result to be 2477 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2478 // if the contents of the resulting outer trunc fold to something simple. 2479 auto FindTruncSrcType = [&]() -> Type * { 2480 // We're ultimately looking to fold an addrec of truncs and muls of only 2481 // constants and truncs, so if we find any other types of SCEV 2482 // as operands of the addrec then we bail and return nullptr here. 2483 // Otherwise, we return the type of the operand of a trunc that we find. 2484 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2485 return T->getOperand()->getType(); 2486 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2487 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2488 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2489 return T->getOperand()->getType(); 2490 } 2491 return nullptr; 2492 }; 2493 if (auto *SrcType = FindTruncSrcType()) { 2494 SmallVector<const SCEV *, 8> LargeOps; 2495 bool Ok = true; 2496 // Check all the operands to see if they can be represented in the 2497 // source type of the truncate. 2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2500 if (T->getOperand()->getType() != SrcType) { 2501 Ok = false; 2502 break; 2503 } 2504 LargeOps.push_back(T->getOperand()); 2505 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2506 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2507 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2508 SmallVector<const SCEV *, 8> LargeMulOps; 2509 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2510 if (const SCEVTruncateExpr *T = 2511 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2512 if (T->getOperand()->getType() != SrcType) { 2513 Ok = false; 2514 break; 2515 } 2516 LargeMulOps.push_back(T->getOperand()); 2517 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2518 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2519 } else { 2520 Ok = false; 2521 break; 2522 } 2523 } 2524 if (Ok) 2525 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) { 2532 // Evaluate the expression in the larger type. 2533 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2534 // If it folds to something simple, use it. Otherwise, don't. 2535 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2536 return getTruncateExpr(Fold, Ty); 2537 } 2538 } 2539 2540 // Skip past any other cast SCEVs. 2541 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2542 ++Idx; 2543 2544 // If there are add operands they would be next. 2545 if (Idx < Ops.size()) { 2546 bool DeletedAdd = false; 2547 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2548 if (Ops.size() > AddOpsInlineThreshold || 2549 Add->getNumOperands() > AddOpsInlineThreshold) 2550 break; 2551 // If we have an add, expand the add operands onto the end of the operands 2552 // list. 2553 Ops.erase(Ops.begin()+Idx); 2554 Ops.append(Add->op_begin(), Add->op_end()); 2555 DeletedAdd = true; 2556 } 2557 2558 // If we deleted at least one add, we added operands to the end of the list, 2559 // and they are not necessarily sorted. Recurse to resort and resimplify 2560 // any operands we just acquired. 2561 if (DeletedAdd) 2562 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2563 } 2564 2565 // Skip over the add expression until we get to a multiply. 2566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2567 ++Idx; 2568 2569 // Check to see if there are any folding opportunities present with 2570 // operands multiplied by constant values. 2571 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2572 uint64_t BitWidth = getTypeSizeInBits(Ty); 2573 DenseMap<const SCEV *, APInt> M; 2574 SmallVector<const SCEV *, 8> NewOps; 2575 APInt AccumulatedConstant(BitWidth, 0); 2576 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2577 Ops.data(), Ops.size(), 2578 APInt(BitWidth, 1), *this)) { 2579 struct APIntCompare { 2580 bool operator()(const APInt &LHS, const APInt &RHS) const { 2581 return LHS.ult(RHS); 2582 } 2583 }; 2584 2585 // Some interesting folding opportunity is present, so its worthwhile to 2586 // re-generate the operands list. Group the operands by constant scale, 2587 // to avoid multiplying by the same constant scale multiple times. 2588 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2589 for (const SCEV *NewOp : NewOps) 2590 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2591 // Re-generate the operands list. 2592 Ops.clear(); 2593 if (AccumulatedConstant != 0) 2594 Ops.push_back(getConstant(AccumulatedConstant)); 2595 for (auto &MulOp : MulOpLists) 2596 if (MulOp.first != 0) 2597 Ops.push_back(getMulExpr( 2598 getConstant(MulOp.first), 2599 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2600 SCEV::FlagAnyWrap, Depth + 1)); 2601 if (Ops.empty()) 2602 return getZero(Ty); 2603 if (Ops.size() == 1) 2604 return Ops[0]; 2605 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2606 } 2607 } 2608 2609 // If we are adding something to a multiply expression, make sure the 2610 // something is not already an operand of the multiply. If so, merge it into 2611 // the multiply. 2612 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2613 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2614 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2615 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2616 if (isa<SCEVConstant>(MulOpSCEV)) 2617 continue; 2618 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2619 if (MulOpSCEV == Ops[AddOp]) { 2620 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2621 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2622 if (Mul->getNumOperands() != 2) { 2623 // If the multiply has more than two operands, we must get the 2624 // Y*Z term. 2625 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2626 Mul->op_begin()+MulOp); 2627 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2628 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2629 } 2630 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2631 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2632 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2633 SCEV::FlagAnyWrap, Depth + 1); 2634 if (Ops.size() == 2) return OuterMul; 2635 if (AddOp < Idx) { 2636 Ops.erase(Ops.begin()+AddOp); 2637 Ops.erase(Ops.begin()+Idx-1); 2638 } else { 2639 Ops.erase(Ops.begin()+Idx); 2640 Ops.erase(Ops.begin()+AddOp-1); 2641 } 2642 Ops.push_back(OuterMul); 2643 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2644 } 2645 2646 // Check this multiply against other multiplies being added together. 2647 for (unsigned OtherMulIdx = Idx+1; 2648 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2649 ++OtherMulIdx) { 2650 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2651 // If MulOp occurs in OtherMul, we can fold the two multiplies 2652 // together. 2653 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2654 OMulOp != e; ++OMulOp) 2655 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2656 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2657 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2658 if (Mul->getNumOperands() != 2) { 2659 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2660 Mul->op_begin()+MulOp); 2661 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2662 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2663 } 2664 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2665 if (OtherMul->getNumOperands() != 2) { 2666 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2667 OtherMul->op_begin()+OMulOp); 2668 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2669 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2672 const SCEV *InnerMulSum = 2673 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2674 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2675 SCEV::FlagAnyWrap, Depth + 1); 2676 if (Ops.size() == 2) return OuterMul; 2677 Ops.erase(Ops.begin()+Idx); 2678 Ops.erase(Ops.begin()+OtherMulIdx-1); 2679 Ops.push_back(OuterMul); 2680 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2681 } 2682 } 2683 } 2684 } 2685 2686 // If there are any add recurrences in the operands list, see if any other 2687 // added values are loop invariant. If so, we can fold them into the 2688 // recurrence. 2689 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2690 ++Idx; 2691 2692 // Scan over all recurrences, trying to fold loop invariants into them. 2693 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2694 // Scan all of the other operands to this add and add them to the vector if 2695 // they are loop invariant w.r.t. the recurrence. 2696 SmallVector<const SCEV *, 8> LIOps; 2697 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2698 const Loop *AddRecLoop = AddRec->getLoop(); 2699 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2700 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2701 LIOps.push_back(Ops[i]); 2702 Ops.erase(Ops.begin()+i); 2703 --i; --e; 2704 } 2705 2706 // If we found some loop invariants, fold them into the recurrence. 2707 if (!LIOps.empty()) { 2708 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2709 LIOps.push_back(AddRec->getStart()); 2710 2711 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2712 AddRec->op_end()); 2713 // This follows from the fact that the no-wrap flags on the outer add 2714 // expression are applicable on the 0th iteration, when the add recurrence 2715 // will be equal to its start value. 2716 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2717 2718 // Build the new addrec. Propagate the NUW and NSW flags if both the 2719 // outer add and the inner addrec are guaranteed to have no overflow. 2720 // Always propagate NW. 2721 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2722 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2723 2724 // If all of the other operands were loop invariant, we are done. 2725 if (Ops.size() == 1) return NewRec; 2726 2727 // Otherwise, add the folded AddRec by the non-invariant parts. 2728 for (unsigned i = 0;; ++i) 2729 if (Ops[i] == AddRec) { 2730 Ops[i] = NewRec; 2731 break; 2732 } 2733 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2734 } 2735 2736 // Okay, if there weren't any loop invariants to be folded, check to see if 2737 // there are multiple AddRec's with the same loop induction variable being 2738 // added together. If so, we can fold them. 2739 for (unsigned OtherIdx = Idx+1; 2740 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2741 ++OtherIdx) { 2742 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2743 // so that the 1st found AddRecExpr is dominated by all others. 2744 assert(DT.dominates( 2745 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2746 AddRec->getLoop()->getHeader()) && 2747 "AddRecExprs are not sorted in reverse dominance order?"); 2748 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2749 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2750 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2751 AddRec->op_end()); 2752 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2753 ++OtherIdx) { 2754 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2755 if (OtherAddRec->getLoop() == AddRecLoop) { 2756 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2757 i != e; ++i) { 2758 if (i >= AddRecOps.size()) { 2759 AddRecOps.append(OtherAddRec->op_begin()+i, 2760 OtherAddRec->op_end()); 2761 break; 2762 } 2763 SmallVector<const SCEV *, 2> TwoOps = { 2764 AddRecOps[i], OtherAddRec->getOperand(i)}; 2765 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2766 } 2767 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2768 } 2769 } 2770 // Step size has changed, so we cannot guarantee no self-wraparound. 2771 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2772 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2773 } 2774 } 2775 2776 // Otherwise couldn't fold anything into this recurrence. Move onto the 2777 // next one. 2778 } 2779 2780 // Okay, it looks like we really DO need an add expr. Check to see if we 2781 // already have one, otherwise create a new one. 2782 return getOrCreateAddExpr(Ops, Flags); 2783 } 2784 2785 const SCEV * 2786 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2787 SCEV::NoWrapFlags Flags) { 2788 FoldingSetNodeID ID; 2789 ID.AddInteger(scAddExpr); 2790 for (const SCEV *Op : Ops) 2791 ID.AddPointer(Op); 2792 void *IP = nullptr; 2793 SCEVAddExpr *S = 2794 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2795 if (!S) { 2796 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2797 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2798 S = new (SCEVAllocator) 2799 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2800 UniqueSCEVs.InsertNode(S, IP); 2801 addToLoopUseLists(S); 2802 } 2803 S->setNoWrapFlags(Flags); 2804 return S; 2805 } 2806 2807 const SCEV * 2808 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2809 const Loop *L, SCEV::NoWrapFlags Flags) { 2810 FoldingSetNodeID ID; 2811 ID.AddInteger(scAddRecExpr); 2812 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2813 ID.AddPointer(Ops[i]); 2814 ID.AddPointer(L); 2815 void *IP = nullptr; 2816 SCEVAddRecExpr *S = 2817 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2818 if (!S) { 2819 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2820 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2821 S = new (SCEVAllocator) 2822 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2823 UniqueSCEVs.InsertNode(S, IP); 2824 addToLoopUseLists(S); 2825 } 2826 S->setNoWrapFlags(Flags); 2827 return S; 2828 } 2829 2830 const SCEV * 2831 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2832 SCEV::NoWrapFlags Flags) { 2833 FoldingSetNodeID ID; 2834 ID.AddInteger(scMulExpr); 2835 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2836 ID.AddPointer(Ops[i]); 2837 void *IP = nullptr; 2838 SCEVMulExpr *S = 2839 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2840 if (!S) { 2841 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2842 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2843 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2844 O, Ops.size()); 2845 UniqueSCEVs.InsertNode(S, IP); 2846 addToLoopUseLists(S); 2847 } 2848 S->setNoWrapFlags(Flags); 2849 return S; 2850 } 2851 2852 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2853 uint64_t k = i*j; 2854 if (j > 1 && k / j != i) Overflow = true; 2855 return k; 2856 } 2857 2858 /// Compute the result of "n choose k", the binomial coefficient. If an 2859 /// intermediate computation overflows, Overflow will be set and the return will 2860 /// be garbage. Overflow is not cleared on absence of overflow. 2861 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2862 // We use the multiplicative formula: 2863 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2864 // At each iteration, we take the n-th term of the numeral and divide by the 2865 // (k-n)th term of the denominator. This division will always produce an 2866 // integral result, and helps reduce the chance of overflow in the 2867 // intermediate computations. However, we can still overflow even when the 2868 // final result would fit. 2869 2870 if (n == 0 || n == k) return 1; 2871 if (k > n) return 0; 2872 2873 if (k > n/2) 2874 k = n-k; 2875 2876 uint64_t r = 1; 2877 for (uint64_t i = 1; i <= k; ++i) { 2878 r = umul_ov(r, n-(i-1), Overflow); 2879 r /= i; 2880 } 2881 return r; 2882 } 2883 2884 /// Determine if any of the operands in this SCEV are a constant or if 2885 /// any of the add or multiply expressions in this SCEV contain a constant. 2886 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2887 struct FindConstantInAddMulChain { 2888 bool FoundConstant = false; 2889 2890 bool follow(const SCEV *S) { 2891 FoundConstant |= isa<SCEVConstant>(S); 2892 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2893 } 2894 2895 bool isDone() const { 2896 return FoundConstant; 2897 } 2898 }; 2899 2900 FindConstantInAddMulChain F; 2901 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2902 ST.visitAll(StartExpr); 2903 return F.FoundConstant; 2904 } 2905 2906 /// Get a canonical multiply expression, or something simpler if possible. 2907 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2908 SCEV::NoWrapFlags Flags, 2909 unsigned Depth) { 2910 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2911 "only nuw or nsw allowed"); 2912 assert(!Ops.empty() && "Cannot get empty mul!"); 2913 if (Ops.size() == 1) return Ops[0]; 2914 #ifndef NDEBUG 2915 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2916 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2917 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2918 "SCEVMulExpr operand types don't match!"); 2919 #endif 2920 2921 // Sort by complexity, this groups all similar expression types together. 2922 GroupByComplexity(Ops, &LI, DT); 2923 2924 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2925 2926 // Limit recursion calls depth. 2927 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2928 return getOrCreateMulExpr(Ops, Flags); 2929 2930 // If there are any constants, fold them together. 2931 unsigned Idx = 0; 2932 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2933 2934 if (Ops.size() == 2) 2935 // C1*(C2+V) -> C1*C2 + C1*V 2936 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2937 // If any of Add's ops are Adds or Muls with a constant, apply this 2938 // transformation as well. 2939 // 2940 // TODO: There are some cases where this transformation is not 2941 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2942 // this transformation should be narrowed down. 2943 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2944 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2945 SCEV::FlagAnyWrap, Depth + 1), 2946 getMulExpr(LHSC, Add->getOperand(1), 2947 SCEV::FlagAnyWrap, Depth + 1), 2948 SCEV::FlagAnyWrap, Depth + 1); 2949 2950 ++Idx; 2951 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2952 // We found two constants, fold them together! 2953 ConstantInt *Fold = 2954 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2955 Ops[0] = getConstant(Fold); 2956 Ops.erase(Ops.begin()+1); // Erase the folded element 2957 if (Ops.size() == 1) return Ops[0]; 2958 LHSC = cast<SCEVConstant>(Ops[0]); 2959 } 2960 2961 // If we are left with a constant one being multiplied, strip it off. 2962 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2963 Ops.erase(Ops.begin()); 2964 --Idx; 2965 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2966 // If we have a multiply of zero, it will always be zero. 2967 return Ops[0]; 2968 } else if (Ops[0]->isAllOnesValue()) { 2969 // If we have a mul by -1 of an add, try distributing the -1 among the 2970 // add operands. 2971 if (Ops.size() == 2) { 2972 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2973 SmallVector<const SCEV *, 4> NewOps; 2974 bool AnyFolded = false; 2975 for (const SCEV *AddOp : Add->operands()) { 2976 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2977 Depth + 1); 2978 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2979 NewOps.push_back(Mul); 2980 } 2981 if (AnyFolded) 2982 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2983 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2984 // Negation preserves a recurrence's no self-wrap property. 2985 SmallVector<const SCEV *, 4> Operands; 2986 for (const SCEV *AddRecOp : AddRec->operands()) 2987 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2988 Depth + 1)); 2989 2990 return getAddRecExpr(Operands, AddRec->getLoop(), 2991 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2992 } 2993 } 2994 } 2995 2996 if (Ops.size() == 1) 2997 return Ops[0]; 2998 } 2999 3000 // Skip over the add expression until we get to a multiply. 3001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3002 ++Idx; 3003 3004 // If there are mul operands inline them all into this expression. 3005 if (Idx < Ops.size()) { 3006 bool DeletedMul = false; 3007 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3008 if (Ops.size() > MulOpsInlineThreshold) 3009 break; 3010 // If we have an mul, expand the mul operands onto the end of the 3011 // operands list. 3012 Ops.erase(Ops.begin()+Idx); 3013 Ops.append(Mul->op_begin(), Mul->op_end()); 3014 DeletedMul = true; 3015 } 3016 3017 // If we deleted at least one mul, we added operands to the end of the 3018 // list, and they are not necessarily sorted. Recurse to resort and 3019 // resimplify any operands we just acquired. 3020 if (DeletedMul) 3021 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3022 } 3023 3024 // If there are any add recurrences in the operands list, see if any other 3025 // added values are loop invariant. If so, we can fold them into the 3026 // recurrence. 3027 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3028 ++Idx; 3029 3030 // Scan over all recurrences, trying to fold loop invariants into them. 3031 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3032 // Scan all of the other operands to this mul and add them to the vector 3033 // if they are loop invariant w.r.t. the recurrence. 3034 SmallVector<const SCEV *, 8> LIOps; 3035 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3036 const Loop *AddRecLoop = AddRec->getLoop(); 3037 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3038 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3039 LIOps.push_back(Ops[i]); 3040 Ops.erase(Ops.begin()+i); 3041 --i; --e; 3042 } 3043 3044 // If we found some loop invariants, fold them into the recurrence. 3045 if (!LIOps.empty()) { 3046 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3047 SmallVector<const SCEV *, 4> NewOps; 3048 NewOps.reserve(AddRec->getNumOperands()); 3049 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3050 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3051 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3052 SCEV::FlagAnyWrap, Depth + 1)); 3053 3054 // Build the new addrec. Propagate the NUW and NSW flags if both the 3055 // outer mul and the inner addrec are guaranteed to have no overflow. 3056 // 3057 // No self-wrap cannot be guaranteed after changing the step size, but 3058 // will be inferred if either NUW or NSW is true. 3059 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3060 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3061 3062 // If all of the other operands were loop invariant, we are done. 3063 if (Ops.size() == 1) return NewRec; 3064 3065 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3066 for (unsigned i = 0;; ++i) 3067 if (Ops[i] == AddRec) { 3068 Ops[i] = NewRec; 3069 break; 3070 } 3071 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3072 } 3073 3074 // Okay, if there weren't any loop invariants to be folded, check to see 3075 // if there are multiple AddRec's with the same loop induction variable 3076 // being multiplied together. If so, we can fold them. 3077 3078 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3079 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3080 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3081 // ]]],+,...up to x=2n}. 3082 // Note that the arguments to choose() are always integers with values 3083 // known at compile time, never SCEV objects. 3084 // 3085 // The implementation avoids pointless extra computations when the two 3086 // addrec's are of different length (mathematically, it's equivalent to 3087 // an infinite stream of zeros on the right). 3088 bool OpsModified = false; 3089 for (unsigned OtherIdx = Idx+1; 3090 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3091 ++OtherIdx) { 3092 const SCEVAddRecExpr *OtherAddRec = 3093 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3094 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3095 continue; 3096 3097 // Limit max number of arguments to avoid creation of unreasonably big 3098 // SCEVAddRecs with very complex operands. 3099 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3100 MaxAddRecSize || isHugeExpression(AddRec) || 3101 isHugeExpression(OtherAddRec)) 3102 continue; 3103 3104 bool Overflow = false; 3105 Type *Ty = AddRec->getType(); 3106 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3107 SmallVector<const SCEV*, 7> AddRecOps; 3108 for (int x = 0, xe = AddRec->getNumOperands() + 3109 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3110 SmallVector <const SCEV *, 7> SumOps; 3111 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3112 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3113 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3114 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3115 z < ze && !Overflow; ++z) { 3116 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3117 uint64_t Coeff; 3118 if (LargerThan64Bits) 3119 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3120 else 3121 Coeff = Coeff1*Coeff2; 3122 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3123 const SCEV *Term1 = AddRec->getOperand(y-z); 3124 const SCEV *Term2 = OtherAddRec->getOperand(z); 3125 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3126 SCEV::FlagAnyWrap, Depth + 1)); 3127 } 3128 } 3129 if (SumOps.empty()) 3130 SumOps.push_back(getZero(Ty)); 3131 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3132 } 3133 if (!Overflow) { 3134 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3135 SCEV::FlagAnyWrap); 3136 if (Ops.size() == 2) return NewAddRec; 3137 Ops[Idx] = NewAddRec; 3138 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3139 OpsModified = true; 3140 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3141 if (!AddRec) 3142 break; 3143 } 3144 } 3145 if (OpsModified) 3146 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3147 3148 // Otherwise couldn't fold anything into this recurrence. Move onto the 3149 // next one. 3150 } 3151 3152 // Okay, it looks like we really DO need an mul expr. Check to see if we 3153 // already have one, otherwise create a new one. 3154 return getOrCreateMulExpr(Ops, Flags); 3155 } 3156 3157 /// Represents an unsigned remainder expression based on unsigned division. 3158 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3159 const SCEV *RHS) { 3160 assert(getEffectiveSCEVType(LHS->getType()) == 3161 getEffectiveSCEVType(RHS->getType()) && 3162 "SCEVURemExpr operand types don't match!"); 3163 3164 // Short-circuit easy cases 3165 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3166 // If constant is one, the result is trivial 3167 if (RHSC->getValue()->isOne()) 3168 return getZero(LHS->getType()); // X urem 1 --> 0 3169 3170 // If constant is a power of two, fold into a zext(trunc(LHS)). 3171 if (RHSC->getAPInt().isPowerOf2()) { 3172 Type *FullTy = LHS->getType(); 3173 Type *TruncTy = 3174 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3175 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3176 } 3177 } 3178 3179 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3180 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3181 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3182 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3183 } 3184 3185 /// Get a canonical unsigned division expression, or something simpler if 3186 /// possible. 3187 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3188 const SCEV *RHS) { 3189 assert(getEffectiveSCEVType(LHS->getType()) == 3190 getEffectiveSCEVType(RHS->getType()) && 3191 "SCEVUDivExpr operand types don't match!"); 3192 3193 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3194 if (RHSC->getValue()->isOne()) 3195 return LHS; // X udiv 1 --> x 3196 // If the denominator is zero, the result of the udiv is undefined. Don't 3197 // try to analyze it, because the resolution chosen here may differ from 3198 // the resolution chosen in other parts of the compiler. 3199 if (!RHSC->getValue()->isZero()) { 3200 // Determine if the division can be folded into the operands of 3201 // its operands. 3202 // TODO: Generalize this to non-constants by using known-bits information. 3203 Type *Ty = LHS->getType(); 3204 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3205 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3206 // For non-power-of-two values, effectively round the value up to the 3207 // nearest power of two. 3208 if (!RHSC->getAPInt().isPowerOf2()) 3209 ++MaxShiftAmt; 3210 IntegerType *ExtTy = 3211 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3213 if (const SCEVConstant *Step = 3214 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3215 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3216 const APInt &StepInt = Step->getAPInt(); 3217 const APInt &DivInt = RHSC->getAPInt(); 3218 if (!StepInt.urem(DivInt) && 3219 getZeroExtendExpr(AR, ExtTy) == 3220 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3221 getZeroExtendExpr(Step, ExtTy), 3222 AR->getLoop(), SCEV::FlagAnyWrap)) { 3223 SmallVector<const SCEV *, 4> Operands; 3224 for (const SCEV *Op : AR->operands()) 3225 Operands.push_back(getUDivExpr(Op, RHS)); 3226 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3227 } 3228 /// Get a canonical UDivExpr for a recurrence. 3229 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3230 // We can currently only fold X%N if X is constant. 3231 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3232 if (StartC && !DivInt.urem(StepInt) && 3233 getZeroExtendExpr(AR, ExtTy) == 3234 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3235 getZeroExtendExpr(Step, ExtTy), 3236 AR->getLoop(), SCEV::FlagAnyWrap)) { 3237 const APInt &StartInt = StartC->getAPInt(); 3238 const APInt &StartRem = StartInt.urem(StepInt); 3239 if (StartRem != 0) 3240 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3241 AR->getLoop(), SCEV::FlagNW); 3242 } 3243 } 3244 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3245 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3246 SmallVector<const SCEV *, 4> Operands; 3247 for (const SCEV *Op : M->operands()) 3248 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3249 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3250 // Find an operand that's safely divisible. 3251 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3252 const SCEV *Op = M->getOperand(i); 3253 const SCEV *Div = getUDivExpr(Op, RHSC); 3254 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3255 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3256 M->op_end()); 3257 Operands[i] = Div; 3258 return getMulExpr(Operands); 3259 } 3260 } 3261 } 3262 3263 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3264 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3265 if (auto *DivisorConstant = 3266 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3267 bool Overflow = false; 3268 APInt NewRHS = 3269 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3270 if (Overflow) { 3271 return getConstant(RHSC->getType(), 0, false); 3272 } 3273 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3274 } 3275 } 3276 3277 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3278 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3279 SmallVector<const SCEV *, 4> Operands; 3280 for (const SCEV *Op : A->operands()) 3281 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3282 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3283 Operands.clear(); 3284 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3285 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3286 if (isa<SCEVUDivExpr>(Op) || 3287 getMulExpr(Op, RHS) != A->getOperand(i)) 3288 break; 3289 Operands.push_back(Op); 3290 } 3291 if (Operands.size() == A->getNumOperands()) 3292 return getAddExpr(Operands); 3293 } 3294 } 3295 3296 // Fold if both operands are constant. 3297 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3298 Constant *LHSCV = LHSC->getValue(); 3299 Constant *RHSCV = RHSC->getValue(); 3300 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3301 RHSCV))); 3302 } 3303 } 3304 } 3305 3306 FoldingSetNodeID ID; 3307 ID.AddInteger(scUDivExpr); 3308 ID.AddPointer(LHS); 3309 ID.AddPointer(RHS); 3310 void *IP = nullptr; 3311 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3312 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3313 LHS, RHS); 3314 UniqueSCEVs.InsertNode(S, IP); 3315 addToLoopUseLists(S); 3316 return S; 3317 } 3318 3319 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3320 APInt A = C1->getAPInt().abs(); 3321 APInt B = C2->getAPInt().abs(); 3322 uint32_t ABW = A.getBitWidth(); 3323 uint32_t BBW = B.getBitWidth(); 3324 3325 if (ABW > BBW) 3326 B = B.zext(ABW); 3327 else if (ABW < BBW) 3328 A = A.zext(BBW); 3329 3330 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3331 } 3332 3333 /// Get a canonical unsigned division expression, or something simpler if 3334 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3335 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3336 /// it's not exact because the udiv may be clearing bits. 3337 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3338 const SCEV *RHS) { 3339 // TODO: we could try to find factors in all sorts of things, but for now we 3340 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3341 // end of this file for inspiration. 3342 3343 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3344 if (!Mul || !Mul->hasNoUnsignedWrap()) 3345 return getUDivExpr(LHS, RHS); 3346 3347 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3348 // If the mulexpr multiplies by a constant, then that constant must be the 3349 // first element of the mulexpr. 3350 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3351 if (LHSCst == RHSCst) { 3352 SmallVector<const SCEV *, 2> Operands; 3353 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3354 return getMulExpr(Operands); 3355 } 3356 3357 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3358 // that there's a factor provided by one of the other terms. We need to 3359 // check. 3360 APInt Factor = gcd(LHSCst, RHSCst); 3361 if (!Factor.isIntN(1)) { 3362 LHSCst = 3363 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3364 RHSCst = 3365 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3366 SmallVector<const SCEV *, 2> Operands; 3367 Operands.push_back(LHSCst); 3368 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3369 LHS = getMulExpr(Operands); 3370 RHS = RHSCst; 3371 Mul = dyn_cast<SCEVMulExpr>(LHS); 3372 if (!Mul) 3373 return getUDivExactExpr(LHS, RHS); 3374 } 3375 } 3376 } 3377 3378 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3379 if (Mul->getOperand(i) == RHS) { 3380 SmallVector<const SCEV *, 2> Operands; 3381 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3382 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3383 return getMulExpr(Operands); 3384 } 3385 } 3386 3387 return getUDivExpr(LHS, RHS); 3388 } 3389 3390 /// Get an add recurrence expression for the specified loop. Simplify the 3391 /// expression as much as possible. 3392 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3393 const Loop *L, 3394 SCEV::NoWrapFlags Flags) { 3395 SmallVector<const SCEV *, 4> Operands; 3396 Operands.push_back(Start); 3397 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3398 if (StepChrec->getLoop() == L) { 3399 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3400 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3401 } 3402 3403 Operands.push_back(Step); 3404 return getAddRecExpr(Operands, L, Flags); 3405 } 3406 3407 /// Get an add recurrence expression for the specified loop. Simplify the 3408 /// expression as much as possible. 3409 const SCEV * 3410 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3411 const Loop *L, SCEV::NoWrapFlags Flags) { 3412 if (Operands.size() == 1) return Operands[0]; 3413 #ifndef NDEBUG 3414 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3415 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3416 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3417 "SCEVAddRecExpr operand types don't match!"); 3418 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3419 assert(isLoopInvariant(Operands[i], L) && 3420 "SCEVAddRecExpr operand is not loop-invariant!"); 3421 #endif 3422 3423 if (Operands.back()->isZero()) { 3424 Operands.pop_back(); 3425 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3426 } 3427 3428 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3429 // use that information to infer NUW and NSW flags. However, computing a 3430 // BE count requires calling getAddRecExpr, so we may not yet have a 3431 // meaningful BE count at this point (and if we don't, we'd be stuck 3432 // with a SCEVCouldNotCompute as the cached BE count). 3433 3434 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3435 3436 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3437 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3438 const Loop *NestedLoop = NestedAR->getLoop(); 3439 if (L->contains(NestedLoop) 3440 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3441 : (!NestedLoop->contains(L) && 3442 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3443 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3444 NestedAR->op_end()); 3445 Operands[0] = NestedAR->getStart(); 3446 // AddRecs require their operands be loop-invariant with respect to their 3447 // loops. Don't perform this transformation if it would break this 3448 // requirement. 3449 bool AllInvariant = all_of( 3450 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3451 3452 if (AllInvariant) { 3453 // Create a recurrence for the outer loop with the same step size. 3454 // 3455 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3456 // inner recurrence has the same property. 3457 SCEV::NoWrapFlags OuterFlags = 3458 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3459 3460 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3461 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3462 return isLoopInvariant(Op, NestedLoop); 3463 }); 3464 3465 if (AllInvariant) { 3466 // Ok, both add recurrences are valid after the transformation. 3467 // 3468 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3469 // the outer recurrence has the same property. 3470 SCEV::NoWrapFlags InnerFlags = 3471 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3472 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3473 } 3474 } 3475 // Reset Operands to its original state. 3476 Operands[0] = NestedAR; 3477 } 3478 } 3479 3480 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3481 // already have one, otherwise create a new one. 3482 return getOrCreateAddRecExpr(Operands, L, Flags); 3483 } 3484 3485 const SCEV * 3486 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3487 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3488 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3489 // getSCEV(Base)->getType() has the same address space as Base->getType() 3490 // because SCEV::getType() preserves the address space. 3491 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3492 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3493 // instruction to its SCEV, because the Instruction may be guarded by control 3494 // flow and the no-overflow bits may not be valid for the expression in any 3495 // context. This can be fixed similarly to how these flags are handled for 3496 // adds. 3497 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3498 : SCEV::FlagAnyWrap; 3499 3500 const SCEV *TotalOffset = getZero(IntPtrTy); 3501 // The array size is unimportant. The first thing we do on CurTy is getting 3502 // its element type. 3503 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3504 for (const SCEV *IndexExpr : IndexExprs) { 3505 // Compute the (potentially symbolic) offset in bytes for this index. 3506 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3507 // For a struct, add the member offset. 3508 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3509 unsigned FieldNo = Index->getZExtValue(); 3510 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3511 3512 // Add the field offset to the running total offset. 3513 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3514 3515 // Update CurTy to the type of the field at Index. 3516 CurTy = STy->getTypeAtIndex(Index); 3517 } else { 3518 // Update CurTy to its element type. 3519 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3520 // For an array, add the element offset, explicitly scaled. 3521 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3522 // Getelementptr indices are signed. 3523 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3524 3525 // Multiply the index by the element size to compute the element offset. 3526 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3527 3528 // Add the element offset to the running total offset. 3529 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3530 } 3531 } 3532 3533 // Add the total offset from all the GEP indices to the base. 3534 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3535 } 3536 3537 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3538 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3539 ArrayRef<const SCEV *> Ops) { 3540 FoldingSetNodeID ID; 3541 void *IP = nullptr; 3542 ID.AddInteger(SCEVType); 3543 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3544 ID.AddPointer(Ops[i]); 3545 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3546 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3547 } 3548 3549 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3550 SmallVectorImpl<const SCEV *> &Ops) { 3551 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3552 if (Ops.size() == 1) return Ops[0]; 3553 #ifndef NDEBUG 3554 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3555 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3556 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3557 "Operand types don't match!"); 3558 #endif 3559 3560 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3561 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3562 3563 // Sort by complexity, this groups all similar expression types together. 3564 GroupByComplexity(Ops, &LI, DT); 3565 3566 // Check if we have created the same expression before. 3567 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3568 return S; 3569 } 3570 3571 // If there are any constants, fold them together. 3572 unsigned Idx = 0; 3573 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3574 ++Idx; 3575 assert(Idx < Ops.size()); 3576 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3577 if (Kind == scSMaxExpr) 3578 return APIntOps::smax(LHS, RHS); 3579 else if (Kind == scSMinExpr) 3580 return APIntOps::smin(LHS, RHS); 3581 else if (Kind == scUMaxExpr) 3582 return APIntOps::umax(LHS, RHS); 3583 else if (Kind == scUMinExpr) 3584 return APIntOps::umin(LHS, RHS); 3585 llvm_unreachable("Unknown SCEV min/max opcode"); 3586 }; 3587 3588 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3589 // We found two constants, fold them together! 3590 ConstantInt *Fold = ConstantInt::get( 3591 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3592 Ops[0] = getConstant(Fold); 3593 Ops.erase(Ops.begin()+1); // Erase the folded element 3594 if (Ops.size() == 1) return Ops[0]; 3595 LHSC = cast<SCEVConstant>(Ops[0]); 3596 } 3597 3598 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3599 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3600 3601 if (IsMax ? IsMinV : IsMaxV) { 3602 // If we are left with a constant minimum(/maximum)-int, strip it off. 3603 Ops.erase(Ops.begin()); 3604 --Idx; 3605 } else if (IsMax ? IsMaxV : IsMinV) { 3606 // If we have a max(/min) with a constant maximum(/minimum)-int, 3607 // it will always be the extremum. 3608 return LHSC; 3609 } 3610 3611 if (Ops.size() == 1) return Ops[0]; 3612 } 3613 3614 // Find the first operation of the same kind 3615 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3616 ++Idx; 3617 3618 // Check to see if one of the operands is of the same kind. If so, expand its 3619 // operands onto our operand list, and recurse to simplify. 3620 if (Idx < Ops.size()) { 3621 bool DeletedAny = false; 3622 while (Ops[Idx]->getSCEVType() == Kind) { 3623 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3624 Ops.erase(Ops.begin()+Idx); 3625 Ops.append(SMME->op_begin(), SMME->op_end()); 3626 DeletedAny = true; 3627 } 3628 3629 if (DeletedAny) 3630 return getMinMaxExpr(Kind, Ops); 3631 } 3632 3633 // Okay, check to see if the same value occurs in the operand list twice. If 3634 // so, delete one. Since we sorted the list, these values are required to 3635 // be adjacent. 3636 llvm::CmpInst::Predicate GEPred = 3637 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3638 llvm::CmpInst::Predicate LEPred = 3639 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3640 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3641 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3642 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3643 if (Ops[i] == Ops[i + 1] || 3644 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3645 // X op Y op Y --> X op Y 3646 // X op Y --> X, if we know X, Y are ordered appropriately 3647 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3648 --i; 3649 --e; 3650 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3651 Ops[i + 1])) { 3652 // X op Y --> Y, if we know X, Y are ordered appropriately 3653 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3654 --i; 3655 --e; 3656 } 3657 } 3658 3659 if (Ops.size() == 1) return Ops[0]; 3660 3661 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3662 3663 // Okay, it looks like we really DO need an expr. Check to see if we 3664 // already have one, otherwise create a new one. 3665 const SCEV *ExistingSCEV; 3666 FoldingSetNodeID ID; 3667 void *IP; 3668 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3669 if (ExistingSCEV) 3670 return ExistingSCEV; 3671 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3672 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3673 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3674 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3675 3676 UniqueSCEVs.InsertNode(S, IP); 3677 addToLoopUseLists(S); 3678 return S; 3679 } 3680 3681 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3682 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3683 return getSMaxExpr(Ops); 3684 } 3685 3686 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3687 return getMinMaxExpr(scSMaxExpr, Ops); 3688 } 3689 3690 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3691 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3692 return getUMaxExpr(Ops); 3693 } 3694 3695 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3696 return getMinMaxExpr(scUMaxExpr, Ops); 3697 } 3698 3699 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3700 const SCEV *RHS) { 3701 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3702 return getSMinExpr(Ops); 3703 } 3704 3705 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3706 return getMinMaxExpr(scSMinExpr, Ops); 3707 } 3708 3709 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3710 const SCEV *RHS) { 3711 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3712 return getUMinExpr(Ops); 3713 } 3714 3715 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3716 return getMinMaxExpr(scUMinExpr, Ops); 3717 } 3718 3719 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3720 // We can bypass creating a target-independent 3721 // constant expression and then folding it back into a ConstantInt. 3722 // This is just a compile-time optimization. 3723 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3724 } 3725 3726 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3727 StructType *STy, 3728 unsigned FieldNo) { 3729 // We can bypass creating a target-independent 3730 // constant expression and then folding it back into a ConstantInt. 3731 // This is just a compile-time optimization. 3732 return getConstant( 3733 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3734 } 3735 3736 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3737 // Don't attempt to do anything other than create a SCEVUnknown object 3738 // here. createSCEV only calls getUnknown after checking for all other 3739 // interesting possibilities, and any other code that calls getUnknown 3740 // is doing so in order to hide a value from SCEV canonicalization. 3741 3742 FoldingSetNodeID ID; 3743 ID.AddInteger(scUnknown); 3744 ID.AddPointer(V); 3745 void *IP = nullptr; 3746 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3747 assert(cast<SCEVUnknown>(S)->getValue() == V && 3748 "Stale SCEVUnknown in uniquing map!"); 3749 return S; 3750 } 3751 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3752 FirstUnknown); 3753 FirstUnknown = cast<SCEVUnknown>(S); 3754 UniqueSCEVs.InsertNode(S, IP); 3755 return S; 3756 } 3757 3758 //===----------------------------------------------------------------------===// 3759 // Basic SCEV Analysis and PHI Idiom Recognition Code 3760 // 3761 3762 /// Test if values of the given type are analyzable within the SCEV 3763 /// framework. This primarily includes integer types, and it can optionally 3764 /// include pointer types if the ScalarEvolution class has access to 3765 /// target-specific information. 3766 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3767 // Integers and pointers are always SCEVable. 3768 return Ty->isIntOrPtrTy(); 3769 } 3770 3771 /// Return the size in bits of the specified type, for which isSCEVable must 3772 /// return true. 3773 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3774 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3775 if (Ty->isPointerTy()) 3776 return getDataLayout().getIndexTypeSizeInBits(Ty); 3777 return getDataLayout().getTypeSizeInBits(Ty); 3778 } 3779 3780 /// Return a type with the same bitwidth as the given type and which represents 3781 /// how SCEV will treat the given type, for which isSCEVable must return 3782 /// true. For pointer types, this is the pointer-sized integer type. 3783 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3784 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3785 3786 if (Ty->isIntegerTy()) 3787 return Ty; 3788 3789 // The only other support type is pointer. 3790 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3791 return getDataLayout().getIntPtrType(Ty); 3792 } 3793 3794 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3795 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3796 } 3797 3798 const SCEV *ScalarEvolution::getCouldNotCompute() { 3799 return CouldNotCompute.get(); 3800 } 3801 3802 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3803 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3804 auto *SU = dyn_cast<SCEVUnknown>(S); 3805 return SU && SU->getValue() == nullptr; 3806 }); 3807 3808 return !ContainsNulls; 3809 } 3810 3811 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3812 HasRecMapType::iterator I = HasRecMap.find(S); 3813 if (I != HasRecMap.end()) 3814 return I->second; 3815 3816 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3817 HasRecMap.insert({S, FoundAddRec}); 3818 return FoundAddRec; 3819 } 3820 3821 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3822 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3823 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3824 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3825 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3826 if (!Add) 3827 return {S, nullptr}; 3828 3829 if (Add->getNumOperands() != 2) 3830 return {S, nullptr}; 3831 3832 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3833 if (!ConstOp) 3834 return {S, nullptr}; 3835 3836 return {Add->getOperand(1), ConstOp->getValue()}; 3837 } 3838 3839 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3840 /// by the value and offset from any ValueOffsetPair in the set. 3841 SetVector<ScalarEvolution::ValueOffsetPair> * 3842 ScalarEvolution::getSCEVValues(const SCEV *S) { 3843 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3844 if (SI == ExprValueMap.end()) 3845 return nullptr; 3846 #ifndef NDEBUG 3847 if (VerifySCEVMap) { 3848 // Check there is no dangling Value in the set returned. 3849 for (const auto &VE : SI->second) 3850 assert(ValueExprMap.count(VE.first)); 3851 } 3852 #endif 3853 return &SI->second; 3854 } 3855 3856 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3857 /// cannot be used separately. eraseValueFromMap should be used to remove 3858 /// V from ValueExprMap and ExprValueMap at the same time. 3859 void ScalarEvolution::eraseValueFromMap(Value *V) { 3860 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3861 if (I != ValueExprMap.end()) { 3862 const SCEV *S = I->second; 3863 // Remove {V, 0} from the set of ExprValueMap[S] 3864 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3865 SV->remove({V, nullptr}); 3866 3867 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3868 const SCEV *Stripped; 3869 ConstantInt *Offset; 3870 std::tie(Stripped, Offset) = splitAddExpr(S); 3871 if (Offset != nullptr) { 3872 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3873 SV->remove({V, Offset}); 3874 } 3875 ValueExprMap.erase(V); 3876 } 3877 } 3878 3879 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3880 /// TODO: In reality it is better to check the poison recursively 3881 /// but this is better than nothing. 3882 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3883 if (auto *I = dyn_cast<Instruction>(V)) { 3884 if (isa<OverflowingBinaryOperator>(I)) { 3885 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3886 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3887 return true; 3888 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3889 return true; 3890 } 3891 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3892 return true; 3893 } 3894 return false; 3895 } 3896 3897 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3898 /// create a new one. 3899 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3900 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3901 3902 const SCEV *S = getExistingSCEV(V); 3903 if (S == nullptr) { 3904 S = createSCEV(V); 3905 // During PHI resolution, it is possible to create two SCEVs for the same 3906 // V, so it is needed to double check whether V->S is inserted into 3907 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3908 std::pair<ValueExprMapType::iterator, bool> Pair = 3909 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3910 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3911 ExprValueMap[S].insert({V, nullptr}); 3912 3913 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3914 // ExprValueMap. 3915 const SCEV *Stripped = S; 3916 ConstantInt *Offset = nullptr; 3917 std::tie(Stripped, Offset) = splitAddExpr(S); 3918 // If stripped is SCEVUnknown, don't bother to save 3919 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3920 // increase the complexity of the expansion code. 3921 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3922 // because it may generate add/sub instead of GEP in SCEV expansion. 3923 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3924 !isa<GetElementPtrInst>(V)) 3925 ExprValueMap[Stripped].insert({V, Offset}); 3926 } 3927 } 3928 return S; 3929 } 3930 3931 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3932 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3933 3934 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3935 if (I != ValueExprMap.end()) { 3936 const SCEV *S = I->second; 3937 if (checkValidity(S)) 3938 return S; 3939 eraseValueFromMap(V); 3940 forgetMemoizedResults(S); 3941 } 3942 return nullptr; 3943 } 3944 3945 /// Return a SCEV corresponding to -V = -1*V 3946 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3947 SCEV::NoWrapFlags Flags) { 3948 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3949 return getConstant( 3950 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3951 3952 Type *Ty = V->getType(); 3953 Ty = getEffectiveSCEVType(Ty); 3954 return getMulExpr( 3955 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3956 } 3957 3958 /// If Expr computes ~A, return A else return nullptr 3959 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3960 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3961 if (!Add || Add->getNumOperands() != 2 || 3962 !Add->getOperand(0)->isAllOnesValue()) 3963 return nullptr; 3964 3965 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3966 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3967 !AddRHS->getOperand(0)->isAllOnesValue()) 3968 return nullptr; 3969 3970 return AddRHS->getOperand(1); 3971 } 3972 3973 /// Return a SCEV corresponding to ~V = -1-V 3974 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3975 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3976 return getConstant( 3977 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3978 3979 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3980 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3981 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3982 SmallVector<const SCEV *, 2> MatchedOperands; 3983 for (const SCEV *Operand : MME->operands()) { 3984 const SCEV *Matched = MatchNotExpr(Operand); 3985 if (!Matched) 3986 return (const SCEV *)nullptr; 3987 MatchedOperands.push_back(Matched); 3988 } 3989 return getMinMaxExpr( 3990 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3991 MatchedOperands); 3992 }; 3993 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3994 return Replaced; 3995 } 3996 3997 Type *Ty = V->getType(); 3998 Ty = getEffectiveSCEVType(Ty); 3999 const SCEV *AllOnes = 4000 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4001 return getMinusSCEV(AllOnes, V); 4002 } 4003 4004 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4005 SCEV::NoWrapFlags Flags, 4006 unsigned Depth) { 4007 // Fast path: X - X --> 0. 4008 if (LHS == RHS) 4009 return getZero(LHS->getType()); 4010 4011 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4012 // makes it so that we cannot make much use of NUW. 4013 auto AddFlags = SCEV::FlagAnyWrap; 4014 const bool RHSIsNotMinSigned = 4015 !getSignedRangeMin(RHS).isMinSignedValue(); 4016 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4017 // Let M be the minimum representable signed value. Then (-1)*RHS 4018 // signed-wraps if and only if RHS is M. That can happen even for 4019 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4020 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4021 // (-1)*RHS, we need to prove that RHS != M. 4022 // 4023 // If LHS is non-negative and we know that LHS - RHS does not 4024 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4025 // either by proving that RHS > M or that LHS >= 0. 4026 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4027 AddFlags = SCEV::FlagNSW; 4028 } 4029 } 4030 4031 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4032 // RHS is NSW and LHS >= 0. 4033 // 4034 // The difficulty here is that the NSW flag may have been proven 4035 // relative to a loop that is to be found in a recurrence in LHS and 4036 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4037 // larger scope than intended. 4038 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4039 4040 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4041 } 4042 4043 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4044 unsigned Depth) { 4045 Type *SrcTy = V->getType(); 4046 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4047 "Cannot truncate or zero extend with non-integer arguments!"); 4048 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4049 return V; // No conversion 4050 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4051 return getTruncateExpr(V, Ty, Depth); 4052 return getZeroExtendExpr(V, Ty, Depth); 4053 } 4054 4055 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4056 unsigned Depth) { 4057 Type *SrcTy = V->getType(); 4058 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4059 "Cannot truncate or zero extend with non-integer arguments!"); 4060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4061 return V; // No conversion 4062 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4063 return getTruncateExpr(V, Ty, Depth); 4064 return getSignExtendExpr(V, Ty, Depth); 4065 } 4066 4067 const SCEV * 4068 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4069 Type *SrcTy = V->getType(); 4070 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4071 "Cannot noop or zero extend with non-integer arguments!"); 4072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4073 "getNoopOrZeroExtend cannot truncate!"); 4074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4075 return V; // No conversion 4076 return getZeroExtendExpr(V, Ty); 4077 } 4078 4079 const SCEV * 4080 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4081 Type *SrcTy = V->getType(); 4082 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4083 "Cannot noop or sign extend with non-integer arguments!"); 4084 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4085 "getNoopOrSignExtend cannot truncate!"); 4086 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4087 return V; // No conversion 4088 return getSignExtendExpr(V, Ty); 4089 } 4090 4091 const SCEV * 4092 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4093 Type *SrcTy = V->getType(); 4094 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4095 "Cannot noop or any extend with non-integer arguments!"); 4096 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4097 "getNoopOrAnyExtend cannot truncate!"); 4098 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4099 return V; // No conversion 4100 return getAnyExtendExpr(V, Ty); 4101 } 4102 4103 const SCEV * 4104 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4105 Type *SrcTy = V->getType(); 4106 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4107 "Cannot truncate or noop with non-integer arguments!"); 4108 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4109 "getTruncateOrNoop cannot extend!"); 4110 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4111 return V; // No conversion 4112 return getTruncateExpr(V, Ty); 4113 } 4114 4115 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4116 const SCEV *RHS) { 4117 const SCEV *PromotedLHS = LHS; 4118 const SCEV *PromotedRHS = RHS; 4119 4120 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4121 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4122 else 4123 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4124 4125 return getUMaxExpr(PromotedLHS, PromotedRHS); 4126 } 4127 4128 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4129 const SCEV *RHS) { 4130 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4131 return getUMinFromMismatchedTypes(Ops); 4132 } 4133 4134 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4135 SmallVectorImpl<const SCEV *> &Ops) { 4136 assert(!Ops.empty() && "At least one operand must be!"); 4137 // Trivial case. 4138 if (Ops.size() == 1) 4139 return Ops[0]; 4140 4141 // Find the max type first. 4142 Type *MaxType = nullptr; 4143 for (auto *S : Ops) 4144 if (MaxType) 4145 MaxType = getWiderType(MaxType, S->getType()); 4146 else 4147 MaxType = S->getType(); 4148 4149 // Extend all ops to max type. 4150 SmallVector<const SCEV *, 2> PromotedOps; 4151 for (auto *S : Ops) 4152 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4153 4154 // Generate umin. 4155 return getUMinExpr(PromotedOps); 4156 } 4157 4158 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4159 // A pointer operand may evaluate to a nonpointer expression, such as null. 4160 if (!V->getType()->isPointerTy()) 4161 return V; 4162 4163 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4164 return getPointerBase(Cast->getOperand()); 4165 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4166 const SCEV *PtrOp = nullptr; 4167 for (const SCEV *NAryOp : NAry->operands()) { 4168 if (NAryOp->getType()->isPointerTy()) { 4169 // Cannot find the base of an expression with multiple pointer operands. 4170 if (PtrOp) 4171 return V; 4172 PtrOp = NAryOp; 4173 } 4174 } 4175 if (!PtrOp) 4176 return V; 4177 return getPointerBase(PtrOp); 4178 } 4179 return V; 4180 } 4181 4182 /// Push users of the given Instruction onto the given Worklist. 4183 static void 4184 PushDefUseChildren(Instruction *I, 4185 SmallVectorImpl<Instruction *> &Worklist) { 4186 // Push the def-use children onto the Worklist stack. 4187 for (User *U : I->users()) 4188 Worklist.push_back(cast<Instruction>(U)); 4189 } 4190 4191 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4192 SmallVector<Instruction *, 16> Worklist; 4193 PushDefUseChildren(PN, Worklist); 4194 4195 SmallPtrSet<Instruction *, 8> Visited; 4196 Visited.insert(PN); 4197 while (!Worklist.empty()) { 4198 Instruction *I = Worklist.pop_back_val(); 4199 if (!Visited.insert(I).second) 4200 continue; 4201 4202 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4203 if (It != ValueExprMap.end()) { 4204 const SCEV *Old = It->second; 4205 4206 // Short-circuit the def-use traversal if the symbolic name 4207 // ceases to appear in expressions. 4208 if (Old != SymName && !hasOperand(Old, SymName)) 4209 continue; 4210 4211 // SCEVUnknown for a PHI either means that it has an unrecognized 4212 // structure, it's a PHI that's in the progress of being computed 4213 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4214 // additional loop trip count information isn't going to change anything. 4215 // In the second case, createNodeForPHI will perform the necessary 4216 // updates on its own when it gets to that point. In the third, we do 4217 // want to forget the SCEVUnknown. 4218 if (!isa<PHINode>(I) || 4219 !isa<SCEVUnknown>(Old) || 4220 (I != PN && Old == SymName)) { 4221 eraseValueFromMap(It->first); 4222 forgetMemoizedResults(Old); 4223 } 4224 } 4225 4226 PushDefUseChildren(I, Worklist); 4227 } 4228 } 4229 4230 namespace { 4231 4232 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4233 /// expression in case its Loop is L. If it is not L then 4234 /// if IgnoreOtherLoops is true then use AddRec itself 4235 /// otherwise rewrite cannot be done. 4236 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4237 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4238 public: 4239 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4240 bool IgnoreOtherLoops = true) { 4241 SCEVInitRewriter Rewriter(L, SE); 4242 const SCEV *Result = Rewriter.visit(S); 4243 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4244 return SE.getCouldNotCompute(); 4245 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4246 ? SE.getCouldNotCompute() 4247 : Result; 4248 } 4249 4250 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4251 if (!SE.isLoopInvariant(Expr, L)) 4252 SeenLoopVariantSCEVUnknown = true; 4253 return Expr; 4254 } 4255 4256 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4257 // Only re-write AddRecExprs for this loop. 4258 if (Expr->getLoop() == L) 4259 return Expr->getStart(); 4260 SeenOtherLoops = true; 4261 return Expr; 4262 } 4263 4264 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4265 4266 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4267 4268 private: 4269 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4270 : SCEVRewriteVisitor(SE), L(L) {} 4271 4272 const Loop *L; 4273 bool SeenLoopVariantSCEVUnknown = false; 4274 bool SeenOtherLoops = false; 4275 }; 4276 4277 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4278 /// increment expression in case its Loop is L. If it is not L then 4279 /// use AddRec itself. 4280 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4281 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4282 public: 4283 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4284 SCEVPostIncRewriter Rewriter(L, SE); 4285 const SCEV *Result = Rewriter.visit(S); 4286 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4287 ? SE.getCouldNotCompute() 4288 : Result; 4289 } 4290 4291 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4292 if (!SE.isLoopInvariant(Expr, L)) 4293 SeenLoopVariantSCEVUnknown = true; 4294 return Expr; 4295 } 4296 4297 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4298 // Only re-write AddRecExprs for this loop. 4299 if (Expr->getLoop() == L) 4300 return Expr->getPostIncExpr(SE); 4301 SeenOtherLoops = true; 4302 return Expr; 4303 } 4304 4305 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4306 4307 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4308 4309 private: 4310 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4311 : SCEVRewriteVisitor(SE), L(L) {} 4312 4313 const Loop *L; 4314 bool SeenLoopVariantSCEVUnknown = false; 4315 bool SeenOtherLoops = false; 4316 }; 4317 4318 /// This class evaluates the compare condition by matching it against the 4319 /// condition of loop latch. If there is a match we assume a true value 4320 /// for the condition while building SCEV nodes. 4321 class SCEVBackedgeConditionFolder 4322 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4323 public: 4324 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4325 ScalarEvolution &SE) { 4326 bool IsPosBECond = false; 4327 Value *BECond = nullptr; 4328 if (BasicBlock *Latch = L->getLoopLatch()) { 4329 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4330 if (BI && BI->isConditional()) { 4331 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4332 "Both outgoing branches should not target same header!"); 4333 BECond = BI->getCondition(); 4334 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4335 } else { 4336 return S; 4337 } 4338 } 4339 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4340 return Rewriter.visit(S); 4341 } 4342 4343 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4344 const SCEV *Result = Expr; 4345 bool InvariantF = SE.isLoopInvariant(Expr, L); 4346 4347 if (!InvariantF) { 4348 Instruction *I = cast<Instruction>(Expr->getValue()); 4349 switch (I->getOpcode()) { 4350 case Instruction::Select: { 4351 SelectInst *SI = cast<SelectInst>(I); 4352 Optional<const SCEV *> Res = 4353 compareWithBackedgeCondition(SI->getCondition()); 4354 if (Res.hasValue()) { 4355 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4356 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4357 } 4358 break; 4359 } 4360 default: { 4361 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4362 if (Res.hasValue()) 4363 Result = Res.getValue(); 4364 break; 4365 } 4366 } 4367 } 4368 return Result; 4369 } 4370 4371 private: 4372 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4373 bool IsPosBECond, ScalarEvolution &SE) 4374 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4375 IsPositiveBECond(IsPosBECond) {} 4376 4377 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4378 4379 const Loop *L; 4380 /// Loop back condition. 4381 Value *BackedgeCond = nullptr; 4382 /// Set to true if loop back is on positive branch condition. 4383 bool IsPositiveBECond; 4384 }; 4385 4386 Optional<const SCEV *> 4387 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4388 4389 // If value matches the backedge condition for loop latch, 4390 // then return a constant evolution node based on loopback 4391 // branch taken. 4392 if (BackedgeCond == IC) 4393 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4394 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4395 return None; 4396 } 4397 4398 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4399 public: 4400 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4401 ScalarEvolution &SE) { 4402 SCEVShiftRewriter Rewriter(L, SE); 4403 const SCEV *Result = Rewriter.visit(S); 4404 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4405 } 4406 4407 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4408 // Only allow AddRecExprs for this loop. 4409 if (!SE.isLoopInvariant(Expr, L)) 4410 Valid = false; 4411 return Expr; 4412 } 4413 4414 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4415 if (Expr->getLoop() == L && Expr->isAffine()) 4416 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4417 Valid = false; 4418 return Expr; 4419 } 4420 4421 bool isValid() { return Valid; } 4422 4423 private: 4424 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4425 : SCEVRewriteVisitor(SE), L(L) {} 4426 4427 const Loop *L; 4428 bool Valid = true; 4429 }; 4430 4431 } // end anonymous namespace 4432 4433 SCEV::NoWrapFlags 4434 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4435 if (!AR->isAffine()) 4436 return SCEV::FlagAnyWrap; 4437 4438 using OBO = OverflowingBinaryOperator; 4439 4440 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4441 4442 if (!AR->hasNoSignedWrap()) { 4443 ConstantRange AddRecRange = getSignedRange(AR); 4444 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4445 4446 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4447 Instruction::Add, IncRange, OBO::NoSignedWrap); 4448 if (NSWRegion.contains(AddRecRange)) 4449 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4450 } 4451 4452 if (!AR->hasNoUnsignedWrap()) { 4453 ConstantRange AddRecRange = getUnsignedRange(AR); 4454 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4455 4456 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4457 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4458 if (NUWRegion.contains(AddRecRange)) 4459 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4460 } 4461 4462 return Result; 4463 } 4464 4465 namespace { 4466 4467 /// Represents an abstract binary operation. This may exist as a 4468 /// normal instruction or constant expression, or may have been 4469 /// derived from an expression tree. 4470 struct BinaryOp { 4471 unsigned Opcode; 4472 Value *LHS; 4473 Value *RHS; 4474 bool IsNSW = false; 4475 bool IsNUW = false; 4476 4477 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4478 /// constant expression. 4479 Operator *Op = nullptr; 4480 4481 explicit BinaryOp(Operator *Op) 4482 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4483 Op(Op) { 4484 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4485 IsNSW = OBO->hasNoSignedWrap(); 4486 IsNUW = OBO->hasNoUnsignedWrap(); 4487 } 4488 } 4489 4490 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4491 bool IsNUW = false) 4492 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4493 }; 4494 4495 } // end anonymous namespace 4496 4497 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4498 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4499 auto *Op = dyn_cast<Operator>(V); 4500 if (!Op) 4501 return None; 4502 4503 // Implementation detail: all the cleverness here should happen without 4504 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4505 // SCEV expressions when possible, and we should not break that. 4506 4507 switch (Op->getOpcode()) { 4508 case Instruction::Add: 4509 case Instruction::Sub: 4510 case Instruction::Mul: 4511 case Instruction::UDiv: 4512 case Instruction::URem: 4513 case Instruction::And: 4514 case Instruction::Or: 4515 case Instruction::AShr: 4516 case Instruction::Shl: 4517 return BinaryOp(Op); 4518 4519 case Instruction::Xor: 4520 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4521 // If the RHS of the xor is a signmask, then this is just an add. 4522 // Instcombine turns add of signmask into xor as a strength reduction step. 4523 if (RHSC->getValue().isSignMask()) 4524 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4525 return BinaryOp(Op); 4526 4527 case Instruction::LShr: 4528 // Turn logical shift right of a constant into a unsigned divide. 4529 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4530 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4531 4532 // If the shift count is not less than the bitwidth, the result of 4533 // the shift is undefined. Don't try to analyze it, because the 4534 // resolution chosen here may differ from the resolution chosen in 4535 // other parts of the compiler. 4536 if (SA->getValue().ult(BitWidth)) { 4537 Constant *X = 4538 ConstantInt::get(SA->getContext(), 4539 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4540 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4541 } 4542 } 4543 return BinaryOp(Op); 4544 4545 case Instruction::ExtractValue: { 4546 auto *EVI = cast<ExtractValueInst>(Op); 4547 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4548 break; 4549 4550 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4551 if (!WO) 4552 break; 4553 4554 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4555 bool Signed = WO->isSigned(); 4556 // TODO: Should add nuw/nsw flags for mul as well. 4557 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4558 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4559 4560 // Now that we know that all uses of the arithmetic-result component of 4561 // CI are guarded by the overflow check, we can go ahead and pretend 4562 // that the arithmetic is non-overflowing. 4563 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4564 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4565 } 4566 4567 default: 4568 break; 4569 } 4570 4571 return None; 4572 } 4573 4574 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4575 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4576 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4577 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4578 /// follows one of the following patterns: 4579 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4580 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4581 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4582 /// we return the type of the truncation operation, and indicate whether the 4583 /// truncated type should be treated as signed/unsigned by setting 4584 /// \p Signed to true/false, respectively. 4585 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4586 bool &Signed, ScalarEvolution &SE) { 4587 // The case where Op == SymbolicPHI (that is, with no type conversions on 4588 // the way) is handled by the regular add recurrence creating logic and 4589 // would have already been triggered in createAddRecForPHI. Reaching it here 4590 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4591 // because one of the other operands of the SCEVAddExpr updating this PHI is 4592 // not invariant). 4593 // 4594 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4595 // this case predicates that allow us to prove that Op == SymbolicPHI will 4596 // be added. 4597 if (Op == SymbolicPHI) 4598 return nullptr; 4599 4600 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4601 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4602 if (SourceBits != NewBits) 4603 return nullptr; 4604 4605 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4606 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4607 if (!SExt && !ZExt) 4608 return nullptr; 4609 const SCEVTruncateExpr *Trunc = 4610 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4611 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4612 if (!Trunc) 4613 return nullptr; 4614 const SCEV *X = Trunc->getOperand(); 4615 if (X != SymbolicPHI) 4616 return nullptr; 4617 Signed = SExt != nullptr; 4618 return Trunc->getType(); 4619 } 4620 4621 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4622 if (!PN->getType()->isIntegerTy()) 4623 return nullptr; 4624 const Loop *L = LI.getLoopFor(PN->getParent()); 4625 if (!L || L->getHeader() != PN->getParent()) 4626 return nullptr; 4627 return L; 4628 } 4629 4630 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4631 // computation that updates the phi follows the following pattern: 4632 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4633 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4634 // If so, try to see if it can be rewritten as an AddRecExpr under some 4635 // Predicates. If successful, return them as a pair. Also cache the results 4636 // of the analysis. 4637 // 4638 // Example usage scenario: 4639 // Say the Rewriter is called for the following SCEV: 4640 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4641 // where: 4642 // %X = phi i64 (%Start, %BEValue) 4643 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4644 // and call this function with %SymbolicPHI = %X. 4645 // 4646 // The analysis will find that the value coming around the backedge has 4647 // the following SCEV: 4648 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4649 // Upon concluding that this matches the desired pattern, the function 4650 // will return the pair {NewAddRec, SmallPredsVec} where: 4651 // NewAddRec = {%Start,+,%Step} 4652 // SmallPredsVec = {P1, P2, P3} as follows: 4653 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4654 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4655 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4656 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4657 // under the predicates {P1,P2,P3}. 4658 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4659 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4660 // 4661 // TODO's: 4662 // 4663 // 1) Extend the Induction descriptor to also support inductions that involve 4664 // casts: When needed (namely, when we are called in the context of the 4665 // vectorizer induction analysis), a Set of cast instructions will be 4666 // populated by this method, and provided back to isInductionPHI. This is 4667 // needed to allow the vectorizer to properly record them to be ignored by 4668 // the cost model and to avoid vectorizing them (otherwise these casts, 4669 // which are redundant under the runtime overflow checks, will be 4670 // vectorized, which can be costly). 4671 // 4672 // 2) Support additional induction/PHISCEV patterns: We also want to support 4673 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4674 // after the induction update operation (the induction increment): 4675 // 4676 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4677 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4678 // 4679 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4680 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4681 // 4682 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4683 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4684 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4685 SmallVector<const SCEVPredicate *, 3> Predicates; 4686 4687 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4688 // return an AddRec expression under some predicate. 4689 4690 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4691 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4692 assert(L && "Expecting an integer loop header phi"); 4693 4694 // The loop may have multiple entrances or multiple exits; we can analyze 4695 // this phi as an addrec if it has a unique entry value and a unique 4696 // backedge value. 4697 Value *BEValueV = nullptr, *StartValueV = nullptr; 4698 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4699 Value *V = PN->getIncomingValue(i); 4700 if (L->contains(PN->getIncomingBlock(i))) { 4701 if (!BEValueV) { 4702 BEValueV = V; 4703 } else if (BEValueV != V) { 4704 BEValueV = nullptr; 4705 break; 4706 } 4707 } else if (!StartValueV) { 4708 StartValueV = V; 4709 } else if (StartValueV != V) { 4710 StartValueV = nullptr; 4711 break; 4712 } 4713 } 4714 if (!BEValueV || !StartValueV) 4715 return None; 4716 4717 const SCEV *BEValue = getSCEV(BEValueV); 4718 4719 // If the value coming around the backedge is an add with the symbolic 4720 // value we just inserted, possibly with casts that we can ignore under 4721 // an appropriate runtime guard, then we found a simple induction variable! 4722 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4723 if (!Add) 4724 return None; 4725 4726 // If there is a single occurrence of the symbolic value, possibly 4727 // casted, replace it with a recurrence. 4728 unsigned FoundIndex = Add->getNumOperands(); 4729 Type *TruncTy = nullptr; 4730 bool Signed; 4731 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4732 if ((TruncTy = 4733 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4734 if (FoundIndex == e) { 4735 FoundIndex = i; 4736 break; 4737 } 4738 4739 if (FoundIndex == Add->getNumOperands()) 4740 return None; 4741 4742 // Create an add with everything but the specified operand. 4743 SmallVector<const SCEV *, 8> Ops; 4744 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4745 if (i != FoundIndex) 4746 Ops.push_back(Add->getOperand(i)); 4747 const SCEV *Accum = getAddExpr(Ops); 4748 4749 // The runtime checks will not be valid if the step amount is 4750 // varying inside the loop. 4751 if (!isLoopInvariant(Accum, L)) 4752 return None; 4753 4754 // *** Part2: Create the predicates 4755 4756 // Analysis was successful: we have a phi-with-cast pattern for which we 4757 // can return an AddRec expression under the following predicates: 4758 // 4759 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4760 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4761 // P2: An Equal predicate that guarantees that 4762 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4763 // P3: An Equal predicate that guarantees that 4764 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4765 // 4766 // As we next prove, the above predicates guarantee that: 4767 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4768 // 4769 // 4770 // More formally, we want to prove that: 4771 // Expr(i+1) = Start + (i+1) * Accum 4772 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4773 // 4774 // Given that: 4775 // 1) Expr(0) = Start 4776 // 2) Expr(1) = Start + Accum 4777 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4778 // 3) Induction hypothesis (step i): 4779 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4780 // 4781 // Proof: 4782 // Expr(i+1) = 4783 // = Start + (i+1)*Accum 4784 // = (Start + i*Accum) + Accum 4785 // = Expr(i) + Accum 4786 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4787 // :: from step i 4788 // 4789 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4790 // 4791 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4792 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4793 // + Accum :: from P3 4794 // 4795 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4796 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4797 // 4798 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4799 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4800 // 4801 // By induction, the same applies to all iterations 1<=i<n: 4802 // 4803 4804 // Create a truncated addrec for which we will add a no overflow check (P1). 4805 const SCEV *StartVal = getSCEV(StartValueV); 4806 const SCEV *PHISCEV = 4807 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4808 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4809 4810 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4811 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4812 // will be constant. 4813 // 4814 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4815 // add P1. 4816 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4817 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4818 Signed ? SCEVWrapPredicate::IncrementNSSW 4819 : SCEVWrapPredicate::IncrementNUSW; 4820 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4821 Predicates.push_back(AddRecPred); 4822 } 4823 4824 // Create the Equal Predicates P2,P3: 4825 4826 // It is possible that the predicates P2 and/or P3 are computable at 4827 // compile time due to StartVal and/or Accum being constants. 4828 // If either one is, then we can check that now and escape if either P2 4829 // or P3 is false. 4830 4831 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4832 // for each of StartVal and Accum 4833 auto getExtendedExpr = [&](const SCEV *Expr, 4834 bool CreateSignExtend) -> const SCEV * { 4835 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4836 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4837 const SCEV *ExtendedExpr = 4838 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4839 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4840 return ExtendedExpr; 4841 }; 4842 4843 // Given: 4844 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4845 // = getExtendedExpr(Expr) 4846 // Determine whether the predicate P: Expr == ExtendedExpr 4847 // is known to be false at compile time 4848 auto PredIsKnownFalse = [&](const SCEV *Expr, 4849 const SCEV *ExtendedExpr) -> bool { 4850 return Expr != ExtendedExpr && 4851 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4852 }; 4853 4854 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4855 if (PredIsKnownFalse(StartVal, StartExtended)) { 4856 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4857 return None; 4858 } 4859 4860 // The Step is always Signed (because the overflow checks are either 4861 // NSSW or NUSW) 4862 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4863 if (PredIsKnownFalse(Accum, AccumExtended)) { 4864 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4865 return None; 4866 } 4867 4868 auto AppendPredicate = [&](const SCEV *Expr, 4869 const SCEV *ExtendedExpr) -> void { 4870 if (Expr != ExtendedExpr && 4871 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4872 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4873 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4874 Predicates.push_back(Pred); 4875 } 4876 }; 4877 4878 AppendPredicate(StartVal, StartExtended); 4879 AppendPredicate(Accum, AccumExtended); 4880 4881 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4882 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4883 // into NewAR if it will also add the runtime overflow checks specified in 4884 // Predicates. 4885 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4886 4887 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4888 std::make_pair(NewAR, Predicates); 4889 // Remember the result of the analysis for this SCEV at this locayyytion. 4890 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4891 return PredRewrite; 4892 } 4893 4894 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4895 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4896 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4897 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4898 if (!L) 4899 return None; 4900 4901 // Check to see if we already analyzed this PHI. 4902 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4903 if (I != PredicatedSCEVRewrites.end()) { 4904 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4905 I->second; 4906 // Analysis was done before and failed to create an AddRec: 4907 if (Rewrite.first == SymbolicPHI) 4908 return None; 4909 // Analysis was done before and succeeded to create an AddRec under 4910 // a predicate: 4911 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4912 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4913 return Rewrite; 4914 } 4915 4916 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4917 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4918 4919 // Record in the cache that the analysis failed 4920 if (!Rewrite) { 4921 SmallVector<const SCEVPredicate *, 3> Predicates; 4922 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4923 return None; 4924 } 4925 4926 return Rewrite; 4927 } 4928 4929 // FIXME: This utility is currently required because the Rewriter currently 4930 // does not rewrite this expression: 4931 // {0, +, (sext ix (trunc iy to ix) to iy)} 4932 // into {0, +, %step}, 4933 // even when the following Equal predicate exists: 4934 // "%step == (sext ix (trunc iy to ix) to iy)". 4935 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4936 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4937 if (AR1 == AR2) 4938 return true; 4939 4940 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4941 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4942 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4943 return false; 4944 return true; 4945 }; 4946 4947 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4948 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4949 return false; 4950 return true; 4951 } 4952 4953 /// A helper function for createAddRecFromPHI to handle simple cases. 4954 /// 4955 /// This function tries to find an AddRec expression for the simplest (yet most 4956 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4957 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4958 /// technique for finding the AddRec expression. 4959 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4960 Value *BEValueV, 4961 Value *StartValueV) { 4962 const Loop *L = LI.getLoopFor(PN->getParent()); 4963 assert(L && L->getHeader() == PN->getParent()); 4964 assert(BEValueV && StartValueV); 4965 4966 auto BO = MatchBinaryOp(BEValueV, DT); 4967 if (!BO) 4968 return nullptr; 4969 4970 if (BO->Opcode != Instruction::Add) 4971 return nullptr; 4972 4973 const SCEV *Accum = nullptr; 4974 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4975 Accum = getSCEV(BO->RHS); 4976 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4977 Accum = getSCEV(BO->LHS); 4978 4979 if (!Accum) 4980 return nullptr; 4981 4982 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4983 if (BO->IsNUW) 4984 Flags = setFlags(Flags, SCEV::FlagNUW); 4985 if (BO->IsNSW) 4986 Flags = setFlags(Flags, SCEV::FlagNSW); 4987 4988 const SCEV *StartVal = getSCEV(StartValueV); 4989 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4990 4991 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4992 4993 // We can add Flags to the post-inc expression only if we 4994 // know that it is *undefined behavior* for BEValueV to 4995 // overflow. 4996 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4997 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4998 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4999 5000 return PHISCEV; 5001 } 5002 5003 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5004 const Loop *L = LI.getLoopFor(PN->getParent()); 5005 if (!L || L->getHeader() != PN->getParent()) 5006 return nullptr; 5007 5008 // The loop may have multiple entrances or multiple exits; we can analyze 5009 // this phi as an addrec if it has a unique entry value and a unique 5010 // backedge value. 5011 Value *BEValueV = nullptr, *StartValueV = nullptr; 5012 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5013 Value *V = PN->getIncomingValue(i); 5014 if (L->contains(PN->getIncomingBlock(i))) { 5015 if (!BEValueV) { 5016 BEValueV = V; 5017 } else if (BEValueV != V) { 5018 BEValueV = nullptr; 5019 break; 5020 } 5021 } else if (!StartValueV) { 5022 StartValueV = V; 5023 } else if (StartValueV != V) { 5024 StartValueV = nullptr; 5025 break; 5026 } 5027 } 5028 if (!BEValueV || !StartValueV) 5029 return nullptr; 5030 5031 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5032 "PHI node already processed?"); 5033 5034 // First, try to find AddRec expression without creating a fictituos symbolic 5035 // value for PN. 5036 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5037 return S; 5038 5039 // Handle PHI node value symbolically. 5040 const SCEV *SymbolicName = getUnknown(PN); 5041 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5042 5043 // Using this symbolic name for the PHI, analyze the value coming around 5044 // the back-edge. 5045 const SCEV *BEValue = getSCEV(BEValueV); 5046 5047 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5048 // has a special value for the first iteration of the loop. 5049 5050 // If the value coming around the backedge is an add with the symbolic 5051 // value we just inserted, then we found a simple induction variable! 5052 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5053 // If there is a single occurrence of the symbolic value, replace it 5054 // with a recurrence. 5055 unsigned FoundIndex = Add->getNumOperands(); 5056 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5057 if (Add->getOperand(i) == SymbolicName) 5058 if (FoundIndex == e) { 5059 FoundIndex = i; 5060 break; 5061 } 5062 5063 if (FoundIndex != Add->getNumOperands()) { 5064 // Create an add with everything but the specified operand. 5065 SmallVector<const SCEV *, 8> Ops; 5066 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5067 if (i != FoundIndex) 5068 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5069 L, *this)); 5070 const SCEV *Accum = getAddExpr(Ops); 5071 5072 // This is not a valid addrec if the step amount is varying each 5073 // loop iteration, but is not itself an addrec in this loop. 5074 if (isLoopInvariant(Accum, L) || 5075 (isa<SCEVAddRecExpr>(Accum) && 5076 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5077 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5078 5079 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5080 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5081 if (BO->IsNUW) 5082 Flags = setFlags(Flags, SCEV::FlagNUW); 5083 if (BO->IsNSW) 5084 Flags = setFlags(Flags, SCEV::FlagNSW); 5085 } 5086 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5087 // If the increment is an inbounds GEP, then we know the address 5088 // space cannot be wrapped around. We cannot make any guarantee 5089 // about signed or unsigned overflow because pointers are 5090 // unsigned but we may have a negative index from the base 5091 // pointer. We can guarantee that no unsigned wrap occurs if the 5092 // indices form a positive value. 5093 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5094 Flags = setFlags(Flags, SCEV::FlagNW); 5095 5096 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5097 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5098 Flags = setFlags(Flags, SCEV::FlagNUW); 5099 } 5100 5101 // We cannot transfer nuw and nsw flags from subtraction 5102 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5103 // for instance. 5104 } 5105 5106 const SCEV *StartVal = getSCEV(StartValueV); 5107 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5108 5109 // Okay, for the entire analysis of this edge we assumed the PHI 5110 // to be symbolic. We now need to go back and purge all of the 5111 // entries for the scalars that use the symbolic expression. 5112 forgetSymbolicName(PN, SymbolicName); 5113 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5114 5115 // We can add Flags to the post-inc expression only if we 5116 // know that it is *undefined behavior* for BEValueV to 5117 // overflow. 5118 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5119 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5120 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5121 5122 return PHISCEV; 5123 } 5124 } 5125 } else { 5126 // Otherwise, this could be a loop like this: 5127 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5128 // In this case, j = {1,+,1} and BEValue is j. 5129 // Because the other in-value of i (0) fits the evolution of BEValue 5130 // i really is an addrec evolution. 5131 // 5132 // We can generalize this saying that i is the shifted value of BEValue 5133 // by one iteration: 5134 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5135 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5136 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5137 if (Shifted != getCouldNotCompute() && 5138 Start != getCouldNotCompute()) { 5139 const SCEV *StartVal = getSCEV(StartValueV); 5140 if (Start == StartVal) { 5141 // Okay, for the entire analysis of this edge we assumed the PHI 5142 // to be symbolic. We now need to go back and purge all of the 5143 // entries for the scalars that use the symbolic expression. 5144 forgetSymbolicName(PN, SymbolicName); 5145 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5146 return Shifted; 5147 } 5148 } 5149 } 5150 5151 // Remove the temporary PHI node SCEV that has been inserted while intending 5152 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5153 // as it will prevent later (possibly simpler) SCEV expressions to be added 5154 // to the ValueExprMap. 5155 eraseValueFromMap(PN); 5156 5157 return nullptr; 5158 } 5159 5160 // Checks if the SCEV S is available at BB. S is considered available at BB 5161 // if S can be materialized at BB without introducing a fault. 5162 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5163 BasicBlock *BB) { 5164 struct CheckAvailable { 5165 bool TraversalDone = false; 5166 bool Available = true; 5167 5168 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5169 BasicBlock *BB = nullptr; 5170 DominatorTree &DT; 5171 5172 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5173 : L(L), BB(BB), DT(DT) {} 5174 5175 bool setUnavailable() { 5176 TraversalDone = true; 5177 Available = false; 5178 return false; 5179 } 5180 5181 bool follow(const SCEV *S) { 5182 switch (S->getSCEVType()) { 5183 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5184 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5185 case scUMinExpr: 5186 case scSMinExpr: 5187 // These expressions are available if their operand(s) is/are. 5188 return true; 5189 5190 case scAddRecExpr: { 5191 // We allow add recurrences that are on the loop BB is in, or some 5192 // outer loop. This guarantees availability because the value of the 5193 // add recurrence at BB is simply the "current" value of the induction 5194 // variable. We can relax this in the future; for instance an add 5195 // recurrence on a sibling dominating loop is also available at BB. 5196 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5197 if (L && (ARLoop == L || ARLoop->contains(L))) 5198 return true; 5199 5200 return setUnavailable(); 5201 } 5202 5203 case scUnknown: { 5204 // For SCEVUnknown, we check for simple dominance. 5205 const auto *SU = cast<SCEVUnknown>(S); 5206 Value *V = SU->getValue(); 5207 5208 if (isa<Argument>(V)) 5209 return false; 5210 5211 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5212 return false; 5213 5214 return setUnavailable(); 5215 } 5216 5217 case scUDivExpr: 5218 case scCouldNotCompute: 5219 // We do not try to smart about these at all. 5220 return setUnavailable(); 5221 } 5222 llvm_unreachable("switch should be fully covered!"); 5223 } 5224 5225 bool isDone() { return TraversalDone; } 5226 }; 5227 5228 CheckAvailable CA(L, BB, DT); 5229 SCEVTraversal<CheckAvailable> ST(CA); 5230 5231 ST.visitAll(S); 5232 return CA.Available; 5233 } 5234 5235 // Try to match a control flow sequence that branches out at BI and merges back 5236 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5237 // match. 5238 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5239 Value *&C, Value *&LHS, Value *&RHS) { 5240 C = BI->getCondition(); 5241 5242 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5243 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5244 5245 if (!LeftEdge.isSingleEdge()) 5246 return false; 5247 5248 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5249 5250 Use &LeftUse = Merge->getOperandUse(0); 5251 Use &RightUse = Merge->getOperandUse(1); 5252 5253 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5254 LHS = LeftUse; 5255 RHS = RightUse; 5256 return true; 5257 } 5258 5259 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5260 LHS = RightUse; 5261 RHS = LeftUse; 5262 return true; 5263 } 5264 5265 return false; 5266 } 5267 5268 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5269 auto IsReachable = 5270 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5271 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5272 const Loop *L = LI.getLoopFor(PN->getParent()); 5273 5274 // We don't want to break LCSSA, even in a SCEV expression tree. 5275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5276 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5277 return nullptr; 5278 5279 // Try to match 5280 // 5281 // br %cond, label %left, label %right 5282 // left: 5283 // br label %merge 5284 // right: 5285 // br label %merge 5286 // merge: 5287 // V = phi [ %x, %left ], [ %y, %right ] 5288 // 5289 // as "select %cond, %x, %y" 5290 5291 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5292 assert(IDom && "At least the entry block should dominate PN"); 5293 5294 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5295 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5296 5297 if (BI && BI->isConditional() && 5298 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5299 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5300 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5301 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5302 } 5303 5304 return nullptr; 5305 } 5306 5307 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5308 if (const SCEV *S = createAddRecFromPHI(PN)) 5309 return S; 5310 5311 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5312 return S; 5313 5314 // If the PHI has a single incoming value, follow that value, unless the 5315 // PHI's incoming blocks are in a different loop, in which case doing so 5316 // risks breaking LCSSA form. Instcombine would normally zap these, but 5317 // it doesn't have DominatorTree information, so it may miss cases. 5318 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5319 if (LI.replacementPreservesLCSSAForm(PN, V)) 5320 return getSCEV(V); 5321 5322 // If it's not a loop phi, we can't handle it yet. 5323 return getUnknown(PN); 5324 } 5325 5326 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5327 Value *Cond, 5328 Value *TrueVal, 5329 Value *FalseVal) { 5330 // Handle "constant" branch or select. This can occur for instance when a 5331 // loop pass transforms an inner loop and moves on to process the outer loop. 5332 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5333 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5334 5335 // Try to match some simple smax or umax patterns. 5336 auto *ICI = dyn_cast<ICmpInst>(Cond); 5337 if (!ICI) 5338 return getUnknown(I); 5339 5340 Value *LHS = ICI->getOperand(0); 5341 Value *RHS = ICI->getOperand(1); 5342 5343 switch (ICI->getPredicate()) { 5344 case ICmpInst::ICMP_SLT: 5345 case ICmpInst::ICMP_SLE: 5346 std::swap(LHS, RHS); 5347 LLVM_FALLTHROUGH; 5348 case ICmpInst::ICMP_SGT: 5349 case ICmpInst::ICMP_SGE: 5350 // a >s b ? a+x : b+x -> smax(a, b)+x 5351 // a >s b ? b+x : a+x -> smin(a, b)+x 5352 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5353 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5354 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5355 const SCEV *LA = getSCEV(TrueVal); 5356 const SCEV *RA = getSCEV(FalseVal); 5357 const SCEV *LDiff = getMinusSCEV(LA, LS); 5358 const SCEV *RDiff = getMinusSCEV(RA, RS); 5359 if (LDiff == RDiff) 5360 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5361 LDiff = getMinusSCEV(LA, RS); 5362 RDiff = getMinusSCEV(RA, LS); 5363 if (LDiff == RDiff) 5364 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5365 } 5366 break; 5367 case ICmpInst::ICMP_ULT: 5368 case ICmpInst::ICMP_ULE: 5369 std::swap(LHS, RHS); 5370 LLVM_FALLTHROUGH; 5371 case ICmpInst::ICMP_UGT: 5372 case ICmpInst::ICMP_UGE: 5373 // a >u b ? a+x : b+x -> umax(a, b)+x 5374 // a >u b ? b+x : a+x -> umin(a, b)+x 5375 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5376 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5377 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5378 const SCEV *LA = getSCEV(TrueVal); 5379 const SCEV *RA = getSCEV(FalseVal); 5380 const SCEV *LDiff = getMinusSCEV(LA, LS); 5381 const SCEV *RDiff = getMinusSCEV(RA, RS); 5382 if (LDiff == RDiff) 5383 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5384 LDiff = getMinusSCEV(LA, RS); 5385 RDiff = getMinusSCEV(RA, LS); 5386 if (LDiff == RDiff) 5387 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5388 } 5389 break; 5390 case ICmpInst::ICMP_NE: 5391 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5392 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5393 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5394 const SCEV *One = getOne(I->getType()); 5395 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5396 const SCEV *LA = getSCEV(TrueVal); 5397 const SCEV *RA = getSCEV(FalseVal); 5398 const SCEV *LDiff = getMinusSCEV(LA, LS); 5399 const SCEV *RDiff = getMinusSCEV(RA, One); 5400 if (LDiff == RDiff) 5401 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5402 } 5403 break; 5404 case ICmpInst::ICMP_EQ: 5405 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5406 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5407 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5408 const SCEV *One = getOne(I->getType()); 5409 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5410 const SCEV *LA = getSCEV(TrueVal); 5411 const SCEV *RA = getSCEV(FalseVal); 5412 const SCEV *LDiff = getMinusSCEV(LA, One); 5413 const SCEV *RDiff = getMinusSCEV(RA, LS); 5414 if (LDiff == RDiff) 5415 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5416 } 5417 break; 5418 default: 5419 break; 5420 } 5421 5422 return getUnknown(I); 5423 } 5424 5425 /// Expand GEP instructions into add and multiply operations. This allows them 5426 /// to be analyzed by regular SCEV code. 5427 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5428 // Don't attempt to analyze GEPs over unsized objects. 5429 if (!GEP->getSourceElementType()->isSized()) 5430 return getUnknown(GEP); 5431 5432 SmallVector<const SCEV *, 4> IndexExprs; 5433 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5434 IndexExprs.push_back(getSCEV(*Index)); 5435 return getGEPExpr(GEP, IndexExprs); 5436 } 5437 5438 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5439 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5440 return C->getAPInt().countTrailingZeros(); 5441 5442 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5443 return std::min(GetMinTrailingZeros(T->getOperand()), 5444 (uint32_t)getTypeSizeInBits(T->getType())); 5445 5446 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5447 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5448 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5449 ? getTypeSizeInBits(E->getType()) 5450 : OpRes; 5451 } 5452 5453 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5455 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5456 ? getTypeSizeInBits(E->getType()) 5457 : OpRes; 5458 } 5459 5460 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5461 // The result is the min of all operands results. 5462 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5463 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5464 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5465 return MinOpRes; 5466 } 5467 5468 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5469 // The result is the sum of all operands results. 5470 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5471 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5472 for (unsigned i = 1, e = M->getNumOperands(); 5473 SumOpRes != BitWidth && i != e; ++i) 5474 SumOpRes = 5475 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5476 return SumOpRes; 5477 } 5478 5479 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5480 // The result is the min of all operands results. 5481 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5482 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5483 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5484 return MinOpRes; 5485 } 5486 5487 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5488 // The result is the min of all operands results. 5489 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5490 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5491 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5492 return MinOpRes; 5493 } 5494 5495 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5496 // The result is the min of all operands results. 5497 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5498 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5500 return MinOpRes; 5501 } 5502 5503 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5504 // For a SCEVUnknown, ask ValueTracking. 5505 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5506 return Known.countMinTrailingZeros(); 5507 } 5508 5509 // SCEVUDivExpr 5510 return 0; 5511 } 5512 5513 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5514 auto I = MinTrailingZerosCache.find(S); 5515 if (I != MinTrailingZerosCache.end()) 5516 return I->second; 5517 5518 uint32_t Result = GetMinTrailingZerosImpl(S); 5519 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5520 assert(InsertPair.second && "Should insert a new key"); 5521 return InsertPair.first->second; 5522 } 5523 5524 /// Helper method to assign a range to V from metadata present in the IR. 5525 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5526 if (Instruction *I = dyn_cast<Instruction>(V)) 5527 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5528 return getConstantRangeFromMetadata(*MD); 5529 5530 return None; 5531 } 5532 5533 /// Determine the range for a particular SCEV. If SignHint is 5534 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5535 /// with a "cleaner" unsigned (resp. signed) representation. 5536 const ConstantRange & 5537 ScalarEvolution::getRangeRef(const SCEV *S, 5538 ScalarEvolution::RangeSignHint SignHint) { 5539 DenseMap<const SCEV *, ConstantRange> &Cache = 5540 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5541 : SignedRanges; 5542 ConstantRange::PreferredRangeType RangeType = 5543 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5544 ? ConstantRange::Unsigned : ConstantRange::Signed; 5545 5546 // See if we've computed this range already. 5547 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5548 if (I != Cache.end()) 5549 return I->second; 5550 5551 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5552 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5553 5554 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5555 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5556 5557 // If the value has known zeros, the maximum value will have those known zeros 5558 // as well. 5559 uint32_t TZ = GetMinTrailingZeros(S); 5560 if (TZ != 0) { 5561 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5562 ConservativeResult = 5563 ConstantRange(APInt::getMinValue(BitWidth), 5564 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5565 else 5566 ConservativeResult = ConstantRange( 5567 APInt::getSignedMinValue(BitWidth), 5568 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5569 } 5570 5571 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5572 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5573 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5574 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5575 return setRange(Add, SignHint, 5576 ConservativeResult.intersectWith(X, RangeType)); 5577 } 5578 5579 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5580 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5581 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5582 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5583 return setRange(Mul, SignHint, 5584 ConservativeResult.intersectWith(X, RangeType)); 5585 } 5586 5587 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5588 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5589 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5590 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5591 return setRange(SMax, SignHint, 5592 ConservativeResult.intersectWith(X, RangeType)); 5593 } 5594 5595 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5596 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5597 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5598 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5599 return setRange(UMax, SignHint, 5600 ConservativeResult.intersectWith(X, RangeType)); 5601 } 5602 5603 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5604 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5605 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5606 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5607 return setRange(SMin, SignHint, 5608 ConservativeResult.intersectWith(X, RangeType)); 5609 } 5610 5611 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5612 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5613 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5614 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5615 return setRange(UMin, SignHint, 5616 ConservativeResult.intersectWith(X, RangeType)); 5617 } 5618 5619 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5620 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5621 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5622 return setRange(UDiv, SignHint, 5623 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5624 } 5625 5626 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5627 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5628 return setRange(ZExt, SignHint, 5629 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5630 RangeType)); 5631 } 5632 5633 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5634 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5635 return setRange(SExt, SignHint, 5636 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5637 RangeType)); 5638 } 5639 5640 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5641 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5642 return setRange(Trunc, SignHint, 5643 ConservativeResult.intersectWith(X.truncate(BitWidth), 5644 RangeType)); 5645 } 5646 5647 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5648 // If there's no unsigned wrap, the value will never be less than its 5649 // initial value. 5650 if (AddRec->hasNoUnsignedWrap()) 5651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5652 if (!C->getValue()->isZero()) 5653 ConservativeResult = ConservativeResult.intersectWith( 5654 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5655 5656 // If there's no signed wrap, and all the operands have the same sign or 5657 // zero, the value won't ever change sign. 5658 if (AddRec->hasNoSignedWrap()) { 5659 bool AllNonNeg = true; 5660 bool AllNonPos = true; 5661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5662 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5663 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5664 } 5665 if (AllNonNeg) 5666 ConservativeResult = ConservativeResult.intersectWith( 5667 ConstantRange(APInt(BitWidth, 0), 5668 APInt::getSignedMinValue(BitWidth)), RangeType); 5669 else if (AllNonPos) 5670 ConservativeResult = ConservativeResult.intersectWith( 5671 ConstantRange(APInt::getSignedMinValue(BitWidth), 5672 APInt(BitWidth, 1)), RangeType); 5673 } 5674 5675 // TODO: non-affine addrec 5676 if (AddRec->isAffine()) { 5677 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5678 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5679 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5680 auto RangeFromAffine = getRangeForAffineAR( 5681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5682 BitWidth); 5683 if (!RangeFromAffine.isFullSet()) 5684 ConservativeResult = 5685 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5686 5687 auto RangeFromFactoring = getRangeViaFactoring( 5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5689 BitWidth); 5690 if (!RangeFromFactoring.isFullSet()) 5691 ConservativeResult = 5692 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5693 } 5694 } 5695 5696 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5697 } 5698 5699 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5700 // Check if the IR explicitly contains !range metadata. 5701 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5702 if (MDRange.hasValue()) 5703 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5704 RangeType); 5705 5706 // Split here to avoid paying the compile-time cost of calling both 5707 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5708 // if needed. 5709 const DataLayout &DL = getDataLayout(); 5710 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5711 // For a SCEVUnknown, ask ValueTracking. 5712 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5713 if (Known.One != ~Known.Zero + 1) 5714 ConservativeResult = 5715 ConservativeResult.intersectWith( 5716 ConstantRange(Known.One, ~Known.Zero + 1), RangeType); 5717 } else { 5718 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5719 "generalize as needed!"); 5720 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5721 if (NS > 1) 5722 ConservativeResult = ConservativeResult.intersectWith( 5723 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5724 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5725 RangeType); 5726 } 5727 5728 // A range of Phi is a subset of union of all ranges of its input. 5729 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5730 // Make sure that we do not run over cycled Phis. 5731 if (PendingPhiRanges.insert(Phi).second) { 5732 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5733 for (auto &Op : Phi->operands()) { 5734 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5735 RangeFromOps = RangeFromOps.unionWith(OpRange); 5736 // No point to continue if we already have a full set. 5737 if (RangeFromOps.isFullSet()) 5738 break; 5739 } 5740 ConservativeResult = 5741 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5742 bool Erased = PendingPhiRanges.erase(Phi); 5743 assert(Erased && "Failed to erase Phi properly?"); 5744 (void) Erased; 5745 } 5746 } 5747 5748 return setRange(U, SignHint, std::move(ConservativeResult)); 5749 } 5750 5751 return setRange(S, SignHint, std::move(ConservativeResult)); 5752 } 5753 5754 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5755 // values that the expression can take. Initially, the expression has a value 5756 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5757 // argument defines if we treat Step as signed or unsigned. 5758 static ConstantRange getRangeForAffineARHelper(APInt Step, 5759 const ConstantRange &StartRange, 5760 const APInt &MaxBECount, 5761 unsigned BitWidth, bool Signed) { 5762 // If either Step or MaxBECount is 0, then the expression won't change, and we 5763 // just need to return the initial range. 5764 if (Step == 0 || MaxBECount == 0) 5765 return StartRange; 5766 5767 // If we don't know anything about the initial value (i.e. StartRange is 5768 // FullRange), then we don't know anything about the final range either. 5769 // Return FullRange. 5770 if (StartRange.isFullSet()) 5771 return ConstantRange::getFull(BitWidth); 5772 5773 // If Step is signed and negative, then we use its absolute value, but we also 5774 // note that we're moving in the opposite direction. 5775 bool Descending = Signed && Step.isNegative(); 5776 5777 if (Signed) 5778 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5779 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5780 // This equations hold true due to the well-defined wrap-around behavior of 5781 // APInt. 5782 Step = Step.abs(); 5783 5784 // Check if Offset is more than full span of BitWidth. If it is, the 5785 // expression is guaranteed to overflow. 5786 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5787 return ConstantRange::getFull(BitWidth); 5788 5789 // Offset is by how much the expression can change. Checks above guarantee no 5790 // overflow here. 5791 APInt Offset = Step * MaxBECount; 5792 5793 // Minimum value of the final range will match the minimal value of StartRange 5794 // if the expression is increasing and will be decreased by Offset otherwise. 5795 // Maximum value of the final range will match the maximal value of StartRange 5796 // if the expression is decreasing and will be increased by Offset otherwise. 5797 APInt StartLower = StartRange.getLower(); 5798 APInt StartUpper = StartRange.getUpper() - 1; 5799 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5800 : (StartUpper + std::move(Offset)); 5801 5802 // It's possible that the new minimum/maximum value will fall into the initial 5803 // range (due to wrap around). This means that the expression can take any 5804 // value in this bitwidth, and we have to return full range. 5805 if (StartRange.contains(MovedBoundary)) 5806 return ConstantRange::getFull(BitWidth); 5807 5808 APInt NewLower = 5809 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5810 APInt NewUpper = 5811 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5812 NewUpper += 1; 5813 5814 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5815 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5816 } 5817 5818 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5819 const SCEV *Step, 5820 const SCEV *MaxBECount, 5821 unsigned BitWidth) { 5822 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5823 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5824 "Precondition!"); 5825 5826 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5827 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5828 5829 // First, consider step signed. 5830 ConstantRange StartSRange = getSignedRange(Start); 5831 ConstantRange StepSRange = getSignedRange(Step); 5832 5833 // If Step can be both positive and negative, we need to find ranges for the 5834 // maximum absolute step values in both directions and union them. 5835 ConstantRange SR = 5836 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5837 MaxBECountValue, BitWidth, /* Signed = */ true); 5838 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5839 StartSRange, MaxBECountValue, 5840 BitWidth, /* Signed = */ true)); 5841 5842 // Next, consider step unsigned. 5843 ConstantRange UR = getRangeForAffineARHelper( 5844 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5845 MaxBECountValue, BitWidth, /* Signed = */ false); 5846 5847 // Finally, intersect signed and unsigned ranges. 5848 return SR.intersectWith(UR, ConstantRange::Smallest); 5849 } 5850 5851 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5852 const SCEV *Step, 5853 const SCEV *MaxBECount, 5854 unsigned BitWidth) { 5855 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5856 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5857 5858 struct SelectPattern { 5859 Value *Condition = nullptr; 5860 APInt TrueValue; 5861 APInt FalseValue; 5862 5863 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5864 const SCEV *S) { 5865 Optional<unsigned> CastOp; 5866 APInt Offset(BitWidth, 0); 5867 5868 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5869 "Should be!"); 5870 5871 // Peel off a constant offset: 5872 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5873 // In the future we could consider being smarter here and handle 5874 // {Start+Step,+,Step} too. 5875 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5876 return; 5877 5878 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5879 S = SA->getOperand(1); 5880 } 5881 5882 // Peel off a cast operation 5883 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5884 CastOp = SCast->getSCEVType(); 5885 S = SCast->getOperand(); 5886 } 5887 5888 using namespace llvm::PatternMatch; 5889 5890 auto *SU = dyn_cast<SCEVUnknown>(S); 5891 const APInt *TrueVal, *FalseVal; 5892 if (!SU || 5893 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5894 m_APInt(FalseVal)))) { 5895 Condition = nullptr; 5896 return; 5897 } 5898 5899 TrueValue = *TrueVal; 5900 FalseValue = *FalseVal; 5901 5902 // Re-apply the cast we peeled off earlier 5903 if (CastOp.hasValue()) 5904 switch (*CastOp) { 5905 default: 5906 llvm_unreachable("Unknown SCEV cast type!"); 5907 5908 case scTruncate: 5909 TrueValue = TrueValue.trunc(BitWidth); 5910 FalseValue = FalseValue.trunc(BitWidth); 5911 break; 5912 case scZeroExtend: 5913 TrueValue = TrueValue.zext(BitWidth); 5914 FalseValue = FalseValue.zext(BitWidth); 5915 break; 5916 case scSignExtend: 5917 TrueValue = TrueValue.sext(BitWidth); 5918 FalseValue = FalseValue.sext(BitWidth); 5919 break; 5920 } 5921 5922 // Re-apply the constant offset we peeled off earlier 5923 TrueValue += Offset; 5924 FalseValue += Offset; 5925 } 5926 5927 bool isRecognized() { return Condition != nullptr; } 5928 }; 5929 5930 SelectPattern StartPattern(*this, BitWidth, Start); 5931 if (!StartPattern.isRecognized()) 5932 return ConstantRange::getFull(BitWidth); 5933 5934 SelectPattern StepPattern(*this, BitWidth, Step); 5935 if (!StepPattern.isRecognized()) 5936 return ConstantRange::getFull(BitWidth); 5937 5938 if (StartPattern.Condition != StepPattern.Condition) { 5939 // We don't handle this case today; but we could, by considering four 5940 // possibilities below instead of two. I'm not sure if there are cases where 5941 // that will help over what getRange already does, though. 5942 return ConstantRange::getFull(BitWidth); 5943 } 5944 5945 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5946 // construct arbitrary general SCEV expressions here. This function is called 5947 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5948 // say) can end up caching a suboptimal value. 5949 5950 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5951 // C2352 and C2512 (otherwise it isn't needed). 5952 5953 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5954 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5955 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5956 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5957 5958 ConstantRange TrueRange = 5959 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5960 ConstantRange FalseRange = 5961 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5962 5963 return TrueRange.unionWith(FalseRange); 5964 } 5965 5966 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5967 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5968 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5969 5970 // Return early if there are no flags to propagate to the SCEV. 5971 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5972 if (BinOp->hasNoUnsignedWrap()) 5973 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5974 if (BinOp->hasNoSignedWrap()) 5975 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5976 if (Flags == SCEV::FlagAnyWrap) 5977 return SCEV::FlagAnyWrap; 5978 5979 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5980 } 5981 5982 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5983 // Here we check that I is in the header of the innermost loop containing I, 5984 // since we only deal with instructions in the loop header. The actual loop we 5985 // need to check later will come from an add recurrence, but getting that 5986 // requires computing the SCEV of the operands, which can be expensive. This 5987 // check we can do cheaply to rule out some cases early. 5988 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5989 if (InnermostContainingLoop == nullptr || 5990 InnermostContainingLoop->getHeader() != I->getParent()) 5991 return false; 5992 5993 // Only proceed if we can prove that I does not yield poison. 5994 if (!programUndefinedIfFullPoison(I)) 5995 return false; 5996 5997 // At this point we know that if I is executed, then it does not wrap 5998 // according to at least one of NSW or NUW. If I is not executed, then we do 5999 // not know if the calculation that I represents would wrap. Multiple 6000 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6001 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6002 // derived from other instructions that map to the same SCEV. We cannot make 6003 // that guarantee for cases where I is not executed. So we need to find the 6004 // loop that I is considered in relation to and prove that I is executed for 6005 // every iteration of that loop. That implies that the value that I 6006 // calculates does not wrap anywhere in the loop, so then we can apply the 6007 // flags to the SCEV. 6008 // 6009 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6010 // from different loops, so that we know which loop to prove that I is 6011 // executed in. 6012 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6013 // I could be an extractvalue from a call to an overflow intrinsic. 6014 // TODO: We can do better here in some cases. 6015 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6016 return false; 6017 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6018 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6019 bool AllOtherOpsLoopInvariant = true; 6020 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6021 ++OtherOpIndex) { 6022 if (OtherOpIndex != OpIndex) { 6023 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6024 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6025 AllOtherOpsLoopInvariant = false; 6026 break; 6027 } 6028 } 6029 } 6030 if (AllOtherOpsLoopInvariant && 6031 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6032 return true; 6033 } 6034 } 6035 return false; 6036 } 6037 6038 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6039 // If we know that \c I can never be poison period, then that's enough. 6040 if (isSCEVExprNeverPoison(I)) 6041 return true; 6042 6043 // For an add recurrence specifically, we assume that infinite loops without 6044 // side effects are undefined behavior, and then reason as follows: 6045 // 6046 // If the add recurrence is poison in any iteration, it is poison on all 6047 // future iterations (since incrementing poison yields poison). If the result 6048 // of the add recurrence is fed into the loop latch condition and the loop 6049 // does not contain any throws or exiting blocks other than the latch, we now 6050 // have the ability to "choose" whether the backedge is taken or not (by 6051 // choosing a sufficiently evil value for the poison feeding into the branch) 6052 // for every iteration including and after the one in which \p I first became 6053 // poison. There are two possibilities (let's call the iteration in which \p 6054 // I first became poison as K): 6055 // 6056 // 1. In the set of iterations including and after K, the loop body executes 6057 // no side effects. In this case executing the backege an infinte number 6058 // of times will yield undefined behavior. 6059 // 6060 // 2. In the set of iterations including and after K, the loop body executes 6061 // at least one side effect. In this case, that specific instance of side 6062 // effect is control dependent on poison, which also yields undefined 6063 // behavior. 6064 6065 auto *ExitingBB = L->getExitingBlock(); 6066 auto *LatchBB = L->getLoopLatch(); 6067 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6068 return false; 6069 6070 SmallPtrSet<const Instruction *, 16> Pushed; 6071 SmallVector<const Instruction *, 8> PoisonStack; 6072 6073 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6074 // things that are known to be fully poison under that assumption go on the 6075 // PoisonStack. 6076 Pushed.insert(I); 6077 PoisonStack.push_back(I); 6078 6079 bool LatchControlDependentOnPoison = false; 6080 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6081 const Instruction *Poison = PoisonStack.pop_back_val(); 6082 6083 for (auto *PoisonUser : Poison->users()) { 6084 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6085 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6086 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6087 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6088 assert(BI->isConditional() && "Only possibility!"); 6089 if (BI->getParent() == LatchBB) { 6090 LatchControlDependentOnPoison = true; 6091 break; 6092 } 6093 } 6094 } 6095 } 6096 6097 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6098 } 6099 6100 ScalarEvolution::LoopProperties 6101 ScalarEvolution::getLoopProperties(const Loop *L) { 6102 using LoopProperties = ScalarEvolution::LoopProperties; 6103 6104 auto Itr = LoopPropertiesCache.find(L); 6105 if (Itr == LoopPropertiesCache.end()) { 6106 auto HasSideEffects = [](Instruction *I) { 6107 if (auto *SI = dyn_cast<StoreInst>(I)) 6108 return !SI->isSimple(); 6109 6110 return I->mayHaveSideEffects(); 6111 }; 6112 6113 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6114 /*HasNoSideEffects*/ true}; 6115 6116 for (auto *BB : L->getBlocks()) 6117 for (auto &I : *BB) { 6118 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6119 LP.HasNoAbnormalExits = false; 6120 if (HasSideEffects(&I)) 6121 LP.HasNoSideEffects = false; 6122 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6123 break; // We're already as pessimistic as we can get. 6124 } 6125 6126 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6127 assert(InsertPair.second && "We just checked!"); 6128 Itr = InsertPair.first; 6129 } 6130 6131 return Itr->second; 6132 } 6133 6134 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6135 if (!isSCEVable(V->getType())) 6136 return getUnknown(V); 6137 6138 if (Instruction *I = dyn_cast<Instruction>(V)) { 6139 // Don't attempt to analyze instructions in blocks that aren't 6140 // reachable. Such instructions don't matter, and they aren't required 6141 // to obey basic rules for definitions dominating uses which this 6142 // analysis depends on. 6143 if (!DT.isReachableFromEntry(I->getParent())) 6144 return getUnknown(UndefValue::get(V->getType())); 6145 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6146 return getConstant(CI); 6147 else if (isa<ConstantPointerNull>(V)) 6148 return getZero(V->getType()); 6149 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6150 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6151 else if (!isa<ConstantExpr>(V)) 6152 return getUnknown(V); 6153 6154 Operator *U = cast<Operator>(V); 6155 if (auto BO = MatchBinaryOp(U, DT)) { 6156 switch (BO->Opcode) { 6157 case Instruction::Add: { 6158 // The simple thing to do would be to just call getSCEV on both operands 6159 // and call getAddExpr with the result. However if we're looking at a 6160 // bunch of things all added together, this can be quite inefficient, 6161 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6162 // Instead, gather up all the operands and make a single getAddExpr call. 6163 // LLVM IR canonical form means we need only traverse the left operands. 6164 SmallVector<const SCEV *, 4> AddOps; 6165 do { 6166 if (BO->Op) { 6167 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6168 AddOps.push_back(OpSCEV); 6169 break; 6170 } 6171 6172 // If a NUW or NSW flag can be applied to the SCEV for this 6173 // addition, then compute the SCEV for this addition by itself 6174 // with a separate call to getAddExpr. We need to do that 6175 // instead of pushing the operands of the addition onto AddOps, 6176 // since the flags are only known to apply to this particular 6177 // addition - they may not apply to other additions that can be 6178 // formed with operands from AddOps. 6179 const SCEV *RHS = getSCEV(BO->RHS); 6180 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6181 if (Flags != SCEV::FlagAnyWrap) { 6182 const SCEV *LHS = getSCEV(BO->LHS); 6183 if (BO->Opcode == Instruction::Sub) 6184 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6185 else 6186 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6187 break; 6188 } 6189 } 6190 6191 if (BO->Opcode == Instruction::Sub) 6192 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6193 else 6194 AddOps.push_back(getSCEV(BO->RHS)); 6195 6196 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6197 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6198 NewBO->Opcode != Instruction::Sub)) { 6199 AddOps.push_back(getSCEV(BO->LHS)); 6200 break; 6201 } 6202 BO = NewBO; 6203 } while (true); 6204 6205 return getAddExpr(AddOps); 6206 } 6207 6208 case Instruction::Mul: { 6209 SmallVector<const SCEV *, 4> MulOps; 6210 do { 6211 if (BO->Op) { 6212 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6213 MulOps.push_back(OpSCEV); 6214 break; 6215 } 6216 6217 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6218 if (Flags != SCEV::FlagAnyWrap) { 6219 MulOps.push_back( 6220 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6221 break; 6222 } 6223 } 6224 6225 MulOps.push_back(getSCEV(BO->RHS)); 6226 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6227 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6228 MulOps.push_back(getSCEV(BO->LHS)); 6229 break; 6230 } 6231 BO = NewBO; 6232 } while (true); 6233 6234 return getMulExpr(MulOps); 6235 } 6236 case Instruction::UDiv: 6237 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6238 case Instruction::URem: 6239 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6240 case Instruction::Sub: { 6241 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6242 if (BO->Op) 6243 Flags = getNoWrapFlagsFromUB(BO->Op); 6244 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6245 } 6246 case Instruction::And: 6247 // For an expression like x&255 that merely masks off the high bits, 6248 // use zext(trunc(x)) as the SCEV expression. 6249 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6250 if (CI->isZero()) 6251 return getSCEV(BO->RHS); 6252 if (CI->isMinusOne()) 6253 return getSCEV(BO->LHS); 6254 const APInt &A = CI->getValue(); 6255 6256 // Instcombine's ShrinkDemandedConstant may strip bits out of 6257 // constants, obscuring what would otherwise be a low-bits mask. 6258 // Use computeKnownBits to compute what ShrinkDemandedConstant 6259 // knew about to reconstruct a low-bits mask value. 6260 unsigned LZ = A.countLeadingZeros(); 6261 unsigned TZ = A.countTrailingZeros(); 6262 unsigned BitWidth = A.getBitWidth(); 6263 KnownBits Known(BitWidth); 6264 computeKnownBits(BO->LHS, Known, getDataLayout(), 6265 0, &AC, nullptr, &DT); 6266 6267 APInt EffectiveMask = 6268 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6269 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6270 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6271 const SCEV *LHS = getSCEV(BO->LHS); 6272 const SCEV *ShiftedLHS = nullptr; 6273 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6274 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6275 // For an expression like (x * 8) & 8, simplify the multiply. 6276 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6277 unsigned GCD = std::min(MulZeros, TZ); 6278 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6279 SmallVector<const SCEV*, 4> MulOps; 6280 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6281 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6282 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6283 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6284 } 6285 } 6286 if (!ShiftedLHS) 6287 ShiftedLHS = getUDivExpr(LHS, MulCount); 6288 return getMulExpr( 6289 getZeroExtendExpr( 6290 getTruncateExpr(ShiftedLHS, 6291 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6292 BO->LHS->getType()), 6293 MulCount); 6294 } 6295 } 6296 break; 6297 6298 case Instruction::Or: 6299 // If the RHS of the Or is a constant, we may have something like: 6300 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6301 // optimizations will transparently handle this case. 6302 // 6303 // In order for this transformation to be safe, the LHS must be of the 6304 // form X*(2^n) and the Or constant must be less than 2^n. 6305 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6306 const SCEV *LHS = getSCEV(BO->LHS); 6307 const APInt &CIVal = CI->getValue(); 6308 if (GetMinTrailingZeros(LHS) >= 6309 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6310 // Build a plain add SCEV. 6311 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6312 // If the LHS of the add was an addrec and it has no-wrap flags, 6313 // transfer the no-wrap flags, since an or won't introduce a wrap. 6314 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6315 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6316 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6317 OldAR->getNoWrapFlags()); 6318 } 6319 return S; 6320 } 6321 } 6322 break; 6323 6324 case Instruction::Xor: 6325 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6326 // If the RHS of xor is -1, then this is a not operation. 6327 if (CI->isMinusOne()) 6328 return getNotSCEV(getSCEV(BO->LHS)); 6329 6330 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6331 // This is a variant of the check for xor with -1, and it handles 6332 // the case where instcombine has trimmed non-demanded bits out 6333 // of an xor with -1. 6334 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6335 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6336 if (LBO->getOpcode() == Instruction::And && 6337 LCI->getValue() == CI->getValue()) 6338 if (const SCEVZeroExtendExpr *Z = 6339 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6340 Type *UTy = BO->LHS->getType(); 6341 const SCEV *Z0 = Z->getOperand(); 6342 Type *Z0Ty = Z0->getType(); 6343 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6344 6345 // If C is a low-bits mask, the zero extend is serving to 6346 // mask off the high bits. Complement the operand and 6347 // re-apply the zext. 6348 if (CI->getValue().isMask(Z0TySize)) 6349 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6350 6351 // If C is a single bit, it may be in the sign-bit position 6352 // before the zero-extend. In this case, represent the xor 6353 // using an add, which is equivalent, and re-apply the zext. 6354 APInt Trunc = CI->getValue().trunc(Z0TySize); 6355 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6356 Trunc.isSignMask()) 6357 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6358 UTy); 6359 } 6360 } 6361 break; 6362 6363 case Instruction::Shl: 6364 // Turn shift left of a constant amount into a multiply. 6365 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6366 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6367 6368 // If the shift count is not less than the bitwidth, the result of 6369 // the shift is undefined. Don't try to analyze it, because the 6370 // resolution chosen here may differ from the resolution chosen in 6371 // other parts of the compiler. 6372 if (SA->getValue().uge(BitWidth)) 6373 break; 6374 6375 // It is currently not resolved how to interpret NSW for left 6376 // shift by BitWidth - 1, so we avoid applying flags in that 6377 // case. Remove this check (or this comment) once the situation 6378 // is resolved. See 6379 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6380 // and http://reviews.llvm.org/D8890 . 6381 auto Flags = SCEV::FlagAnyWrap; 6382 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6383 Flags = getNoWrapFlagsFromUB(BO->Op); 6384 6385 Constant *X = ConstantInt::get( 6386 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6387 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6388 } 6389 break; 6390 6391 case Instruction::AShr: { 6392 // AShr X, C, where C is a constant. 6393 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6394 if (!CI) 6395 break; 6396 6397 Type *OuterTy = BO->LHS->getType(); 6398 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6399 // If the shift count is not less than the bitwidth, the result of 6400 // the shift is undefined. Don't try to analyze it, because the 6401 // resolution chosen here may differ from the resolution chosen in 6402 // other parts of the compiler. 6403 if (CI->getValue().uge(BitWidth)) 6404 break; 6405 6406 if (CI->isZero()) 6407 return getSCEV(BO->LHS); // shift by zero --> noop 6408 6409 uint64_t AShrAmt = CI->getZExtValue(); 6410 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6411 6412 Operator *L = dyn_cast<Operator>(BO->LHS); 6413 if (L && L->getOpcode() == Instruction::Shl) { 6414 // X = Shl A, n 6415 // Y = AShr X, m 6416 // Both n and m are constant. 6417 6418 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6419 if (L->getOperand(1) == BO->RHS) 6420 // For a two-shift sext-inreg, i.e. n = m, 6421 // use sext(trunc(x)) as the SCEV expression. 6422 return getSignExtendExpr( 6423 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6424 6425 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6426 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6427 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6428 if (ShlAmt > AShrAmt) { 6429 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6430 // expression. We already checked that ShlAmt < BitWidth, so 6431 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6432 // ShlAmt - AShrAmt < Amt. 6433 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6434 ShlAmt - AShrAmt); 6435 return getSignExtendExpr( 6436 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6437 getConstant(Mul)), OuterTy); 6438 } 6439 } 6440 } 6441 break; 6442 } 6443 } 6444 } 6445 6446 switch (U->getOpcode()) { 6447 case Instruction::Trunc: 6448 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6449 6450 case Instruction::ZExt: 6451 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6452 6453 case Instruction::SExt: 6454 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6455 // The NSW flag of a subtract does not always survive the conversion to 6456 // A + (-1)*B. By pushing sign extension onto its operands we are much 6457 // more likely to preserve NSW and allow later AddRec optimisations. 6458 // 6459 // NOTE: This is effectively duplicating this logic from getSignExtend: 6460 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6461 // but by that point the NSW information has potentially been lost. 6462 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6463 Type *Ty = U->getType(); 6464 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6465 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6466 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6467 } 6468 } 6469 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6470 6471 case Instruction::BitCast: 6472 // BitCasts are no-op casts so we just eliminate the cast. 6473 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6474 return getSCEV(U->getOperand(0)); 6475 break; 6476 6477 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6478 // lead to pointer expressions which cannot safely be expanded to GEPs, 6479 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6480 // simplifying integer expressions. 6481 6482 case Instruction::GetElementPtr: 6483 return createNodeForGEP(cast<GEPOperator>(U)); 6484 6485 case Instruction::PHI: 6486 return createNodeForPHI(cast<PHINode>(U)); 6487 6488 case Instruction::Select: 6489 // U can also be a select constant expr, which let fall through. Since 6490 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6491 // constant expressions cannot have instructions as operands, we'd have 6492 // returned getUnknown for a select constant expressions anyway. 6493 if (isa<Instruction>(U)) 6494 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6495 U->getOperand(1), U->getOperand(2)); 6496 break; 6497 6498 case Instruction::Call: 6499 case Instruction::Invoke: 6500 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6501 return getSCEV(RV); 6502 break; 6503 } 6504 6505 return getUnknown(V); 6506 } 6507 6508 //===----------------------------------------------------------------------===// 6509 // Iteration Count Computation Code 6510 // 6511 6512 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6513 if (!ExitCount) 6514 return 0; 6515 6516 ConstantInt *ExitConst = ExitCount->getValue(); 6517 6518 // Guard against huge trip counts. 6519 if (ExitConst->getValue().getActiveBits() > 32) 6520 return 0; 6521 6522 // In case of integer overflow, this returns 0, which is correct. 6523 return ((unsigned)ExitConst->getZExtValue()) + 1; 6524 } 6525 6526 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6527 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6528 return getSmallConstantTripCount(L, ExitingBB); 6529 6530 // No trip count information for multiple exits. 6531 return 0; 6532 } 6533 6534 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6535 BasicBlock *ExitingBlock) { 6536 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6537 assert(L->isLoopExiting(ExitingBlock) && 6538 "Exiting block must actually branch out of the loop!"); 6539 const SCEVConstant *ExitCount = 6540 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6541 return getConstantTripCount(ExitCount); 6542 } 6543 6544 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6545 const auto *MaxExitCount = 6546 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6547 return getConstantTripCount(MaxExitCount); 6548 } 6549 6550 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6551 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6552 return getSmallConstantTripMultiple(L, ExitingBB); 6553 6554 // No trip multiple information for multiple exits. 6555 return 0; 6556 } 6557 6558 /// Returns the largest constant divisor of the trip count of this loop as a 6559 /// normal unsigned value, if possible. This means that the actual trip count is 6560 /// always a multiple of the returned value (don't forget the trip count could 6561 /// very well be zero as well!). 6562 /// 6563 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6564 /// multiple of a constant (which is also the case if the trip count is simply 6565 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6566 /// if the trip count is very large (>= 2^32). 6567 /// 6568 /// As explained in the comments for getSmallConstantTripCount, this assumes 6569 /// that control exits the loop via ExitingBlock. 6570 unsigned 6571 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6572 BasicBlock *ExitingBlock) { 6573 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6574 assert(L->isLoopExiting(ExitingBlock) && 6575 "Exiting block must actually branch out of the loop!"); 6576 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6577 if (ExitCount == getCouldNotCompute()) 6578 return 1; 6579 6580 // Get the trip count from the BE count by adding 1. 6581 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6582 6583 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6584 if (!TC) 6585 // Attempt to factor more general cases. Returns the greatest power of 6586 // two divisor. If overflow happens, the trip count expression is still 6587 // divisible by the greatest power of 2 divisor returned. 6588 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6589 6590 ConstantInt *Result = TC->getValue(); 6591 6592 // Guard against huge trip counts (this requires checking 6593 // for zero to handle the case where the trip count == -1 and the 6594 // addition wraps). 6595 if (!Result || Result->getValue().getActiveBits() > 32 || 6596 Result->getValue().getActiveBits() == 0) 6597 return 1; 6598 6599 return (unsigned)Result->getZExtValue(); 6600 } 6601 6602 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6603 BasicBlock *ExitingBlock, 6604 ExitCountKind Kind) { 6605 switch (Kind) { 6606 case Exact: 6607 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6608 case ConstantMaximum: 6609 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6610 }; 6611 llvm_unreachable("Invalid ExitCountKind!"); 6612 } 6613 6614 const SCEV * 6615 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6616 SCEVUnionPredicate &Preds) { 6617 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6618 } 6619 6620 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6621 ExitCountKind Kind) { 6622 switch (Kind) { 6623 case Exact: 6624 return getBackedgeTakenInfo(L).getExact(L, this); 6625 case ConstantMaximum: 6626 return getBackedgeTakenInfo(L).getMax(this); 6627 }; 6628 llvm_unreachable("Invalid ExitCountKind!"); 6629 } 6630 6631 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6632 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6633 } 6634 6635 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6636 static void 6637 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6638 BasicBlock *Header = L->getHeader(); 6639 6640 // Push all Loop-header PHIs onto the Worklist stack. 6641 for (PHINode &PN : Header->phis()) 6642 Worklist.push_back(&PN); 6643 } 6644 6645 const ScalarEvolution::BackedgeTakenInfo & 6646 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6647 auto &BTI = getBackedgeTakenInfo(L); 6648 if (BTI.hasFullInfo()) 6649 return BTI; 6650 6651 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6652 6653 if (!Pair.second) 6654 return Pair.first->second; 6655 6656 BackedgeTakenInfo Result = 6657 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6658 6659 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6660 } 6661 6662 const ScalarEvolution::BackedgeTakenInfo & 6663 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6664 // Initially insert an invalid entry for this loop. If the insertion 6665 // succeeds, proceed to actually compute a backedge-taken count and 6666 // update the value. The temporary CouldNotCompute value tells SCEV 6667 // code elsewhere that it shouldn't attempt to request a new 6668 // backedge-taken count, which could result in infinite recursion. 6669 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6670 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6671 if (!Pair.second) 6672 return Pair.first->second; 6673 6674 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6675 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6676 // must be cleared in this scope. 6677 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6678 6679 // In product build, there are no usage of statistic. 6680 (void)NumTripCountsComputed; 6681 (void)NumTripCountsNotComputed; 6682 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6683 const SCEV *BEExact = Result.getExact(L, this); 6684 if (BEExact != getCouldNotCompute()) { 6685 assert(isLoopInvariant(BEExact, L) && 6686 isLoopInvariant(Result.getMax(this), L) && 6687 "Computed backedge-taken count isn't loop invariant for loop!"); 6688 ++NumTripCountsComputed; 6689 } 6690 else if (Result.getMax(this) == getCouldNotCompute() && 6691 isa<PHINode>(L->getHeader()->begin())) { 6692 // Only count loops that have phi nodes as not being computable. 6693 ++NumTripCountsNotComputed; 6694 } 6695 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6696 6697 // Now that we know more about the trip count for this loop, forget any 6698 // existing SCEV values for PHI nodes in this loop since they are only 6699 // conservative estimates made without the benefit of trip count 6700 // information. This is similar to the code in forgetLoop, except that 6701 // it handles SCEVUnknown PHI nodes specially. 6702 if (Result.hasAnyInfo()) { 6703 SmallVector<Instruction *, 16> Worklist; 6704 PushLoopPHIs(L, Worklist); 6705 6706 SmallPtrSet<Instruction *, 8> Discovered; 6707 while (!Worklist.empty()) { 6708 Instruction *I = Worklist.pop_back_val(); 6709 6710 ValueExprMapType::iterator It = 6711 ValueExprMap.find_as(static_cast<Value *>(I)); 6712 if (It != ValueExprMap.end()) { 6713 const SCEV *Old = It->second; 6714 6715 // SCEVUnknown for a PHI either means that it has an unrecognized 6716 // structure, or it's a PHI that's in the progress of being computed 6717 // by createNodeForPHI. In the former case, additional loop trip 6718 // count information isn't going to change anything. In the later 6719 // case, createNodeForPHI will perform the necessary updates on its 6720 // own when it gets to that point. 6721 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6722 eraseValueFromMap(It->first); 6723 forgetMemoizedResults(Old); 6724 } 6725 if (PHINode *PN = dyn_cast<PHINode>(I)) 6726 ConstantEvolutionLoopExitValue.erase(PN); 6727 } 6728 6729 // Since we don't need to invalidate anything for correctness and we're 6730 // only invalidating to make SCEV's results more precise, we get to stop 6731 // early to avoid invalidating too much. This is especially important in 6732 // cases like: 6733 // 6734 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6735 // loop0: 6736 // %pn0 = phi 6737 // ... 6738 // loop1: 6739 // %pn1 = phi 6740 // ... 6741 // 6742 // where both loop0 and loop1's backedge taken count uses the SCEV 6743 // expression for %v. If we don't have the early stop below then in cases 6744 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6745 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6746 // count for loop1, effectively nullifying SCEV's trip count cache. 6747 for (auto *U : I->users()) 6748 if (auto *I = dyn_cast<Instruction>(U)) { 6749 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6750 if (LoopForUser && L->contains(LoopForUser) && 6751 Discovered.insert(I).second) 6752 Worklist.push_back(I); 6753 } 6754 } 6755 } 6756 6757 // Re-lookup the insert position, since the call to 6758 // computeBackedgeTakenCount above could result in a 6759 // recusive call to getBackedgeTakenInfo (on a different 6760 // loop), which would invalidate the iterator computed 6761 // earlier. 6762 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6763 } 6764 6765 void ScalarEvolution::forgetAllLoops() { 6766 // This method is intended to forget all info about loops. It should 6767 // invalidate caches as if the following happened: 6768 // - The trip counts of all loops have changed arbitrarily 6769 // - Every llvm::Value has been updated in place to produce a different 6770 // result. 6771 BackedgeTakenCounts.clear(); 6772 PredicatedBackedgeTakenCounts.clear(); 6773 LoopPropertiesCache.clear(); 6774 ConstantEvolutionLoopExitValue.clear(); 6775 ValueExprMap.clear(); 6776 ValuesAtScopes.clear(); 6777 LoopDispositions.clear(); 6778 BlockDispositions.clear(); 6779 UnsignedRanges.clear(); 6780 SignedRanges.clear(); 6781 ExprValueMap.clear(); 6782 HasRecMap.clear(); 6783 MinTrailingZerosCache.clear(); 6784 PredicatedSCEVRewrites.clear(); 6785 } 6786 6787 void ScalarEvolution::forgetLoop(const Loop *L) { 6788 // Drop any stored trip count value. 6789 auto RemoveLoopFromBackedgeMap = 6790 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6791 auto BTCPos = Map.find(L); 6792 if (BTCPos != Map.end()) { 6793 BTCPos->second.clear(); 6794 Map.erase(BTCPos); 6795 } 6796 }; 6797 6798 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6799 SmallVector<Instruction *, 32> Worklist; 6800 SmallPtrSet<Instruction *, 16> Visited; 6801 6802 // Iterate over all the loops and sub-loops to drop SCEV information. 6803 while (!LoopWorklist.empty()) { 6804 auto *CurrL = LoopWorklist.pop_back_val(); 6805 6806 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6807 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6808 6809 // Drop information about predicated SCEV rewrites for this loop. 6810 for (auto I = PredicatedSCEVRewrites.begin(); 6811 I != PredicatedSCEVRewrites.end();) { 6812 std::pair<const SCEV *, const Loop *> Entry = I->first; 6813 if (Entry.second == CurrL) 6814 PredicatedSCEVRewrites.erase(I++); 6815 else 6816 ++I; 6817 } 6818 6819 auto LoopUsersItr = LoopUsers.find(CurrL); 6820 if (LoopUsersItr != LoopUsers.end()) { 6821 for (auto *S : LoopUsersItr->second) 6822 forgetMemoizedResults(S); 6823 LoopUsers.erase(LoopUsersItr); 6824 } 6825 6826 // Drop information about expressions based on loop-header PHIs. 6827 PushLoopPHIs(CurrL, Worklist); 6828 6829 while (!Worklist.empty()) { 6830 Instruction *I = Worklist.pop_back_val(); 6831 if (!Visited.insert(I).second) 6832 continue; 6833 6834 ValueExprMapType::iterator It = 6835 ValueExprMap.find_as(static_cast<Value *>(I)); 6836 if (It != ValueExprMap.end()) { 6837 eraseValueFromMap(It->first); 6838 forgetMemoizedResults(It->second); 6839 if (PHINode *PN = dyn_cast<PHINode>(I)) 6840 ConstantEvolutionLoopExitValue.erase(PN); 6841 } 6842 6843 PushDefUseChildren(I, Worklist); 6844 } 6845 6846 LoopPropertiesCache.erase(CurrL); 6847 // Forget all contained loops too, to avoid dangling entries in the 6848 // ValuesAtScopes map. 6849 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6850 } 6851 } 6852 6853 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6854 while (Loop *Parent = L->getParentLoop()) 6855 L = Parent; 6856 forgetLoop(L); 6857 } 6858 6859 void ScalarEvolution::forgetValue(Value *V) { 6860 Instruction *I = dyn_cast<Instruction>(V); 6861 if (!I) return; 6862 6863 // Drop information about expressions based on loop-header PHIs. 6864 SmallVector<Instruction *, 16> Worklist; 6865 Worklist.push_back(I); 6866 6867 SmallPtrSet<Instruction *, 8> Visited; 6868 while (!Worklist.empty()) { 6869 I = Worklist.pop_back_val(); 6870 if (!Visited.insert(I).second) 6871 continue; 6872 6873 ValueExprMapType::iterator It = 6874 ValueExprMap.find_as(static_cast<Value *>(I)); 6875 if (It != ValueExprMap.end()) { 6876 eraseValueFromMap(It->first); 6877 forgetMemoizedResults(It->second); 6878 if (PHINode *PN = dyn_cast<PHINode>(I)) 6879 ConstantEvolutionLoopExitValue.erase(PN); 6880 } 6881 6882 PushDefUseChildren(I, Worklist); 6883 } 6884 } 6885 6886 /// Get the exact loop backedge taken count considering all loop exits. A 6887 /// computable result can only be returned for loops with all exiting blocks 6888 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6889 /// is never skipped. This is a valid assumption as long as the loop exits via 6890 /// that test. For precise results, it is the caller's responsibility to specify 6891 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6892 const SCEV * 6893 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6894 SCEVUnionPredicate *Preds) const { 6895 // If any exits were not computable, the loop is not computable. 6896 if (!isComplete() || ExitNotTaken.empty()) 6897 return SE->getCouldNotCompute(); 6898 6899 const BasicBlock *Latch = L->getLoopLatch(); 6900 // All exiting blocks we have collected must dominate the only backedge. 6901 if (!Latch) 6902 return SE->getCouldNotCompute(); 6903 6904 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6905 // count is simply a minimum out of all these calculated exit counts. 6906 SmallVector<const SCEV *, 2> Ops; 6907 for (auto &ENT : ExitNotTaken) { 6908 const SCEV *BECount = ENT.ExactNotTaken; 6909 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6910 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6911 "We should only have known counts for exiting blocks that dominate " 6912 "latch!"); 6913 6914 Ops.push_back(BECount); 6915 6916 if (Preds && !ENT.hasAlwaysTruePredicate()) 6917 Preds->add(ENT.Predicate.get()); 6918 6919 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6920 "Predicate should be always true!"); 6921 } 6922 6923 return SE->getUMinFromMismatchedTypes(Ops); 6924 } 6925 6926 /// Get the exact not taken count for this loop exit. 6927 const SCEV * 6928 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6929 ScalarEvolution *SE) const { 6930 for (auto &ENT : ExitNotTaken) 6931 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6932 return ENT.ExactNotTaken; 6933 6934 return SE->getCouldNotCompute(); 6935 } 6936 6937 const SCEV * 6938 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 6939 ScalarEvolution *SE) const { 6940 for (auto &ENT : ExitNotTaken) 6941 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6942 return ENT.MaxNotTaken; 6943 6944 return SE->getCouldNotCompute(); 6945 } 6946 6947 /// getMax - Get the max backedge taken count for the loop. 6948 const SCEV * 6949 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6950 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6951 return !ENT.hasAlwaysTruePredicate(); 6952 }; 6953 6954 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6955 return SE->getCouldNotCompute(); 6956 6957 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6958 "No point in having a non-constant max backedge taken count!"); 6959 return getMax(); 6960 } 6961 6962 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6963 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6964 return !ENT.hasAlwaysTruePredicate(); 6965 }; 6966 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6967 } 6968 6969 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6970 ScalarEvolution *SE) const { 6971 if (getMax() && getMax() != SE->getCouldNotCompute() && 6972 SE->hasOperand(getMax(), S)) 6973 return true; 6974 6975 for (auto &ENT : ExitNotTaken) 6976 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6977 SE->hasOperand(ENT.ExactNotTaken, S)) 6978 return true; 6979 6980 return false; 6981 } 6982 6983 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6984 : ExactNotTaken(E), MaxNotTaken(E) { 6985 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6986 isa<SCEVConstant>(MaxNotTaken)) && 6987 "No point in having a non-constant max backedge taken count!"); 6988 } 6989 6990 ScalarEvolution::ExitLimit::ExitLimit( 6991 const SCEV *E, const SCEV *M, bool MaxOrZero, 6992 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6993 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6994 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6995 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6996 "Exact is not allowed to be less precise than Max"); 6997 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6998 isa<SCEVConstant>(MaxNotTaken)) && 6999 "No point in having a non-constant max backedge taken count!"); 7000 for (auto *PredSet : PredSetList) 7001 for (auto *P : *PredSet) 7002 addPredicate(P); 7003 } 7004 7005 ScalarEvolution::ExitLimit::ExitLimit( 7006 const SCEV *E, const SCEV *M, bool MaxOrZero, 7007 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7008 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7009 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7010 isa<SCEVConstant>(MaxNotTaken)) && 7011 "No point in having a non-constant max backedge taken count!"); 7012 } 7013 7014 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7015 bool MaxOrZero) 7016 : ExitLimit(E, M, MaxOrZero, None) { 7017 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7018 isa<SCEVConstant>(MaxNotTaken)) && 7019 "No point in having a non-constant max backedge taken count!"); 7020 } 7021 7022 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7023 /// computable exit into a persistent ExitNotTakenInfo array. 7024 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7025 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7026 ExitCounts, 7027 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7028 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7029 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7030 7031 ExitNotTaken.reserve(ExitCounts.size()); 7032 std::transform( 7033 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7034 [&](const EdgeExitInfo &EEI) { 7035 BasicBlock *ExitBB = EEI.first; 7036 const ExitLimit &EL = EEI.second; 7037 if (EL.Predicates.empty()) 7038 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7039 nullptr); 7040 7041 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7042 for (auto *Pred : EL.Predicates) 7043 Predicate->add(Pred); 7044 7045 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7046 std::move(Predicate)); 7047 }); 7048 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7049 "No point in having a non-constant max backedge taken count!"); 7050 } 7051 7052 /// Invalidate this result and free the ExitNotTakenInfo array. 7053 void ScalarEvolution::BackedgeTakenInfo::clear() { 7054 ExitNotTaken.clear(); 7055 } 7056 7057 /// Compute the number of times the backedge of the specified loop will execute. 7058 ScalarEvolution::BackedgeTakenInfo 7059 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7060 bool AllowPredicates) { 7061 SmallVector<BasicBlock *, 8> ExitingBlocks; 7062 L->getExitingBlocks(ExitingBlocks); 7063 7064 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7065 7066 SmallVector<EdgeExitInfo, 4> ExitCounts; 7067 bool CouldComputeBECount = true; 7068 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7069 const SCEV *MustExitMaxBECount = nullptr; 7070 const SCEV *MayExitMaxBECount = nullptr; 7071 bool MustExitMaxOrZero = false; 7072 7073 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7074 // and compute maxBECount. 7075 // Do a union of all the predicates here. 7076 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7077 BasicBlock *ExitBB = ExitingBlocks[i]; 7078 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7079 7080 assert((AllowPredicates || EL.Predicates.empty()) && 7081 "Predicated exit limit when predicates are not allowed!"); 7082 7083 // 1. For each exit that can be computed, add an entry to ExitCounts. 7084 // CouldComputeBECount is true only if all exits can be computed. 7085 if (EL.ExactNotTaken == getCouldNotCompute()) 7086 // We couldn't compute an exact value for this exit, so 7087 // we won't be able to compute an exact value for the loop. 7088 CouldComputeBECount = false; 7089 else 7090 ExitCounts.emplace_back(ExitBB, EL); 7091 7092 // 2. Derive the loop's MaxBECount from each exit's max number of 7093 // non-exiting iterations. Partition the loop exits into two kinds: 7094 // LoopMustExits and LoopMayExits. 7095 // 7096 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7097 // is a LoopMayExit. If any computable LoopMustExit is found, then 7098 // MaxBECount is the minimum EL.MaxNotTaken of computable 7099 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7100 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7101 // computable EL.MaxNotTaken. 7102 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7103 DT.dominates(ExitBB, Latch)) { 7104 if (!MustExitMaxBECount) { 7105 MustExitMaxBECount = EL.MaxNotTaken; 7106 MustExitMaxOrZero = EL.MaxOrZero; 7107 } else { 7108 MustExitMaxBECount = 7109 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7110 } 7111 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7112 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7113 MayExitMaxBECount = EL.MaxNotTaken; 7114 else { 7115 MayExitMaxBECount = 7116 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7117 } 7118 } 7119 } 7120 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7121 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7122 // The loop backedge will be taken the maximum or zero times if there's 7123 // a single exit that must be taken the maximum or zero times. 7124 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7125 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7126 MaxBECount, MaxOrZero); 7127 } 7128 7129 ScalarEvolution::ExitLimit 7130 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7131 bool AllowPredicates) { 7132 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7133 // If our exiting block does not dominate the latch, then its connection with 7134 // loop's exit limit may be far from trivial. 7135 const BasicBlock *Latch = L->getLoopLatch(); 7136 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7137 return getCouldNotCompute(); 7138 7139 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7140 Instruction *Term = ExitingBlock->getTerminator(); 7141 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7142 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7143 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7144 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7145 "It should have one successor in loop and one exit block!"); 7146 // Proceed to the next level to examine the exit condition expression. 7147 return computeExitLimitFromCond( 7148 L, BI->getCondition(), ExitIfTrue, 7149 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7150 } 7151 7152 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7153 // For switch, make sure that there is a single exit from the loop. 7154 BasicBlock *Exit = nullptr; 7155 for (auto *SBB : successors(ExitingBlock)) 7156 if (!L->contains(SBB)) { 7157 if (Exit) // Multiple exit successors. 7158 return getCouldNotCompute(); 7159 Exit = SBB; 7160 } 7161 assert(Exit && "Exiting block must have at least one exit"); 7162 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7163 /*ControlsExit=*/IsOnlyExit); 7164 } 7165 7166 return getCouldNotCompute(); 7167 } 7168 7169 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7170 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7171 bool ControlsExit, bool AllowPredicates) { 7172 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7173 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7174 ControlsExit, AllowPredicates); 7175 } 7176 7177 Optional<ScalarEvolution::ExitLimit> 7178 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7179 bool ExitIfTrue, bool ControlsExit, 7180 bool AllowPredicates) { 7181 (void)this->L; 7182 (void)this->ExitIfTrue; 7183 (void)this->AllowPredicates; 7184 7185 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7186 this->AllowPredicates == AllowPredicates && 7187 "Variance in assumed invariant key components!"); 7188 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7189 if (Itr == TripCountMap.end()) 7190 return None; 7191 return Itr->second; 7192 } 7193 7194 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7195 bool ExitIfTrue, 7196 bool ControlsExit, 7197 bool AllowPredicates, 7198 const ExitLimit &EL) { 7199 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7200 this->AllowPredicates == AllowPredicates && 7201 "Variance in assumed invariant key components!"); 7202 7203 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7204 assert(InsertResult.second && "Expected successful insertion!"); 7205 (void)InsertResult; 7206 (void)ExitIfTrue; 7207 } 7208 7209 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7210 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7211 bool ControlsExit, bool AllowPredicates) { 7212 7213 if (auto MaybeEL = 7214 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7215 return *MaybeEL; 7216 7217 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7218 ControlsExit, AllowPredicates); 7219 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7220 return EL; 7221 } 7222 7223 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7224 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7225 bool ControlsExit, bool AllowPredicates) { 7226 // Check if the controlling expression for this loop is an And or Or. 7227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7228 if (BO->getOpcode() == Instruction::And) { 7229 // Recurse on the operands of the and. 7230 bool EitherMayExit = !ExitIfTrue; 7231 ExitLimit EL0 = computeExitLimitFromCondCached( 7232 Cache, L, BO->getOperand(0), ExitIfTrue, 7233 ControlsExit && !EitherMayExit, AllowPredicates); 7234 ExitLimit EL1 = computeExitLimitFromCondCached( 7235 Cache, L, BO->getOperand(1), ExitIfTrue, 7236 ControlsExit && !EitherMayExit, AllowPredicates); 7237 const SCEV *BECount = getCouldNotCompute(); 7238 const SCEV *MaxBECount = getCouldNotCompute(); 7239 if (EitherMayExit) { 7240 // Both conditions must be true for the loop to continue executing. 7241 // Choose the less conservative count. 7242 if (EL0.ExactNotTaken == getCouldNotCompute() || 7243 EL1.ExactNotTaken == getCouldNotCompute()) 7244 BECount = getCouldNotCompute(); 7245 else 7246 BECount = 7247 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7248 if (EL0.MaxNotTaken == getCouldNotCompute()) 7249 MaxBECount = EL1.MaxNotTaken; 7250 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7251 MaxBECount = EL0.MaxNotTaken; 7252 else 7253 MaxBECount = 7254 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7255 } else { 7256 // Both conditions must be true at the same time for the loop to exit. 7257 // For now, be conservative. 7258 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7259 MaxBECount = EL0.MaxNotTaken; 7260 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7261 BECount = EL0.ExactNotTaken; 7262 } 7263 7264 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7265 // to be more aggressive when computing BECount than when computing 7266 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7267 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7268 // to not. 7269 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7270 !isa<SCEVCouldNotCompute>(BECount)) 7271 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7272 7273 return ExitLimit(BECount, MaxBECount, false, 7274 {&EL0.Predicates, &EL1.Predicates}); 7275 } 7276 if (BO->getOpcode() == Instruction::Or) { 7277 // Recurse on the operands of the or. 7278 bool EitherMayExit = ExitIfTrue; 7279 ExitLimit EL0 = computeExitLimitFromCondCached( 7280 Cache, L, BO->getOperand(0), ExitIfTrue, 7281 ControlsExit && !EitherMayExit, AllowPredicates); 7282 ExitLimit EL1 = computeExitLimitFromCondCached( 7283 Cache, L, BO->getOperand(1), ExitIfTrue, 7284 ControlsExit && !EitherMayExit, AllowPredicates); 7285 const SCEV *BECount = getCouldNotCompute(); 7286 const SCEV *MaxBECount = getCouldNotCompute(); 7287 if (EitherMayExit) { 7288 // Both conditions must be false for the loop to continue executing. 7289 // Choose the less conservative count. 7290 if (EL0.ExactNotTaken == getCouldNotCompute() || 7291 EL1.ExactNotTaken == getCouldNotCompute()) 7292 BECount = getCouldNotCompute(); 7293 else 7294 BECount = 7295 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7296 if (EL0.MaxNotTaken == getCouldNotCompute()) 7297 MaxBECount = EL1.MaxNotTaken; 7298 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7299 MaxBECount = EL0.MaxNotTaken; 7300 else 7301 MaxBECount = 7302 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7303 } else { 7304 // Both conditions must be false at the same time for the loop to exit. 7305 // For now, be conservative. 7306 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7307 MaxBECount = EL0.MaxNotTaken; 7308 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7309 BECount = EL0.ExactNotTaken; 7310 } 7311 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7312 // to be more aggressive when computing BECount than when computing 7313 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7314 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7315 // to not. 7316 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7317 !isa<SCEVCouldNotCompute>(BECount)) 7318 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7319 7320 return ExitLimit(BECount, MaxBECount, false, 7321 {&EL0.Predicates, &EL1.Predicates}); 7322 } 7323 } 7324 7325 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7326 // Proceed to the next level to examine the icmp. 7327 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7328 ExitLimit EL = 7329 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7330 if (EL.hasFullInfo() || !AllowPredicates) 7331 return EL; 7332 7333 // Try again, but use SCEV predicates this time. 7334 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7335 /*AllowPredicates=*/true); 7336 } 7337 7338 // Check for a constant condition. These are normally stripped out by 7339 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7340 // preserve the CFG and is temporarily leaving constant conditions 7341 // in place. 7342 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7343 if (ExitIfTrue == !CI->getZExtValue()) 7344 // The backedge is always taken. 7345 return getCouldNotCompute(); 7346 else 7347 // The backedge is never taken. 7348 return getZero(CI->getType()); 7349 } 7350 7351 // If it's not an integer or pointer comparison then compute it the hard way. 7352 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7353 } 7354 7355 ScalarEvolution::ExitLimit 7356 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7357 ICmpInst *ExitCond, 7358 bool ExitIfTrue, 7359 bool ControlsExit, 7360 bool AllowPredicates) { 7361 // If the condition was exit on true, convert the condition to exit on false 7362 ICmpInst::Predicate Pred; 7363 if (!ExitIfTrue) 7364 Pred = ExitCond->getPredicate(); 7365 else 7366 Pred = ExitCond->getInversePredicate(); 7367 const ICmpInst::Predicate OriginalPred = Pred; 7368 7369 // Handle common loops like: for (X = "string"; *X; ++X) 7370 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7371 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7372 ExitLimit ItCnt = 7373 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7374 if (ItCnt.hasAnyInfo()) 7375 return ItCnt; 7376 } 7377 7378 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7379 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7380 7381 // Try to evaluate any dependencies out of the loop. 7382 LHS = getSCEVAtScope(LHS, L); 7383 RHS = getSCEVAtScope(RHS, L); 7384 7385 // At this point, we would like to compute how many iterations of the 7386 // loop the predicate will return true for these inputs. 7387 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7388 // If there is a loop-invariant, force it into the RHS. 7389 std::swap(LHS, RHS); 7390 Pred = ICmpInst::getSwappedPredicate(Pred); 7391 } 7392 7393 // Simplify the operands before analyzing them. 7394 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7395 7396 // If we have a comparison of a chrec against a constant, try to use value 7397 // ranges to answer this query. 7398 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7399 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7400 if (AddRec->getLoop() == L) { 7401 // Form the constant range. 7402 ConstantRange CompRange = 7403 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7404 7405 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7406 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7407 } 7408 7409 switch (Pred) { 7410 case ICmpInst::ICMP_NE: { // while (X != Y) 7411 // Convert to: while (X-Y != 0) 7412 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7413 AllowPredicates); 7414 if (EL.hasAnyInfo()) return EL; 7415 break; 7416 } 7417 case ICmpInst::ICMP_EQ: { // while (X == Y) 7418 // Convert to: while (X-Y == 0) 7419 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7420 if (EL.hasAnyInfo()) return EL; 7421 break; 7422 } 7423 case ICmpInst::ICMP_SLT: 7424 case ICmpInst::ICMP_ULT: { // while (X < Y) 7425 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7426 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7427 AllowPredicates); 7428 if (EL.hasAnyInfo()) return EL; 7429 break; 7430 } 7431 case ICmpInst::ICMP_SGT: 7432 case ICmpInst::ICMP_UGT: { // while (X > Y) 7433 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7434 ExitLimit EL = 7435 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7436 AllowPredicates); 7437 if (EL.hasAnyInfo()) return EL; 7438 break; 7439 } 7440 default: 7441 break; 7442 } 7443 7444 auto *ExhaustiveCount = 7445 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7446 7447 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7448 return ExhaustiveCount; 7449 7450 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7451 ExitCond->getOperand(1), L, OriginalPred); 7452 } 7453 7454 ScalarEvolution::ExitLimit 7455 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7456 SwitchInst *Switch, 7457 BasicBlock *ExitingBlock, 7458 bool ControlsExit) { 7459 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7460 7461 // Give up if the exit is the default dest of a switch. 7462 if (Switch->getDefaultDest() == ExitingBlock) 7463 return getCouldNotCompute(); 7464 7465 assert(L->contains(Switch->getDefaultDest()) && 7466 "Default case must not exit the loop!"); 7467 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7468 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7469 7470 // while (X != Y) --> while (X-Y != 0) 7471 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7472 if (EL.hasAnyInfo()) 7473 return EL; 7474 7475 return getCouldNotCompute(); 7476 } 7477 7478 static ConstantInt * 7479 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7480 ScalarEvolution &SE) { 7481 const SCEV *InVal = SE.getConstant(C); 7482 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7483 assert(isa<SCEVConstant>(Val) && 7484 "Evaluation of SCEV at constant didn't fold correctly?"); 7485 return cast<SCEVConstant>(Val)->getValue(); 7486 } 7487 7488 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7489 /// compute the backedge execution count. 7490 ScalarEvolution::ExitLimit 7491 ScalarEvolution::computeLoadConstantCompareExitLimit( 7492 LoadInst *LI, 7493 Constant *RHS, 7494 const Loop *L, 7495 ICmpInst::Predicate predicate) { 7496 if (LI->isVolatile()) return getCouldNotCompute(); 7497 7498 // Check to see if the loaded pointer is a getelementptr of a global. 7499 // TODO: Use SCEV instead of manually grubbing with GEPs. 7500 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7501 if (!GEP) return getCouldNotCompute(); 7502 7503 // Make sure that it is really a constant global we are gepping, with an 7504 // initializer, and make sure the first IDX is really 0. 7505 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7506 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7507 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7508 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7509 return getCouldNotCompute(); 7510 7511 // Okay, we allow one non-constant index into the GEP instruction. 7512 Value *VarIdx = nullptr; 7513 std::vector<Constant*> Indexes; 7514 unsigned VarIdxNum = 0; 7515 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7516 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7517 Indexes.push_back(CI); 7518 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7519 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7520 VarIdx = GEP->getOperand(i); 7521 VarIdxNum = i-2; 7522 Indexes.push_back(nullptr); 7523 } 7524 7525 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7526 if (!VarIdx) 7527 return getCouldNotCompute(); 7528 7529 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7530 // Check to see if X is a loop variant variable value now. 7531 const SCEV *Idx = getSCEV(VarIdx); 7532 Idx = getSCEVAtScope(Idx, L); 7533 7534 // We can only recognize very limited forms of loop index expressions, in 7535 // particular, only affine AddRec's like {C1,+,C2}. 7536 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7537 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7538 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7539 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7540 return getCouldNotCompute(); 7541 7542 unsigned MaxSteps = MaxBruteForceIterations; 7543 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7544 ConstantInt *ItCst = ConstantInt::get( 7545 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7546 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7547 7548 // Form the GEP offset. 7549 Indexes[VarIdxNum] = Val; 7550 7551 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7552 Indexes); 7553 if (!Result) break; // Cannot compute! 7554 7555 // Evaluate the condition for this iteration. 7556 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7557 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7558 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7559 ++NumArrayLenItCounts; 7560 return getConstant(ItCst); // Found terminating iteration! 7561 } 7562 } 7563 return getCouldNotCompute(); 7564 } 7565 7566 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7567 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7568 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7569 if (!RHS) 7570 return getCouldNotCompute(); 7571 7572 const BasicBlock *Latch = L->getLoopLatch(); 7573 if (!Latch) 7574 return getCouldNotCompute(); 7575 7576 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7577 if (!Predecessor) 7578 return getCouldNotCompute(); 7579 7580 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7581 // Return LHS in OutLHS and shift_opt in OutOpCode. 7582 auto MatchPositiveShift = 7583 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7584 7585 using namespace PatternMatch; 7586 7587 ConstantInt *ShiftAmt; 7588 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7589 OutOpCode = Instruction::LShr; 7590 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7591 OutOpCode = Instruction::AShr; 7592 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7593 OutOpCode = Instruction::Shl; 7594 else 7595 return false; 7596 7597 return ShiftAmt->getValue().isStrictlyPositive(); 7598 }; 7599 7600 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7601 // 7602 // loop: 7603 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7604 // %iv.shifted = lshr i32 %iv, <positive constant> 7605 // 7606 // Return true on a successful match. Return the corresponding PHI node (%iv 7607 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7608 auto MatchShiftRecurrence = 7609 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7610 Optional<Instruction::BinaryOps> PostShiftOpCode; 7611 7612 { 7613 Instruction::BinaryOps OpC; 7614 Value *V; 7615 7616 // If we encounter a shift instruction, "peel off" the shift operation, 7617 // and remember that we did so. Later when we inspect %iv's backedge 7618 // value, we will make sure that the backedge value uses the same 7619 // operation. 7620 // 7621 // Note: the peeled shift operation does not have to be the same 7622 // instruction as the one feeding into the PHI's backedge value. We only 7623 // really care about it being the same *kind* of shift instruction -- 7624 // that's all that is required for our later inferences to hold. 7625 if (MatchPositiveShift(LHS, V, OpC)) { 7626 PostShiftOpCode = OpC; 7627 LHS = V; 7628 } 7629 } 7630 7631 PNOut = dyn_cast<PHINode>(LHS); 7632 if (!PNOut || PNOut->getParent() != L->getHeader()) 7633 return false; 7634 7635 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7636 Value *OpLHS; 7637 7638 return 7639 // The backedge value for the PHI node must be a shift by a positive 7640 // amount 7641 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7642 7643 // of the PHI node itself 7644 OpLHS == PNOut && 7645 7646 // and the kind of shift should be match the kind of shift we peeled 7647 // off, if any. 7648 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7649 }; 7650 7651 PHINode *PN; 7652 Instruction::BinaryOps OpCode; 7653 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7654 return getCouldNotCompute(); 7655 7656 const DataLayout &DL = getDataLayout(); 7657 7658 // The key rationale for this optimization is that for some kinds of shift 7659 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7660 // within a finite number of iterations. If the condition guarding the 7661 // backedge (in the sense that the backedge is taken if the condition is true) 7662 // is false for the value the shift recurrence stabilizes to, then we know 7663 // that the backedge is taken only a finite number of times. 7664 7665 ConstantInt *StableValue = nullptr; 7666 switch (OpCode) { 7667 default: 7668 llvm_unreachable("Impossible case!"); 7669 7670 case Instruction::AShr: { 7671 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7672 // bitwidth(K) iterations. 7673 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7674 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7675 Predecessor->getTerminator(), &DT); 7676 auto *Ty = cast<IntegerType>(RHS->getType()); 7677 if (Known.isNonNegative()) 7678 StableValue = ConstantInt::get(Ty, 0); 7679 else if (Known.isNegative()) 7680 StableValue = ConstantInt::get(Ty, -1, true); 7681 else 7682 return getCouldNotCompute(); 7683 7684 break; 7685 } 7686 case Instruction::LShr: 7687 case Instruction::Shl: 7688 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7689 // stabilize to 0 in at most bitwidth(K) iterations. 7690 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7691 break; 7692 } 7693 7694 auto *Result = 7695 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7696 assert(Result->getType()->isIntegerTy(1) && 7697 "Otherwise cannot be an operand to a branch instruction"); 7698 7699 if (Result->isZeroValue()) { 7700 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7701 const SCEV *UpperBound = 7702 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7703 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7704 } 7705 7706 return getCouldNotCompute(); 7707 } 7708 7709 /// Return true if we can constant fold an instruction of the specified type, 7710 /// assuming that all operands were constants. 7711 static bool CanConstantFold(const Instruction *I) { 7712 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7713 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7714 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7715 return true; 7716 7717 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7718 if (const Function *F = CI->getCalledFunction()) 7719 return canConstantFoldCallTo(CI, F); 7720 return false; 7721 } 7722 7723 /// Determine whether this instruction can constant evolve within this loop 7724 /// assuming its operands can all constant evolve. 7725 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7726 // An instruction outside of the loop can't be derived from a loop PHI. 7727 if (!L->contains(I)) return false; 7728 7729 if (isa<PHINode>(I)) { 7730 // We don't currently keep track of the control flow needed to evaluate 7731 // PHIs, so we cannot handle PHIs inside of loops. 7732 return L->getHeader() == I->getParent(); 7733 } 7734 7735 // If we won't be able to constant fold this expression even if the operands 7736 // are constants, bail early. 7737 return CanConstantFold(I); 7738 } 7739 7740 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7741 /// recursing through each instruction operand until reaching a loop header phi. 7742 static PHINode * 7743 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7744 DenseMap<Instruction *, PHINode *> &PHIMap, 7745 unsigned Depth) { 7746 if (Depth > MaxConstantEvolvingDepth) 7747 return nullptr; 7748 7749 // Otherwise, we can evaluate this instruction if all of its operands are 7750 // constant or derived from a PHI node themselves. 7751 PHINode *PHI = nullptr; 7752 for (Value *Op : UseInst->operands()) { 7753 if (isa<Constant>(Op)) continue; 7754 7755 Instruction *OpInst = dyn_cast<Instruction>(Op); 7756 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7757 7758 PHINode *P = dyn_cast<PHINode>(OpInst); 7759 if (!P) 7760 // If this operand is already visited, reuse the prior result. 7761 // We may have P != PHI if this is the deepest point at which the 7762 // inconsistent paths meet. 7763 P = PHIMap.lookup(OpInst); 7764 if (!P) { 7765 // Recurse and memoize the results, whether a phi is found or not. 7766 // This recursive call invalidates pointers into PHIMap. 7767 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7768 PHIMap[OpInst] = P; 7769 } 7770 if (!P) 7771 return nullptr; // Not evolving from PHI 7772 if (PHI && PHI != P) 7773 return nullptr; // Evolving from multiple different PHIs. 7774 PHI = P; 7775 } 7776 // This is a expression evolving from a constant PHI! 7777 return PHI; 7778 } 7779 7780 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7781 /// in the loop that V is derived from. We allow arbitrary operations along the 7782 /// way, but the operands of an operation must either be constants or a value 7783 /// derived from a constant PHI. If this expression does not fit with these 7784 /// constraints, return null. 7785 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7786 Instruction *I = dyn_cast<Instruction>(V); 7787 if (!I || !canConstantEvolve(I, L)) return nullptr; 7788 7789 if (PHINode *PN = dyn_cast<PHINode>(I)) 7790 return PN; 7791 7792 // Record non-constant instructions contained by the loop. 7793 DenseMap<Instruction *, PHINode *> PHIMap; 7794 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7795 } 7796 7797 /// EvaluateExpression - Given an expression that passes the 7798 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7799 /// in the loop has the value PHIVal. If we can't fold this expression for some 7800 /// reason, return null. 7801 static Constant *EvaluateExpression(Value *V, const Loop *L, 7802 DenseMap<Instruction *, Constant *> &Vals, 7803 const DataLayout &DL, 7804 const TargetLibraryInfo *TLI) { 7805 // Convenient constant check, but redundant for recursive calls. 7806 if (Constant *C = dyn_cast<Constant>(V)) return C; 7807 Instruction *I = dyn_cast<Instruction>(V); 7808 if (!I) return nullptr; 7809 7810 if (Constant *C = Vals.lookup(I)) return C; 7811 7812 // An instruction inside the loop depends on a value outside the loop that we 7813 // weren't given a mapping for, or a value such as a call inside the loop. 7814 if (!canConstantEvolve(I, L)) return nullptr; 7815 7816 // An unmapped PHI can be due to a branch or another loop inside this loop, 7817 // or due to this not being the initial iteration through a loop where we 7818 // couldn't compute the evolution of this particular PHI last time. 7819 if (isa<PHINode>(I)) return nullptr; 7820 7821 std::vector<Constant*> Operands(I->getNumOperands()); 7822 7823 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7824 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7825 if (!Operand) { 7826 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7827 if (!Operands[i]) return nullptr; 7828 continue; 7829 } 7830 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7831 Vals[Operand] = C; 7832 if (!C) return nullptr; 7833 Operands[i] = C; 7834 } 7835 7836 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7837 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7838 Operands[1], DL, TLI); 7839 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7840 if (!LI->isVolatile()) 7841 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7842 } 7843 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7844 } 7845 7846 7847 // If every incoming value to PN except the one for BB is a specific Constant, 7848 // return that, else return nullptr. 7849 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7850 Constant *IncomingVal = nullptr; 7851 7852 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7853 if (PN->getIncomingBlock(i) == BB) 7854 continue; 7855 7856 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7857 if (!CurrentVal) 7858 return nullptr; 7859 7860 if (IncomingVal != CurrentVal) { 7861 if (IncomingVal) 7862 return nullptr; 7863 IncomingVal = CurrentVal; 7864 } 7865 } 7866 7867 return IncomingVal; 7868 } 7869 7870 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7871 /// in the header of its containing loop, we know the loop executes a 7872 /// constant number of times, and the PHI node is just a recurrence 7873 /// involving constants, fold it. 7874 Constant * 7875 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7876 const APInt &BEs, 7877 const Loop *L) { 7878 auto I = ConstantEvolutionLoopExitValue.find(PN); 7879 if (I != ConstantEvolutionLoopExitValue.end()) 7880 return I->second; 7881 7882 if (BEs.ugt(MaxBruteForceIterations)) 7883 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7884 7885 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7886 7887 DenseMap<Instruction *, Constant *> CurrentIterVals; 7888 BasicBlock *Header = L->getHeader(); 7889 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7890 7891 BasicBlock *Latch = L->getLoopLatch(); 7892 if (!Latch) 7893 return nullptr; 7894 7895 for (PHINode &PHI : Header->phis()) { 7896 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7897 CurrentIterVals[&PHI] = StartCST; 7898 } 7899 if (!CurrentIterVals.count(PN)) 7900 return RetVal = nullptr; 7901 7902 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7903 7904 // Execute the loop symbolically to determine the exit value. 7905 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7906 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7907 7908 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7909 unsigned IterationNum = 0; 7910 const DataLayout &DL = getDataLayout(); 7911 for (; ; ++IterationNum) { 7912 if (IterationNum == NumIterations) 7913 return RetVal = CurrentIterVals[PN]; // Got exit value! 7914 7915 // Compute the value of the PHIs for the next iteration. 7916 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7917 DenseMap<Instruction *, Constant *> NextIterVals; 7918 Constant *NextPHI = 7919 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7920 if (!NextPHI) 7921 return nullptr; // Couldn't evaluate! 7922 NextIterVals[PN] = NextPHI; 7923 7924 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7925 7926 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7927 // cease to be able to evaluate one of them or if they stop evolving, 7928 // because that doesn't necessarily prevent us from computing PN. 7929 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7930 for (const auto &I : CurrentIterVals) { 7931 PHINode *PHI = dyn_cast<PHINode>(I.first); 7932 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7933 PHIsToCompute.emplace_back(PHI, I.second); 7934 } 7935 // We use two distinct loops because EvaluateExpression may invalidate any 7936 // iterators into CurrentIterVals. 7937 for (const auto &I : PHIsToCompute) { 7938 PHINode *PHI = I.first; 7939 Constant *&NextPHI = NextIterVals[PHI]; 7940 if (!NextPHI) { // Not already computed. 7941 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7942 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7943 } 7944 if (NextPHI != I.second) 7945 StoppedEvolving = false; 7946 } 7947 7948 // If all entries in CurrentIterVals == NextIterVals then we can stop 7949 // iterating, the loop can't continue to change. 7950 if (StoppedEvolving) 7951 return RetVal = CurrentIterVals[PN]; 7952 7953 CurrentIterVals.swap(NextIterVals); 7954 } 7955 } 7956 7957 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7958 Value *Cond, 7959 bool ExitWhen) { 7960 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7961 if (!PN) return getCouldNotCompute(); 7962 7963 // If the loop is canonicalized, the PHI will have exactly two entries. 7964 // That's the only form we support here. 7965 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7966 7967 DenseMap<Instruction *, Constant *> CurrentIterVals; 7968 BasicBlock *Header = L->getHeader(); 7969 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7970 7971 BasicBlock *Latch = L->getLoopLatch(); 7972 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7973 7974 for (PHINode &PHI : Header->phis()) { 7975 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7976 CurrentIterVals[&PHI] = StartCST; 7977 } 7978 if (!CurrentIterVals.count(PN)) 7979 return getCouldNotCompute(); 7980 7981 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7982 // the loop symbolically to determine when the condition gets a value of 7983 // "ExitWhen". 7984 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7985 const DataLayout &DL = getDataLayout(); 7986 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7987 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7988 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7989 7990 // Couldn't symbolically evaluate. 7991 if (!CondVal) return getCouldNotCompute(); 7992 7993 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7994 ++NumBruteForceTripCountsComputed; 7995 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7996 } 7997 7998 // Update all the PHI nodes for the next iteration. 7999 DenseMap<Instruction *, Constant *> NextIterVals; 8000 8001 // Create a list of which PHIs we need to compute. We want to do this before 8002 // calling EvaluateExpression on them because that may invalidate iterators 8003 // into CurrentIterVals. 8004 SmallVector<PHINode *, 8> PHIsToCompute; 8005 for (const auto &I : CurrentIterVals) { 8006 PHINode *PHI = dyn_cast<PHINode>(I.first); 8007 if (!PHI || PHI->getParent() != Header) continue; 8008 PHIsToCompute.push_back(PHI); 8009 } 8010 for (PHINode *PHI : PHIsToCompute) { 8011 Constant *&NextPHI = NextIterVals[PHI]; 8012 if (NextPHI) continue; // Already computed! 8013 8014 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8015 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8016 } 8017 CurrentIterVals.swap(NextIterVals); 8018 } 8019 8020 // Too many iterations were needed to evaluate. 8021 return getCouldNotCompute(); 8022 } 8023 8024 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8025 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8026 ValuesAtScopes[V]; 8027 // Check to see if we've folded this expression at this loop before. 8028 for (auto &LS : Values) 8029 if (LS.first == L) 8030 return LS.second ? LS.second : V; 8031 8032 Values.emplace_back(L, nullptr); 8033 8034 // Otherwise compute it. 8035 const SCEV *C = computeSCEVAtScope(V, L); 8036 for (auto &LS : reverse(ValuesAtScopes[V])) 8037 if (LS.first == L) { 8038 LS.second = C; 8039 break; 8040 } 8041 return C; 8042 } 8043 8044 /// This builds up a Constant using the ConstantExpr interface. That way, we 8045 /// will return Constants for objects which aren't represented by a 8046 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8047 /// Returns NULL if the SCEV isn't representable as a Constant. 8048 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8049 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8050 case scCouldNotCompute: 8051 case scAddRecExpr: 8052 break; 8053 case scConstant: 8054 return cast<SCEVConstant>(V)->getValue(); 8055 case scUnknown: 8056 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8057 case scSignExtend: { 8058 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8059 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8060 return ConstantExpr::getSExt(CastOp, SS->getType()); 8061 break; 8062 } 8063 case scZeroExtend: { 8064 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8065 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8066 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8067 break; 8068 } 8069 case scTruncate: { 8070 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8071 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8072 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8073 break; 8074 } 8075 case scAddExpr: { 8076 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8077 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8078 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8079 unsigned AS = PTy->getAddressSpace(); 8080 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8081 C = ConstantExpr::getBitCast(C, DestPtrTy); 8082 } 8083 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8084 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8085 if (!C2) return nullptr; 8086 8087 // First pointer! 8088 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8089 unsigned AS = C2->getType()->getPointerAddressSpace(); 8090 std::swap(C, C2); 8091 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8092 // The offsets have been converted to bytes. We can add bytes to an 8093 // i8* by GEP with the byte count in the first index. 8094 C = ConstantExpr::getBitCast(C, DestPtrTy); 8095 } 8096 8097 // Don't bother trying to sum two pointers. We probably can't 8098 // statically compute a load that results from it anyway. 8099 if (C2->getType()->isPointerTy()) 8100 return nullptr; 8101 8102 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8103 if (PTy->getElementType()->isStructTy()) 8104 C2 = ConstantExpr::getIntegerCast( 8105 C2, Type::getInt32Ty(C->getContext()), true); 8106 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8107 } else 8108 C = ConstantExpr::getAdd(C, C2); 8109 } 8110 return C; 8111 } 8112 break; 8113 } 8114 case scMulExpr: { 8115 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8116 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8117 // Don't bother with pointers at all. 8118 if (C->getType()->isPointerTy()) return nullptr; 8119 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8120 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8121 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8122 C = ConstantExpr::getMul(C, C2); 8123 } 8124 return C; 8125 } 8126 break; 8127 } 8128 case scUDivExpr: { 8129 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8130 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8131 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8132 if (LHS->getType() == RHS->getType()) 8133 return ConstantExpr::getUDiv(LHS, RHS); 8134 break; 8135 } 8136 case scSMaxExpr: 8137 case scUMaxExpr: 8138 case scSMinExpr: 8139 case scUMinExpr: 8140 break; // TODO: smax, umax, smin, umax. 8141 } 8142 return nullptr; 8143 } 8144 8145 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8146 if (isa<SCEVConstant>(V)) return V; 8147 8148 // If this instruction is evolved from a constant-evolving PHI, compute the 8149 // exit value from the loop without using SCEVs. 8150 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8151 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8152 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8153 const Loop *LI = this->LI[I->getParent()]; 8154 // Looking for loop exit value. 8155 if (LI && LI->getParentLoop() == L && 8156 PN->getParent() == LI->getHeader()) { 8157 // Okay, there is no closed form solution for the PHI node. Check 8158 // to see if the loop that contains it has a known backedge-taken 8159 // count. If so, we may be able to force computation of the exit 8160 // value. 8161 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8162 // This trivial case can show up in some degenerate cases where 8163 // the incoming IR has not yet been fully simplified. 8164 if (BackedgeTakenCount->isZero()) { 8165 Value *InitValue = nullptr; 8166 bool MultipleInitValues = false; 8167 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8168 if (!LI->contains(PN->getIncomingBlock(i))) { 8169 if (!InitValue) 8170 InitValue = PN->getIncomingValue(i); 8171 else if (InitValue != PN->getIncomingValue(i)) { 8172 MultipleInitValues = true; 8173 break; 8174 } 8175 } 8176 } 8177 if (!MultipleInitValues && InitValue) 8178 return getSCEV(InitValue); 8179 } 8180 // Do we have a loop invariant value flowing around the backedge 8181 // for a loop which must execute the backedge? 8182 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8183 isKnownPositive(BackedgeTakenCount) && 8184 PN->getNumIncomingValues() == 2) { 8185 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8186 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8187 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8188 return OnBackedge; 8189 } 8190 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8191 // Okay, we know how many times the containing loop executes. If 8192 // this is a constant evolving PHI node, get the final value at 8193 // the specified iteration number. 8194 Constant *RV = 8195 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8196 if (RV) return getSCEV(RV); 8197 } 8198 } 8199 8200 // If there is a single-input Phi, evaluate it at our scope. If we can 8201 // prove that this replacement does not break LCSSA form, use new value. 8202 if (PN->getNumOperands() == 1) { 8203 const SCEV *Input = getSCEV(PN->getOperand(0)); 8204 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8205 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8206 // for the simplest case just support constants. 8207 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8208 } 8209 } 8210 8211 // Okay, this is an expression that we cannot symbolically evaluate 8212 // into a SCEV. Check to see if it's possible to symbolically evaluate 8213 // the arguments into constants, and if so, try to constant propagate the 8214 // result. This is particularly useful for computing loop exit values. 8215 if (CanConstantFold(I)) { 8216 SmallVector<Constant *, 4> Operands; 8217 bool MadeImprovement = false; 8218 for (Value *Op : I->operands()) { 8219 if (Constant *C = dyn_cast<Constant>(Op)) { 8220 Operands.push_back(C); 8221 continue; 8222 } 8223 8224 // If any of the operands is non-constant and if they are 8225 // non-integer and non-pointer, don't even try to analyze them 8226 // with scev techniques. 8227 if (!isSCEVable(Op->getType())) 8228 return V; 8229 8230 const SCEV *OrigV = getSCEV(Op); 8231 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8232 MadeImprovement |= OrigV != OpV; 8233 8234 Constant *C = BuildConstantFromSCEV(OpV); 8235 if (!C) return V; 8236 if (C->getType() != Op->getType()) 8237 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8238 Op->getType(), 8239 false), 8240 C, Op->getType()); 8241 Operands.push_back(C); 8242 } 8243 8244 // Check to see if getSCEVAtScope actually made an improvement. 8245 if (MadeImprovement) { 8246 Constant *C = nullptr; 8247 const DataLayout &DL = getDataLayout(); 8248 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8249 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8250 Operands[1], DL, &TLI); 8251 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8252 if (!LI->isVolatile()) 8253 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8254 } else 8255 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8256 if (!C) return V; 8257 return getSCEV(C); 8258 } 8259 } 8260 } 8261 8262 // This is some other type of SCEVUnknown, just return it. 8263 return V; 8264 } 8265 8266 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8267 // Avoid performing the look-up in the common case where the specified 8268 // expression has no loop-variant portions. 8269 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8270 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8271 if (OpAtScope != Comm->getOperand(i)) { 8272 // Okay, at least one of these operands is loop variant but might be 8273 // foldable. Build a new instance of the folded commutative expression. 8274 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8275 Comm->op_begin()+i); 8276 NewOps.push_back(OpAtScope); 8277 8278 for (++i; i != e; ++i) { 8279 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8280 NewOps.push_back(OpAtScope); 8281 } 8282 if (isa<SCEVAddExpr>(Comm)) 8283 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8284 if (isa<SCEVMulExpr>(Comm)) 8285 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8286 if (isa<SCEVMinMaxExpr>(Comm)) 8287 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8288 llvm_unreachable("Unknown commutative SCEV type!"); 8289 } 8290 } 8291 // If we got here, all operands are loop invariant. 8292 return Comm; 8293 } 8294 8295 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8296 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8297 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8298 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8299 return Div; // must be loop invariant 8300 return getUDivExpr(LHS, RHS); 8301 } 8302 8303 // If this is a loop recurrence for a loop that does not contain L, then we 8304 // are dealing with the final value computed by the loop. 8305 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8306 // First, attempt to evaluate each operand. 8307 // Avoid performing the look-up in the common case where the specified 8308 // expression has no loop-variant portions. 8309 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8310 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8311 if (OpAtScope == AddRec->getOperand(i)) 8312 continue; 8313 8314 // Okay, at least one of these operands is loop variant but might be 8315 // foldable. Build a new instance of the folded commutative expression. 8316 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8317 AddRec->op_begin()+i); 8318 NewOps.push_back(OpAtScope); 8319 for (++i; i != e; ++i) 8320 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8321 8322 const SCEV *FoldedRec = 8323 getAddRecExpr(NewOps, AddRec->getLoop(), 8324 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8325 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8326 // The addrec may be folded to a nonrecurrence, for example, if the 8327 // induction variable is multiplied by zero after constant folding. Go 8328 // ahead and return the folded value. 8329 if (!AddRec) 8330 return FoldedRec; 8331 break; 8332 } 8333 8334 // If the scope is outside the addrec's loop, evaluate it by using the 8335 // loop exit value of the addrec. 8336 if (!AddRec->getLoop()->contains(L)) { 8337 // To evaluate this recurrence, we need to know how many times the AddRec 8338 // loop iterates. Compute this now. 8339 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8340 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8341 8342 // Then, evaluate the AddRec. 8343 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8344 } 8345 8346 return AddRec; 8347 } 8348 8349 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8350 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8351 if (Op == Cast->getOperand()) 8352 return Cast; // must be loop invariant 8353 return getZeroExtendExpr(Op, Cast->getType()); 8354 } 8355 8356 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8357 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8358 if (Op == Cast->getOperand()) 8359 return Cast; // must be loop invariant 8360 return getSignExtendExpr(Op, Cast->getType()); 8361 } 8362 8363 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8364 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8365 if (Op == Cast->getOperand()) 8366 return Cast; // must be loop invariant 8367 return getTruncateExpr(Op, Cast->getType()); 8368 } 8369 8370 llvm_unreachable("Unknown SCEV type!"); 8371 } 8372 8373 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8374 return getSCEVAtScope(getSCEV(V), L); 8375 } 8376 8377 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8378 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8379 return stripInjectiveFunctions(ZExt->getOperand()); 8380 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8381 return stripInjectiveFunctions(SExt->getOperand()); 8382 return S; 8383 } 8384 8385 /// Finds the minimum unsigned root of the following equation: 8386 /// 8387 /// A * X = B (mod N) 8388 /// 8389 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8390 /// A and B isn't important. 8391 /// 8392 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8393 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8394 ScalarEvolution &SE) { 8395 uint32_t BW = A.getBitWidth(); 8396 assert(BW == SE.getTypeSizeInBits(B->getType())); 8397 assert(A != 0 && "A must be non-zero."); 8398 8399 // 1. D = gcd(A, N) 8400 // 8401 // The gcd of A and N may have only one prime factor: 2. The number of 8402 // trailing zeros in A is its multiplicity 8403 uint32_t Mult2 = A.countTrailingZeros(); 8404 // D = 2^Mult2 8405 8406 // 2. Check if B is divisible by D. 8407 // 8408 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8409 // is not less than multiplicity of this prime factor for D. 8410 if (SE.GetMinTrailingZeros(B) < Mult2) 8411 return SE.getCouldNotCompute(); 8412 8413 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8414 // modulo (N / D). 8415 // 8416 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8417 // (N / D) in general. The inverse itself always fits into BW bits, though, 8418 // so we immediately truncate it. 8419 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8420 APInt Mod(BW + 1, 0); 8421 Mod.setBit(BW - Mult2); // Mod = N / D 8422 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8423 8424 // 4. Compute the minimum unsigned root of the equation: 8425 // I * (B / D) mod (N / D) 8426 // To simplify the computation, we factor out the divide by D: 8427 // (I * B mod N) / D 8428 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8429 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8430 } 8431 8432 /// For a given quadratic addrec, generate coefficients of the corresponding 8433 /// quadratic equation, multiplied by a common value to ensure that they are 8434 /// integers. 8435 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8436 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8437 /// were multiplied by, and BitWidth is the bit width of the original addrec 8438 /// coefficients. 8439 /// This function returns None if the addrec coefficients are not compile- 8440 /// time constants. 8441 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8442 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8443 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8444 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8445 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8446 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8447 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8448 << *AddRec << '\n'); 8449 8450 // We currently can only solve this if the coefficients are constants. 8451 if (!LC || !MC || !NC) { 8452 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8453 return None; 8454 } 8455 8456 APInt L = LC->getAPInt(); 8457 APInt M = MC->getAPInt(); 8458 APInt N = NC->getAPInt(); 8459 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8460 8461 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8462 unsigned NewWidth = BitWidth + 1; 8463 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8464 << BitWidth << '\n'); 8465 // The sign-extension (as opposed to a zero-extension) here matches the 8466 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8467 N = N.sext(NewWidth); 8468 M = M.sext(NewWidth); 8469 L = L.sext(NewWidth); 8470 8471 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8472 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8473 // L+M, L+2M+N, L+3M+3N, ... 8474 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8475 // 8476 // The equation Acc = 0 is then 8477 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8478 // In a quadratic form it becomes: 8479 // N n^2 + (2M-N) n + 2L = 0. 8480 8481 APInt A = N; 8482 APInt B = 2 * M - A; 8483 APInt C = 2 * L; 8484 APInt T = APInt(NewWidth, 2); 8485 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8486 << "x + " << C << ", coeff bw: " << NewWidth 8487 << ", multiplied by " << T << '\n'); 8488 return std::make_tuple(A, B, C, T, BitWidth); 8489 } 8490 8491 /// Helper function to compare optional APInts: 8492 /// (a) if X and Y both exist, return min(X, Y), 8493 /// (b) if neither X nor Y exist, return None, 8494 /// (c) if exactly one of X and Y exists, return that value. 8495 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8496 if (X.hasValue() && Y.hasValue()) { 8497 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8498 APInt XW = X->sextOrSelf(W); 8499 APInt YW = Y->sextOrSelf(W); 8500 return XW.slt(YW) ? *X : *Y; 8501 } 8502 if (!X.hasValue() && !Y.hasValue()) 8503 return None; 8504 return X.hasValue() ? *X : *Y; 8505 } 8506 8507 /// Helper function to truncate an optional APInt to a given BitWidth. 8508 /// When solving addrec-related equations, it is preferable to return a value 8509 /// that has the same bit width as the original addrec's coefficients. If the 8510 /// solution fits in the original bit width, truncate it (except for i1). 8511 /// Returning a value of a different bit width may inhibit some optimizations. 8512 /// 8513 /// In general, a solution to a quadratic equation generated from an addrec 8514 /// may require BW+1 bits, where BW is the bit width of the addrec's 8515 /// coefficients. The reason is that the coefficients of the quadratic 8516 /// equation are BW+1 bits wide (to avoid truncation when converting from 8517 /// the addrec to the equation). 8518 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8519 if (!X.hasValue()) 8520 return None; 8521 unsigned W = X->getBitWidth(); 8522 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8523 return X->trunc(BitWidth); 8524 return X; 8525 } 8526 8527 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8528 /// iterations. The values L, M, N are assumed to be signed, and they 8529 /// should all have the same bit widths. 8530 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8531 /// where BW is the bit width of the addrec's coefficients. 8532 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8533 /// returned as such, otherwise the bit width of the returned value may 8534 /// be greater than BW. 8535 /// 8536 /// This function returns None if 8537 /// (a) the addrec coefficients are not constant, or 8538 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8539 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8540 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8541 static Optional<APInt> 8542 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8543 APInt A, B, C, M; 8544 unsigned BitWidth; 8545 auto T = GetQuadraticEquation(AddRec); 8546 if (!T.hasValue()) 8547 return None; 8548 8549 std::tie(A, B, C, M, BitWidth) = *T; 8550 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8551 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8552 if (!X.hasValue()) 8553 return None; 8554 8555 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8556 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8557 if (!V->isZero()) 8558 return None; 8559 8560 return TruncIfPossible(X, BitWidth); 8561 } 8562 8563 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8564 /// iterations. The values M, N are assumed to be signed, and they 8565 /// should all have the same bit widths. 8566 /// Find the least n such that c(n) does not belong to the given range, 8567 /// while c(n-1) does. 8568 /// 8569 /// This function returns None if 8570 /// (a) the addrec coefficients are not constant, or 8571 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8572 /// bounds of the range. 8573 static Optional<APInt> 8574 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8575 const ConstantRange &Range, ScalarEvolution &SE) { 8576 assert(AddRec->getOperand(0)->isZero() && 8577 "Starting value of addrec should be 0"); 8578 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8579 << Range << ", addrec " << *AddRec << '\n'); 8580 // This case is handled in getNumIterationsInRange. Here we can assume that 8581 // we start in the range. 8582 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8583 "Addrec's initial value should be in range"); 8584 8585 APInt A, B, C, M; 8586 unsigned BitWidth; 8587 auto T = GetQuadraticEquation(AddRec); 8588 if (!T.hasValue()) 8589 return None; 8590 8591 // Be careful about the return value: there can be two reasons for not 8592 // returning an actual number. First, if no solutions to the equations 8593 // were found, and second, if the solutions don't leave the given range. 8594 // The first case means that the actual solution is "unknown", the second 8595 // means that it's known, but not valid. If the solution is unknown, we 8596 // cannot make any conclusions. 8597 // Return a pair: the optional solution and a flag indicating if the 8598 // solution was found. 8599 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8600 // Solve for signed overflow and unsigned overflow, pick the lower 8601 // solution. 8602 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8603 << Bound << " (before multiplying by " << M << ")\n"); 8604 Bound *= M; // The quadratic equation multiplier. 8605 8606 Optional<APInt> SO = None; 8607 if (BitWidth > 1) { 8608 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8609 "signed overflow\n"); 8610 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8611 } 8612 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8613 "unsigned overflow\n"); 8614 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8615 BitWidth+1); 8616 8617 auto LeavesRange = [&] (const APInt &X) { 8618 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8619 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8620 if (Range.contains(V0->getValue())) 8621 return false; 8622 // X should be at least 1, so X-1 is non-negative. 8623 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8624 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8625 if (Range.contains(V1->getValue())) 8626 return true; 8627 return false; 8628 }; 8629 8630 // If SolveQuadraticEquationWrap returns None, it means that there can 8631 // be a solution, but the function failed to find it. We cannot treat it 8632 // as "no solution". 8633 if (!SO.hasValue() || !UO.hasValue()) 8634 return { None, false }; 8635 8636 // Check the smaller value first to see if it leaves the range. 8637 // At this point, both SO and UO must have values. 8638 Optional<APInt> Min = MinOptional(SO, UO); 8639 if (LeavesRange(*Min)) 8640 return { Min, true }; 8641 Optional<APInt> Max = Min == SO ? UO : SO; 8642 if (LeavesRange(*Max)) 8643 return { Max, true }; 8644 8645 // Solutions were found, but were eliminated, hence the "true". 8646 return { None, true }; 8647 }; 8648 8649 std::tie(A, B, C, M, BitWidth) = *T; 8650 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8651 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8652 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8653 auto SL = SolveForBoundary(Lower); 8654 auto SU = SolveForBoundary(Upper); 8655 // If any of the solutions was unknown, no meaninigful conclusions can 8656 // be made. 8657 if (!SL.second || !SU.second) 8658 return None; 8659 8660 // Claim: The correct solution is not some value between Min and Max. 8661 // 8662 // Justification: Assuming that Min and Max are different values, one of 8663 // them is when the first signed overflow happens, the other is when the 8664 // first unsigned overflow happens. Crossing the range boundary is only 8665 // possible via an overflow (treating 0 as a special case of it, modeling 8666 // an overflow as crossing k*2^W for some k). 8667 // 8668 // The interesting case here is when Min was eliminated as an invalid 8669 // solution, but Max was not. The argument is that if there was another 8670 // overflow between Min and Max, it would also have been eliminated if 8671 // it was considered. 8672 // 8673 // For a given boundary, it is possible to have two overflows of the same 8674 // type (signed/unsigned) without having the other type in between: this 8675 // can happen when the vertex of the parabola is between the iterations 8676 // corresponding to the overflows. This is only possible when the two 8677 // overflows cross k*2^W for the same k. In such case, if the second one 8678 // left the range (and was the first one to do so), the first overflow 8679 // would have to enter the range, which would mean that either we had left 8680 // the range before or that we started outside of it. Both of these cases 8681 // are contradictions. 8682 // 8683 // Claim: In the case where SolveForBoundary returns None, the correct 8684 // solution is not some value between the Max for this boundary and the 8685 // Min of the other boundary. 8686 // 8687 // Justification: Assume that we had such Max_A and Min_B corresponding 8688 // to range boundaries A and B and such that Max_A < Min_B. If there was 8689 // a solution between Max_A and Min_B, it would have to be caused by an 8690 // overflow corresponding to either A or B. It cannot correspond to B, 8691 // since Min_B is the first occurrence of such an overflow. If it 8692 // corresponded to A, it would have to be either a signed or an unsigned 8693 // overflow that is larger than both eliminated overflows for A. But 8694 // between the eliminated overflows and this overflow, the values would 8695 // cover the entire value space, thus crossing the other boundary, which 8696 // is a contradiction. 8697 8698 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8699 } 8700 8701 ScalarEvolution::ExitLimit 8702 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8703 bool AllowPredicates) { 8704 8705 // This is only used for loops with a "x != y" exit test. The exit condition 8706 // is now expressed as a single expression, V = x-y. So the exit test is 8707 // effectively V != 0. We know and take advantage of the fact that this 8708 // expression only being used in a comparison by zero context. 8709 8710 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8711 // If the value is a constant 8712 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8713 // If the value is already zero, the branch will execute zero times. 8714 if (C->getValue()->isZero()) return C; 8715 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8716 } 8717 8718 const SCEVAddRecExpr *AddRec = 8719 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8720 8721 if (!AddRec && AllowPredicates) 8722 // Try to make this an AddRec using runtime tests, in the first X 8723 // iterations of this loop, where X is the SCEV expression found by the 8724 // algorithm below. 8725 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8726 8727 if (!AddRec || AddRec->getLoop() != L) 8728 return getCouldNotCompute(); 8729 8730 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8731 // the quadratic equation to solve it. 8732 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8733 // We can only use this value if the chrec ends up with an exact zero 8734 // value at this index. When solving for "X*X != 5", for example, we 8735 // should not accept a root of 2. 8736 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8737 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8738 return ExitLimit(R, R, false, Predicates); 8739 } 8740 return getCouldNotCompute(); 8741 } 8742 8743 // Otherwise we can only handle this if it is affine. 8744 if (!AddRec->isAffine()) 8745 return getCouldNotCompute(); 8746 8747 // If this is an affine expression, the execution count of this branch is 8748 // the minimum unsigned root of the following equation: 8749 // 8750 // Start + Step*N = 0 (mod 2^BW) 8751 // 8752 // equivalent to: 8753 // 8754 // Step*N = -Start (mod 2^BW) 8755 // 8756 // where BW is the common bit width of Start and Step. 8757 8758 // Get the initial value for the loop. 8759 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8760 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8761 8762 // For now we handle only constant steps. 8763 // 8764 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8765 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8766 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8767 // We have not yet seen any such cases. 8768 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8769 if (!StepC || StepC->getValue()->isZero()) 8770 return getCouldNotCompute(); 8771 8772 // For positive steps (counting up until unsigned overflow): 8773 // N = -Start/Step (as unsigned) 8774 // For negative steps (counting down to zero): 8775 // N = Start/-Step 8776 // First compute the unsigned distance from zero in the direction of Step. 8777 bool CountDown = StepC->getAPInt().isNegative(); 8778 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8779 8780 // Handle unitary steps, which cannot wraparound. 8781 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8782 // N = Distance (as unsigned) 8783 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8784 APInt MaxBECount = getUnsignedRangeMax(Distance); 8785 8786 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8787 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8788 // case, and see if we can improve the bound. 8789 // 8790 // Explicitly handling this here is necessary because getUnsignedRange 8791 // isn't context-sensitive; it doesn't know that we only care about the 8792 // range inside the loop. 8793 const SCEV *Zero = getZero(Distance->getType()); 8794 const SCEV *One = getOne(Distance->getType()); 8795 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8796 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8797 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8798 // as "unsigned_max(Distance + 1) - 1". 8799 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8800 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8801 } 8802 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8803 } 8804 8805 // If the condition controls loop exit (the loop exits only if the expression 8806 // is true) and the addition is no-wrap we can use unsigned divide to 8807 // compute the backedge count. In this case, the step may not divide the 8808 // distance, but we don't care because if the condition is "missed" the loop 8809 // will have undefined behavior due to wrapping. 8810 if (ControlsExit && AddRec->hasNoSelfWrap() && 8811 loopHasNoAbnormalExits(AddRec->getLoop())) { 8812 const SCEV *Exact = 8813 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8814 const SCEV *Max = 8815 Exact == getCouldNotCompute() 8816 ? Exact 8817 : getConstant(getUnsignedRangeMax(Exact)); 8818 return ExitLimit(Exact, Max, false, Predicates); 8819 } 8820 8821 // Solve the general equation. 8822 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8823 getNegativeSCEV(Start), *this); 8824 const SCEV *M = E == getCouldNotCompute() 8825 ? E 8826 : getConstant(getUnsignedRangeMax(E)); 8827 return ExitLimit(E, M, false, Predicates); 8828 } 8829 8830 ScalarEvolution::ExitLimit 8831 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8832 // Loops that look like: while (X == 0) are very strange indeed. We don't 8833 // handle them yet except for the trivial case. This could be expanded in the 8834 // future as needed. 8835 8836 // If the value is a constant, check to see if it is known to be non-zero 8837 // already. If so, the backedge will execute zero times. 8838 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8839 if (!C->getValue()->isZero()) 8840 return getZero(C->getType()); 8841 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8842 } 8843 8844 // We could implement others, but I really doubt anyone writes loops like 8845 // this, and if they did, they would already be constant folded. 8846 return getCouldNotCompute(); 8847 } 8848 8849 std::pair<BasicBlock *, BasicBlock *> 8850 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8851 // If the block has a unique predecessor, then there is no path from the 8852 // predecessor to the block that does not go through the direct edge 8853 // from the predecessor to the block. 8854 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8855 return {Pred, BB}; 8856 8857 // A loop's header is defined to be a block that dominates the loop. 8858 // If the header has a unique predecessor outside the loop, it must be 8859 // a block that has exactly one successor that can reach the loop. 8860 if (Loop *L = LI.getLoopFor(BB)) 8861 return {L->getLoopPredecessor(), L->getHeader()}; 8862 8863 return {nullptr, nullptr}; 8864 } 8865 8866 /// SCEV structural equivalence is usually sufficient for testing whether two 8867 /// expressions are equal, however for the purposes of looking for a condition 8868 /// guarding a loop, it can be useful to be a little more general, since a 8869 /// front-end may have replicated the controlling expression. 8870 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8871 // Quick check to see if they are the same SCEV. 8872 if (A == B) return true; 8873 8874 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8875 // Not all instructions that are "identical" compute the same value. For 8876 // instance, two distinct alloca instructions allocating the same type are 8877 // identical and do not read memory; but compute distinct values. 8878 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8879 }; 8880 8881 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8882 // two different instructions with the same value. Check for this case. 8883 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8884 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8885 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8886 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8887 if (ComputesEqualValues(AI, BI)) 8888 return true; 8889 8890 // Otherwise assume they may have a different value. 8891 return false; 8892 } 8893 8894 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8895 const SCEV *&LHS, const SCEV *&RHS, 8896 unsigned Depth) { 8897 bool Changed = false; 8898 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8899 // '0 != 0'. 8900 auto TrivialCase = [&](bool TriviallyTrue) { 8901 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8902 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8903 return true; 8904 }; 8905 // If we hit the max recursion limit bail out. 8906 if (Depth >= 3) 8907 return false; 8908 8909 // Canonicalize a constant to the right side. 8910 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8911 // Check for both operands constant. 8912 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8913 if (ConstantExpr::getICmp(Pred, 8914 LHSC->getValue(), 8915 RHSC->getValue())->isNullValue()) 8916 return TrivialCase(false); 8917 else 8918 return TrivialCase(true); 8919 } 8920 // Otherwise swap the operands to put the constant on the right. 8921 std::swap(LHS, RHS); 8922 Pred = ICmpInst::getSwappedPredicate(Pred); 8923 Changed = true; 8924 } 8925 8926 // If we're comparing an addrec with a value which is loop-invariant in the 8927 // addrec's loop, put the addrec on the left. Also make a dominance check, 8928 // as both operands could be addrecs loop-invariant in each other's loop. 8929 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8930 const Loop *L = AR->getLoop(); 8931 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8932 std::swap(LHS, RHS); 8933 Pred = ICmpInst::getSwappedPredicate(Pred); 8934 Changed = true; 8935 } 8936 } 8937 8938 // If there's a constant operand, canonicalize comparisons with boundary 8939 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8940 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8941 const APInt &RA = RC->getAPInt(); 8942 8943 bool SimplifiedByConstantRange = false; 8944 8945 if (!ICmpInst::isEquality(Pred)) { 8946 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8947 if (ExactCR.isFullSet()) 8948 return TrivialCase(true); 8949 else if (ExactCR.isEmptySet()) 8950 return TrivialCase(false); 8951 8952 APInt NewRHS; 8953 CmpInst::Predicate NewPred; 8954 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8955 ICmpInst::isEquality(NewPred)) { 8956 // We were able to convert an inequality to an equality. 8957 Pred = NewPred; 8958 RHS = getConstant(NewRHS); 8959 Changed = SimplifiedByConstantRange = true; 8960 } 8961 } 8962 8963 if (!SimplifiedByConstantRange) { 8964 switch (Pred) { 8965 default: 8966 break; 8967 case ICmpInst::ICMP_EQ: 8968 case ICmpInst::ICMP_NE: 8969 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8970 if (!RA) 8971 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8972 if (const SCEVMulExpr *ME = 8973 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8974 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8975 ME->getOperand(0)->isAllOnesValue()) { 8976 RHS = AE->getOperand(1); 8977 LHS = ME->getOperand(1); 8978 Changed = true; 8979 } 8980 break; 8981 8982 8983 // The "Should have been caught earlier!" messages refer to the fact 8984 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8985 // should have fired on the corresponding cases, and canonicalized the 8986 // check to trivial case. 8987 8988 case ICmpInst::ICMP_UGE: 8989 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8990 Pred = ICmpInst::ICMP_UGT; 8991 RHS = getConstant(RA - 1); 8992 Changed = true; 8993 break; 8994 case ICmpInst::ICMP_ULE: 8995 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8996 Pred = ICmpInst::ICMP_ULT; 8997 RHS = getConstant(RA + 1); 8998 Changed = true; 8999 break; 9000 case ICmpInst::ICMP_SGE: 9001 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9002 Pred = ICmpInst::ICMP_SGT; 9003 RHS = getConstant(RA - 1); 9004 Changed = true; 9005 break; 9006 case ICmpInst::ICMP_SLE: 9007 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9008 Pred = ICmpInst::ICMP_SLT; 9009 RHS = getConstant(RA + 1); 9010 Changed = true; 9011 break; 9012 } 9013 } 9014 } 9015 9016 // Check for obvious equality. 9017 if (HasSameValue(LHS, RHS)) { 9018 if (ICmpInst::isTrueWhenEqual(Pred)) 9019 return TrivialCase(true); 9020 if (ICmpInst::isFalseWhenEqual(Pred)) 9021 return TrivialCase(false); 9022 } 9023 9024 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9025 // adding or subtracting 1 from one of the operands. 9026 switch (Pred) { 9027 case ICmpInst::ICMP_SLE: 9028 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9029 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9030 SCEV::FlagNSW); 9031 Pred = ICmpInst::ICMP_SLT; 9032 Changed = true; 9033 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9034 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9035 SCEV::FlagNSW); 9036 Pred = ICmpInst::ICMP_SLT; 9037 Changed = true; 9038 } 9039 break; 9040 case ICmpInst::ICMP_SGE: 9041 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9042 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9043 SCEV::FlagNSW); 9044 Pred = ICmpInst::ICMP_SGT; 9045 Changed = true; 9046 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9047 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9048 SCEV::FlagNSW); 9049 Pred = ICmpInst::ICMP_SGT; 9050 Changed = true; 9051 } 9052 break; 9053 case ICmpInst::ICMP_ULE: 9054 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9055 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9056 SCEV::FlagNUW); 9057 Pred = ICmpInst::ICMP_ULT; 9058 Changed = true; 9059 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9060 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9061 Pred = ICmpInst::ICMP_ULT; 9062 Changed = true; 9063 } 9064 break; 9065 case ICmpInst::ICMP_UGE: 9066 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9067 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9068 Pred = ICmpInst::ICMP_UGT; 9069 Changed = true; 9070 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9071 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9072 SCEV::FlagNUW); 9073 Pred = ICmpInst::ICMP_UGT; 9074 Changed = true; 9075 } 9076 break; 9077 default: 9078 break; 9079 } 9080 9081 // TODO: More simplifications are possible here. 9082 9083 // Recursively simplify until we either hit a recursion limit or nothing 9084 // changes. 9085 if (Changed) 9086 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9087 9088 return Changed; 9089 } 9090 9091 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9092 return getSignedRangeMax(S).isNegative(); 9093 } 9094 9095 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9096 return getSignedRangeMin(S).isStrictlyPositive(); 9097 } 9098 9099 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9100 return !getSignedRangeMin(S).isNegative(); 9101 } 9102 9103 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9104 return !getSignedRangeMax(S).isStrictlyPositive(); 9105 } 9106 9107 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9108 return isKnownNegative(S) || isKnownPositive(S); 9109 } 9110 9111 std::pair<const SCEV *, const SCEV *> 9112 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9113 // Compute SCEV on entry of loop L. 9114 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9115 if (Start == getCouldNotCompute()) 9116 return { Start, Start }; 9117 // Compute post increment SCEV for loop L. 9118 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9119 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9120 return { Start, PostInc }; 9121 } 9122 9123 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9124 const SCEV *LHS, const SCEV *RHS) { 9125 // First collect all loops. 9126 SmallPtrSet<const Loop *, 8> LoopsUsed; 9127 getUsedLoops(LHS, LoopsUsed); 9128 getUsedLoops(RHS, LoopsUsed); 9129 9130 if (LoopsUsed.empty()) 9131 return false; 9132 9133 // Domination relationship must be a linear order on collected loops. 9134 #ifndef NDEBUG 9135 for (auto *L1 : LoopsUsed) 9136 for (auto *L2 : LoopsUsed) 9137 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9138 DT.dominates(L2->getHeader(), L1->getHeader())) && 9139 "Domination relationship is not a linear order"); 9140 #endif 9141 9142 const Loop *MDL = 9143 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9144 [&](const Loop *L1, const Loop *L2) { 9145 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9146 }); 9147 9148 // Get init and post increment value for LHS. 9149 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9150 // if LHS contains unknown non-invariant SCEV then bail out. 9151 if (SplitLHS.first == getCouldNotCompute()) 9152 return false; 9153 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9154 // Get init and post increment value for RHS. 9155 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9156 // if RHS contains unknown non-invariant SCEV then bail out. 9157 if (SplitRHS.first == getCouldNotCompute()) 9158 return false; 9159 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9160 // It is possible that init SCEV contains an invariant load but it does 9161 // not dominate MDL and is not available at MDL loop entry, so we should 9162 // check it here. 9163 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9164 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9165 return false; 9166 9167 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9168 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9169 SplitRHS.second); 9170 } 9171 9172 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9173 const SCEV *LHS, const SCEV *RHS) { 9174 // Canonicalize the inputs first. 9175 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9176 9177 if (isKnownViaInduction(Pred, LHS, RHS)) 9178 return true; 9179 9180 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9181 return true; 9182 9183 // Otherwise see what can be done with some simple reasoning. 9184 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9185 } 9186 9187 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9188 const SCEVAddRecExpr *LHS, 9189 const SCEV *RHS) { 9190 const Loop *L = LHS->getLoop(); 9191 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9192 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9193 } 9194 9195 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9196 ICmpInst::Predicate Pred, 9197 bool &Increasing) { 9198 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9199 9200 #ifndef NDEBUG 9201 // Verify an invariant: inverting the predicate should turn a monotonically 9202 // increasing change to a monotonically decreasing one, and vice versa. 9203 bool IncreasingSwapped; 9204 bool ResultSwapped = isMonotonicPredicateImpl( 9205 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9206 9207 assert(Result == ResultSwapped && "should be able to analyze both!"); 9208 if (ResultSwapped) 9209 assert(Increasing == !IncreasingSwapped && 9210 "monotonicity should flip as we flip the predicate"); 9211 #endif 9212 9213 return Result; 9214 } 9215 9216 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9217 ICmpInst::Predicate Pred, 9218 bool &Increasing) { 9219 9220 // A zero step value for LHS means the induction variable is essentially a 9221 // loop invariant value. We don't really depend on the predicate actually 9222 // flipping from false to true (for increasing predicates, and the other way 9223 // around for decreasing predicates), all we care about is that *if* the 9224 // predicate changes then it only changes from false to true. 9225 // 9226 // A zero step value in itself is not very useful, but there may be places 9227 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9228 // as general as possible. 9229 9230 switch (Pred) { 9231 default: 9232 return false; // Conservative answer 9233 9234 case ICmpInst::ICMP_UGT: 9235 case ICmpInst::ICMP_UGE: 9236 case ICmpInst::ICMP_ULT: 9237 case ICmpInst::ICMP_ULE: 9238 if (!LHS->hasNoUnsignedWrap()) 9239 return false; 9240 9241 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9242 return true; 9243 9244 case ICmpInst::ICMP_SGT: 9245 case ICmpInst::ICMP_SGE: 9246 case ICmpInst::ICMP_SLT: 9247 case ICmpInst::ICMP_SLE: { 9248 if (!LHS->hasNoSignedWrap()) 9249 return false; 9250 9251 const SCEV *Step = LHS->getStepRecurrence(*this); 9252 9253 if (isKnownNonNegative(Step)) { 9254 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9255 return true; 9256 } 9257 9258 if (isKnownNonPositive(Step)) { 9259 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9260 return true; 9261 } 9262 9263 return false; 9264 } 9265 9266 } 9267 9268 llvm_unreachable("switch has default clause!"); 9269 } 9270 9271 bool ScalarEvolution::isLoopInvariantPredicate( 9272 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9273 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9274 const SCEV *&InvariantRHS) { 9275 9276 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9277 if (!isLoopInvariant(RHS, L)) { 9278 if (!isLoopInvariant(LHS, L)) 9279 return false; 9280 9281 std::swap(LHS, RHS); 9282 Pred = ICmpInst::getSwappedPredicate(Pred); 9283 } 9284 9285 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9286 if (!ArLHS || ArLHS->getLoop() != L) 9287 return false; 9288 9289 bool Increasing; 9290 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9291 return false; 9292 9293 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9294 // true as the loop iterates, and the backedge is control dependent on 9295 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9296 // 9297 // * if the predicate was false in the first iteration then the predicate 9298 // is never evaluated again, since the loop exits without taking the 9299 // backedge. 9300 // * if the predicate was true in the first iteration then it will 9301 // continue to be true for all future iterations since it is 9302 // monotonically increasing. 9303 // 9304 // For both the above possibilities, we can replace the loop varying 9305 // predicate with its value on the first iteration of the loop (which is 9306 // loop invariant). 9307 // 9308 // A similar reasoning applies for a monotonically decreasing predicate, by 9309 // replacing true with false and false with true in the above two bullets. 9310 9311 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9312 9313 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9314 return false; 9315 9316 InvariantPred = Pred; 9317 InvariantLHS = ArLHS->getStart(); 9318 InvariantRHS = RHS; 9319 return true; 9320 } 9321 9322 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9323 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9324 if (HasSameValue(LHS, RHS)) 9325 return ICmpInst::isTrueWhenEqual(Pred); 9326 9327 // This code is split out from isKnownPredicate because it is called from 9328 // within isLoopEntryGuardedByCond. 9329 9330 auto CheckRanges = 9331 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9332 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9333 .contains(RangeLHS); 9334 }; 9335 9336 // The check at the top of the function catches the case where the values are 9337 // known to be equal. 9338 if (Pred == CmpInst::ICMP_EQ) 9339 return false; 9340 9341 if (Pred == CmpInst::ICMP_NE) 9342 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9343 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9344 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9345 9346 if (CmpInst::isSigned(Pred)) 9347 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9348 9349 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9350 } 9351 9352 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9353 const SCEV *LHS, 9354 const SCEV *RHS) { 9355 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9356 // Return Y via OutY. 9357 auto MatchBinaryAddToConst = 9358 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9359 SCEV::NoWrapFlags ExpectedFlags) { 9360 const SCEV *NonConstOp, *ConstOp; 9361 SCEV::NoWrapFlags FlagsPresent; 9362 9363 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9364 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9365 return false; 9366 9367 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9368 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9369 }; 9370 9371 APInt C; 9372 9373 switch (Pred) { 9374 default: 9375 break; 9376 9377 case ICmpInst::ICMP_SGE: 9378 std::swap(LHS, RHS); 9379 LLVM_FALLTHROUGH; 9380 case ICmpInst::ICMP_SLE: 9381 // X s<= (X + C)<nsw> if C >= 0 9382 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9383 return true; 9384 9385 // (X + C)<nsw> s<= X if C <= 0 9386 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9387 !C.isStrictlyPositive()) 9388 return true; 9389 break; 9390 9391 case ICmpInst::ICMP_SGT: 9392 std::swap(LHS, RHS); 9393 LLVM_FALLTHROUGH; 9394 case ICmpInst::ICMP_SLT: 9395 // X s< (X + C)<nsw> if C > 0 9396 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9397 C.isStrictlyPositive()) 9398 return true; 9399 9400 // (X + C)<nsw> s< X if C < 0 9401 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9402 return true; 9403 break; 9404 } 9405 9406 return false; 9407 } 9408 9409 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9410 const SCEV *LHS, 9411 const SCEV *RHS) { 9412 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9413 return false; 9414 9415 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9416 // the stack can result in exponential time complexity. 9417 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9418 9419 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9420 // 9421 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9422 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9423 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9424 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9425 // use isKnownPredicate later if needed. 9426 return isKnownNonNegative(RHS) && 9427 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9428 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9429 } 9430 9431 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9432 ICmpInst::Predicate Pred, 9433 const SCEV *LHS, const SCEV *RHS) { 9434 // No need to even try if we know the module has no guards. 9435 if (!HasGuards) 9436 return false; 9437 9438 return any_of(*BB, [&](Instruction &I) { 9439 using namespace llvm::PatternMatch; 9440 9441 Value *Condition; 9442 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9443 m_Value(Condition))) && 9444 isImpliedCond(Pred, LHS, RHS, Condition, false); 9445 }); 9446 } 9447 9448 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9449 /// protected by a conditional between LHS and RHS. This is used to 9450 /// to eliminate casts. 9451 bool 9452 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9453 ICmpInst::Predicate Pred, 9454 const SCEV *LHS, const SCEV *RHS) { 9455 // Interpret a null as meaning no loop, where there is obviously no guard 9456 // (interprocedural conditions notwithstanding). 9457 if (!L) return true; 9458 9459 if (VerifyIR) 9460 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9461 "This cannot be done on broken IR!"); 9462 9463 9464 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9465 return true; 9466 9467 BasicBlock *Latch = L->getLoopLatch(); 9468 if (!Latch) 9469 return false; 9470 9471 BranchInst *LoopContinuePredicate = 9472 dyn_cast<BranchInst>(Latch->getTerminator()); 9473 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9474 isImpliedCond(Pred, LHS, RHS, 9475 LoopContinuePredicate->getCondition(), 9476 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9477 return true; 9478 9479 // We don't want more than one activation of the following loops on the stack 9480 // -- that can lead to O(n!) time complexity. 9481 if (WalkingBEDominatingConds) 9482 return false; 9483 9484 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9485 9486 // See if we can exploit a trip count to prove the predicate. 9487 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9488 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9489 if (LatchBECount != getCouldNotCompute()) { 9490 // We know that Latch branches back to the loop header exactly 9491 // LatchBECount times. This means the backdege condition at Latch is 9492 // equivalent to "{0,+,1} u< LatchBECount". 9493 Type *Ty = LatchBECount->getType(); 9494 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9495 const SCEV *LoopCounter = 9496 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9497 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9498 LatchBECount)) 9499 return true; 9500 } 9501 9502 // Check conditions due to any @llvm.assume intrinsics. 9503 for (auto &AssumeVH : AC.assumptions()) { 9504 if (!AssumeVH) 9505 continue; 9506 auto *CI = cast<CallInst>(AssumeVH); 9507 if (!DT.dominates(CI, Latch->getTerminator())) 9508 continue; 9509 9510 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9511 return true; 9512 } 9513 9514 // If the loop is not reachable from the entry block, we risk running into an 9515 // infinite loop as we walk up into the dom tree. These loops do not matter 9516 // anyway, so we just return a conservative answer when we see them. 9517 if (!DT.isReachableFromEntry(L->getHeader())) 9518 return false; 9519 9520 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9521 return true; 9522 9523 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9524 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9525 assert(DTN && "should reach the loop header before reaching the root!"); 9526 9527 BasicBlock *BB = DTN->getBlock(); 9528 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9529 return true; 9530 9531 BasicBlock *PBB = BB->getSinglePredecessor(); 9532 if (!PBB) 9533 continue; 9534 9535 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9536 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9537 continue; 9538 9539 Value *Condition = ContinuePredicate->getCondition(); 9540 9541 // If we have an edge `E` within the loop body that dominates the only 9542 // latch, the condition guarding `E` also guards the backedge. This 9543 // reasoning works only for loops with a single latch. 9544 9545 BasicBlockEdge DominatingEdge(PBB, BB); 9546 if (DominatingEdge.isSingleEdge()) { 9547 // We're constructively (and conservatively) enumerating edges within the 9548 // loop body that dominate the latch. The dominator tree better agree 9549 // with us on this: 9550 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9551 9552 if (isImpliedCond(Pred, LHS, RHS, Condition, 9553 BB != ContinuePredicate->getSuccessor(0))) 9554 return true; 9555 } 9556 } 9557 9558 return false; 9559 } 9560 9561 bool 9562 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9563 ICmpInst::Predicate Pred, 9564 const SCEV *LHS, const SCEV *RHS) { 9565 // Interpret a null as meaning no loop, where there is obviously no guard 9566 // (interprocedural conditions notwithstanding). 9567 if (!L) return false; 9568 9569 if (VerifyIR) 9570 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9571 "This cannot be done on broken IR!"); 9572 9573 // Both LHS and RHS must be available at loop entry. 9574 assert(isAvailableAtLoopEntry(LHS, L) && 9575 "LHS is not available at Loop Entry"); 9576 assert(isAvailableAtLoopEntry(RHS, L) && 9577 "RHS is not available at Loop Entry"); 9578 9579 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9580 return true; 9581 9582 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9583 // the facts (a >= b && a != b) separately. A typical situation is when the 9584 // non-strict comparison is known from ranges and non-equality is known from 9585 // dominating predicates. If we are proving strict comparison, we always try 9586 // to prove non-equality and non-strict comparison separately. 9587 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9588 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9589 bool ProvedNonStrictComparison = false; 9590 bool ProvedNonEquality = false; 9591 9592 if (ProvingStrictComparison) { 9593 ProvedNonStrictComparison = 9594 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9595 ProvedNonEquality = 9596 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9597 if (ProvedNonStrictComparison && ProvedNonEquality) 9598 return true; 9599 } 9600 9601 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9602 auto ProveViaGuard = [&](BasicBlock *Block) { 9603 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9604 return true; 9605 if (ProvingStrictComparison) { 9606 if (!ProvedNonStrictComparison) 9607 ProvedNonStrictComparison = 9608 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9609 if (!ProvedNonEquality) 9610 ProvedNonEquality = 9611 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9612 if (ProvedNonStrictComparison && ProvedNonEquality) 9613 return true; 9614 } 9615 return false; 9616 }; 9617 9618 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9619 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9620 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9621 return true; 9622 if (ProvingStrictComparison) { 9623 if (!ProvedNonStrictComparison) 9624 ProvedNonStrictComparison = 9625 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9626 if (!ProvedNonEquality) 9627 ProvedNonEquality = 9628 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9629 if (ProvedNonStrictComparison && ProvedNonEquality) 9630 return true; 9631 } 9632 return false; 9633 }; 9634 9635 // Starting at the loop predecessor, climb up the predecessor chain, as long 9636 // as there are predecessors that can be found that have unique successors 9637 // leading to the original header. 9638 for (std::pair<BasicBlock *, BasicBlock *> 9639 Pair(L->getLoopPredecessor(), L->getHeader()); 9640 Pair.first; 9641 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9642 9643 if (ProveViaGuard(Pair.first)) 9644 return true; 9645 9646 BranchInst *LoopEntryPredicate = 9647 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9648 if (!LoopEntryPredicate || 9649 LoopEntryPredicate->isUnconditional()) 9650 continue; 9651 9652 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9653 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9654 return true; 9655 } 9656 9657 // Check conditions due to any @llvm.assume intrinsics. 9658 for (auto &AssumeVH : AC.assumptions()) { 9659 if (!AssumeVH) 9660 continue; 9661 auto *CI = cast<CallInst>(AssumeVH); 9662 if (!DT.dominates(CI, L->getHeader())) 9663 continue; 9664 9665 if (ProveViaCond(CI->getArgOperand(0), false)) 9666 return true; 9667 } 9668 9669 return false; 9670 } 9671 9672 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9673 const SCEV *LHS, const SCEV *RHS, 9674 Value *FoundCondValue, 9675 bool Inverse) { 9676 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9677 return false; 9678 9679 auto ClearOnExit = 9680 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9681 9682 // Recursively handle And and Or conditions. 9683 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9684 if (BO->getOpcode() == Instruction::And) { 9685 if (!Inverse) 9686 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9687 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9688 } else if (BO->getOpcode() == Instruction::Or) { 9689 if (Inverse) 9690 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9691 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9692 } 9693 } 9694 9695 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9696 if (!ICI) return false; 9697 9698 // Now that we found a conditional branch that dominates the loop or controls 9699 // the loop latch. Check to see if it is the comparison we are looking for. 9700 ICmpInst::Predicate FoundPred; 9701 if (Inverse) 9702 FoundPred = ICI->getInversePredicate(); 9703 else 9704 FoundPred = ICI->getPredicate(); 9705 9706 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9707 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9708 9709 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9710 } 9711 9712 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9713 const SCEV *RHS, 9714 ICmpInst::Predicate FoundPred, 9715 const SCEV *FoundLHS, 9716 const SCEV *FoundRHS) { 9717 // Balance the types. 9718 if (getTypeSizeInBits(LHS->getType()) < 9719 getTypeSizeInBits(FoundLHS->getType())) { 9720 if (CmpInst::isSigned(Pred)) { 9721 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9722 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9723 } else { 9724 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9725 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9726 } 9727 } else if (getTypeSizeInBits(LHS->getType()) > 9728 getTypeSizeInBits(FoundLHS->getType())) { 9729 if (CmpInst::isSigned(FoundPred)) { 9730 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9731 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9732 } else { 9733 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9734 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9735 } 9736 } 9737 9738 // Canonicalize the query to match the way instcombine will have 9739 // canonicalized the comparison. 9740 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9741 if (LHS == RHS) 9742 return CmpInst::isTrueWhenEqual(Pred); 9743 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9744 if (FoundLHS == FoundRHS) 9745 return CmpInst::isFalseWhenEqual(FoundPred); 9746 9747 // Check to see if we can make the LHS or RHS match. 9748 if (LHS == FoundRHS || RHS == FoundLHS) { 9749 if (isa<SCEVConstant>(RHS)) { 9750 std::swap(FoundLHS, FoundRHS); 9751 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9752 } else { 9753 std::swap(LHS, RHS); 9754 Pred = ICmpInst::getSwappedPredicate(Pred); 9755 } 9756 } 9757 9758 // Check whether the found predicate is the same as the desired predicate. 9759 if (FoundPred == Pred) 9760 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9761 9762 // Check whether swapping the found predicate makes it the same as the 9763 // desired predicate. 9764 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9765 if (isa<SCEVConstant>(RHS)) 9766 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9767 else 9768 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9769 RHS, LHS, FoundLHS, FoundRHS); 9770 } 9771 9772 // Unsigned comparison is the same as signed comparison when both the operands 9773 // are non-negative. 9774 if (CmpInst::isUnsigned(FoundPred) && 9775 CmpInst::getSignedPredicate(FoundPred) == Pred && 9776 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9777 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9778 9779 // Check if we can make progress by sharpening ranges. 9780 if (FoundPred == ICmpInst::ICMP_NE && 9781 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9782 9783 const SCEVConstant *C = nullptr; 9784 const SCEV *V = nullptr; 9785 9786 if (isa<SCEVConstant>(FoundLHS)) { 9787 C = cast<SCEVConstant>(FoundLHS); 9788 V = FoundRHS; 9789 } else { 9790 C = cast<SCEVConstant>(FoundRHS); 9791 V = FoundLHS; 9792 } 9793 9794 // The guarding predicate tells us that C != V. If the known range 9795 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9796 // range we consider has to correspond to same signedness as the 9797 // predicate we're interested in folding. 9798 9799 APInt Min = ICmpInst::isSigned(Pred) ? 9800 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9801 9802 if (Min == C->getAPInt()) { 9803 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9804 // This is true even if (Min + 1) wraps around -- in case of 9805 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9806 9807 APInt SharperMin = Min + 1; 9808 9809 switch (Pred) { 9810 case ICmpInst::ICMP_SGE: 9811 case ICmpInst::ICMP_UGE: 9812 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9813 // RHS, we're done. 9814 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9815 getConstant(SharperMin))) 9816 return true; 9817 LLVM_FALLTHROUGH; 9818 9819 case ICmpInst::ICMP_SGT: 9820 case ICmpInst::ICMP_UGT: 9821 // We know from the range information that (V `Pred` Min || 9822 // V == Min). We know from the guarding condition that !(V 9823 // == Min). This gives us 9824 // 9825 // V `Pred` Min || V == Min && !(V == Min) 9826 // => V `Pred` Min 9827 // 9828 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9829 9830 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9831 return true; 9832 LLVM_FALLTHROUGH; 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)) 9845 return true; 9846 if (Pred == ICmpInst::ICMP_NE) 9847 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9848 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9849 return true; 9850 9851 // Otherwise assume the worst. 9852 return false; 9853 } 9854 9855 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9856 const SCEV *&L, const SCEV *&R, 9857 SCEV::NoWrapFlags &Flags) { 9858 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9859 if (!AE || AE->getNumOperands() != 2) 9860 return false; 9861 9862 L = AE->getOperand(0); 9863 R = AE->getOperand(1); 9864 Flags = AE->getNoWrapFlags(); 9865 return true; 9866 } 9867 9868 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9869 const SCEV *Less) { 9870 // We avoid subtracting expressions here because this function is usually 9871 // fairly deep in the call stack (i.e. is called many times). 9872 9873 // X - X = 0. 9874 if (More == Less) 9875 return APInt(getTypeSizeInBits(More->getType()), 0); 9876 9877 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9878 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9879 const auto *MAR = cast<SCEVAddRecExpr>(More); 9880 9881 if (LAR->getLoop() != MAR->getLoop()) 9882 return None; 9883 9884 // We look at affine expressions only; not for correctness but to keep 9885 // getStepRecurrence cheap. 9886 if (!LAR->isAffine() || !MAR->isAffine()) 9887 return None; 9888 9889 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9890 return None; 9891 9892 Less = LAR->getStart(); 9893 More = MAR->getStart(); 9894 9895 // fall through 9896 } 9897 9898 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9899 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9900 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9901 return M - L; 9902 } 9903 9904 SCEV::NoWrapFlags Flags; 9905 const SCEV *LLess = nullptr, *RLess = nullptr; 9906 const SCEV *LMore = nullptr, *RMore = nullptr; 9907 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9908 // Compare (X + C1) vs X. 9909 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9910 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9911 if (RLess == More) 9912 return -(C1->getAPInt()); 9913 9914 // Compare X vs (X + C2). 9915 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9916 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9917 if (RMore == Less) 9918 return C2->getAPInt(); 9919 9920 // Compare (X + C1) vs (X + C2). 9921 if (C1 && C2 && RLess == RMore) 9922 return C2->getAPInt() - C1->getAPInt(); 9923 9924 return None; 9925 } 9926 9927 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9928 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9929 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9930 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9931 return false; 9932 9933 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9934 if (!AddRecLHS) 9935 return false; 9936 9937 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9938 if (!AddRecFoundLHS) 9939 return false; 9940 9941 // We'd like to let SCEV reason about control dependencies, so we constrain 9942 // both the inequalities to be about add recurrences on the same loop. This 9943 // way we can use isLoopEntryGuardedByCond later. 9944 9945 const Loop *L = AddRecFoundLHS->getLoop(); 9946 if (L != AddRecLHS->getLoop()) 9947 return false; 9948 9949 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9950 // 9951 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9952 // ... (2) 9953 // 9954 // Informal proof for (2), assuming (1) [*]: 9955 // 9956 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9957 // 9958 // Then 9959 // 9960 // FoundLHS s< FoundRHS s< INT_MIN - C 9961 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9962 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9963 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9964 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9965 // <=> FoundLHS + C s< FoundRHS + C 9966 // 9967 // [*]: (1) can be proved by ruling out overflow. 9968 // 9969 // [**]: This can be proved by analyzing all the four possibilities: 9970 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9971 // (A s>= 0, B s>= 0). 9972 // 9973 // Note: 9974 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9975 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9976 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9977 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9978 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9979 // C)". 9980 9981 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9982 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9983 if (!LDiff || !RDiff || *LDiff != *RDiff) 9984 return false; 9985 9986 if (LDiff->isMinValue()) 9987 return true; 9988 9989 APInt FoundRHSLimit; 9990 9991 if (Pred == CmpInst::ICMP_ULT) { 9992 FoundRHSLimit = -(*RDiff); 9993 } else { 9994 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9995 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9996 } 9997 9998 // Try to prove (1) or (2), as needed. 9999 return isAvailableAtLoopEntry(FoundRHS, L) && 10000 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10001 getConstant(FoundRHSLimit)); 10002 } 10003 10004 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10005 const SCEV *LHS, const SCEV *RHS, 10006 const SCEV *FoundLHS, 10007 const SCEV *FoundRHS, unsigned Depth) { 10008 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10009 10010 auto ClearOnExit = make_scope_exit([&]() { 10011 if (LPhi) { 10012 bool Erased = PendingMerges.erase(LPhi); 10013 assert(Erased && "Failed to erase LPhi!"); 10014 (void)Erased; 10015 } 10016 if (RPhi) { 10017 bool Erased = PendingMerges.erase(RPhi); 10018 assert(Erased && "Failed to erase RPhi!"); 10019 (void)Erased; 10020 } 10021 }); 10022 10023 // Find respective Phis and check that they are not being pending. 10024 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10025 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10026 if (!PendingMerges.insert(Phi).second) 10027 return false; 10028 LPhi = Phi; 10029 } 10030 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10031 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10032 // If we detect a loop of Phi nodes being processed by this method, for 10033 // example: 10034 // 10035 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10036 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10037 // 10038 // we don't want to deal with a case that complex, so return conservative 10039 // answer false. 10040 if (!PendingMerges.insert(Phi).second) 10041 return false; 10042 RPhi = Phi; 10043 } 10044 10045 // If none of LHS, RHS is a Phi, nothing to do here. 10046 if (!LPhi && !RPhi) 10047 return false; 10048 10049 // If there is a SCEVUnknown Phi we are interested in, make it left. 10050 if (!LPhi) { 10051 std::swap(LHS, RHS); 10052 std::swap(FoundLHS, FoundRHS); 10053 std::swap(LPhi, RPhi); 10054 Pred = ICmpInst::getSwappedPredicate(Pred); 10055 } 10056 10057 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10058 const BasicBlock *LBB = LPhi->getParent(); 10059 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10060 10061 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10062 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10063 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10064 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10065 }; 10066 10067 if (RPhi && RPhi->getParent() == LBB) { 10068 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10069 // If we compare two Phis from the same block, and for each entry block 10070 // the predicate is true for incoming values from this block, then the 10071 // predicate is also true for the Phis. 10072 for (const BasicBlock *IncBB : predecessors(LBB)) { 10073 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10074 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10075 if (!ProvedEasily(L, R)) 10076 return false; 10077 } 10078 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10079 // Case two: RHS is also a Phi from the same basic block, and it is an 10080 // AddRec. It means that there is a loop which has both AddRec and Unknown 10081 // PHIs, for it we can compare incoming values of AddRec from above the loop 10082 // and latch with their respective incoming values of LPhi. 10083 // TODO: Generalize to handle loops with many inputs in a header. 10084 if (LPhi->getNumIncomingValues() != 2) return false; 10085 10086 auto *RLoop = RAR->getLoop(); 10087 auto *Predecessor = RLoop->getLoopPredecessor(); 10088 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10089 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10090 if (!ProvedEasily(L1, RAR->getStart())) 10091 return false; 10092 auto *Latch = RLoop->getLoopLatch(); 10093 assert(Latch && "Loop with AddRec with no latch?"); 10094 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10095 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10096 return false; 10097 } else { 10098 // In all other cases go over inputs of LHS and compare each of them to RHS, 10099 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10100 // At this point RHS is either a non-Phi, or it is a Phi from some block 10101 // different from LBB. 10102 for (const BasicBlock *IncBB : predecessors(LBB)) { 10103 // Check that RHS is available in this block. 10104 if (!dominates(RHS, IncBB)) 10105 return false; 10106 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10107 if (!ProvedEasily(L, RHS)) 10108 return false; 10109 } 10110 } 10111 return true; 10112 } 10113 10114 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10115 const SCEV *LHS, const SCEV *RHS, 10116 const SCEV *FoundLHS, 10117 const SCEV *FoundRHS) { 10118 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10119 return true; 10120 10121 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10122 return true; 10123 10124 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10125 FoundLHS, FoundRHS) || 10126 // ~x < ~y --> x > y 10127 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10128 getNotSCEV(FoundRHS), 10129 getNotSCEV(FoundLHS)); 10130 } 10131 10132 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10133 template <typename MinMaxExprType> 10134 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10135 const SCEV *Candidate) { 10136 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10137 if (!MinMaxExpr) 10138 return false; 10139 10140 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10141 } 10142 10143 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10144 ICmpInst::Predicate Pred, 10145 const SCEV *LHS, const SCEV *RHS) { 10146 // If both sides are affine addrecs for the same loop, with equal 10147 // steps, and we know the recurrences don't wrap, then we only 10148 // need to check the predicate on the starting values. 10149 10150 if (!ICmpInst::isRelational(Pred)) 10151 return false; 10152 10153 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10154 if (!LAR) 10155 return false; 10156 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10157 if (!RAR) 10158 return false; 10159 if (LAR->getLoop() != RAR->getLoop()) 10160 return false; 10161 if (!LAR->isAffine() || !RAR->isAffine()) 10162 return false; 10163 10164 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10165 return false; 10166 10167 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10168 SCEV::FlagNSW : SCEV::FlagNUW; 10169 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10170 return false; 10171 10172 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10173 } 10174 10175 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10176 /// expression? 10177 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10178 ICmpInst::Predicate Pred, 10179 const SCEV *LHS, const SCEV *RHS) { 10180 switch (Pred) { 10181 default: 10182 return false; 10183 10184 case ICmpInst::ICMP_SGE: 10185 std::swap(LHS, RHS); 10186 LLVM_FALLTHROUGH; 10187 case ICmpInst::ICMP_SLE: 10188 return 10189 // min(A, ...) <= A 10190 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10191 // A <= max(A, ...) 10192 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10193 10194 case ICmpInst::ICMP_UGE: 10195 std::swap(LHS, RHS); 10196 LLVM_FALLTHROUGH; 10197 case ICmpInst::ICMP_ULE: 10198 return 10199 // min(A, ...) <= A 10200 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10201 // A <= max(A, ...) 10202 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10203 } 10204 10205 llvm_unreachable("covered switch fell through?!"); 10206 } 10207 10208 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10209 const SCEV *LHS, const SCEV *RHS, 10210 const SCEV *FoundLHS, 10211 const SCEV *FoundRHS, 10212 unsigned Depth) { 10213 assert(getTypeSizeInBits(LHS->getType()) == 10214 getTypeSizeInBits(RHS->getType()) && 10215 "LHS and RHS have different sizes?"); 10216 assert(getTypeSizeInBits(FoundLHS->getType()) == 10217 getTypeSizeInBits(FoundRHS->getType()) && 10218 "FoundLHS and FoundRHS have different sizes?"); 10219 // We want to avoid hurting the compile time with analysis of too big trees. 10220 if (Depth > MaxSCEVOperationsImplicationDepth) 10221 return false; 10222 // We only want to work with ICMP_SGT comparison so far. 10223 // TODO: Extend to ICMP_UGT? 10224 if (Pred == ICmpInst::ICMP_SLT) { 10225 Pred = ICmpInst::ICMP_SGT; 10226 std::swap(LHS, RHS); 10227 std::swap(FoundLHS, FoundRHS); 10228 } 10229 if (Pred != ICmpInst::ICMP_SGT) 10230 return false; 10231 10232 auto GetOpFromSExt = [&](const SCEV *S) { 10233 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10234 return Ext->getOperand(); 10235 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10236 // the constant in some cases. 10237 return S; 10238 }; 10239 10240 // Acquire values from extensions. 10241 auto *OrigLHS = LHS; 10242 auto *OrigFoundLHS = FoundLHS; 10243 LHS = GetOpFromSExt(LHS); 10244 FoundLHS = GetOpFromSExt(FoundLHS); 10245 10246 // Is the SGT predicate can be proved trivially or using the found context. 10247 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10248 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10249 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10250 FoundRHS, Depth + 1); 10251 }; 10252 10253 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10254 // We want to avoid creation of any new non-constant SCEV. Since we are 10255 // going to compare the operands to RHS, we should be certain that we don't 10256 // need any size extensions for this. So let's decline all cases when the 10257 // sizes of types of LHS and RHS do not match. 10258 // TODO: Maybe try to get RHS from sext to catch more cases? 10259 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10260 return false; 10261 10262 // Should not overflow. 10263 if (!LHSAddExpr->hasNoSignedWrap()) 10264 return false; 10265 10266 auto *LL = LHSAddExpr->getOperand(0); 10267 auto *LR = LHSAddExpr->getOperand(1); 10268 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10269 10270 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10271 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10272 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10273 }; 10274 // Try to prove the following rule: 10275 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10276 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10277 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10278 return true; 10279 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10280 Value *LL, *LR; 10281 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10282 10283 using namespace llvm::PatternMatch; 10284 10285 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10286 // Rules for division. 10287 // We are going to perform some comparisons with Denominator and its 10288 // derivative expressions. In general case, creating a SCEV for it may 10289 // lead to a complex analysis of the entire graph, and in particular it 10290 // can request trip count recalculation for the same loop. This would 10291 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10292 // this, we only want to create SCEVs that are constants in this section. 10293 // So we bail if Denominator is not a constant. 10294 if (!isa<ConstantInt>(LR)) 10295 return false; 10296 10297 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10298 10299 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10300 // then a SCEV for the numerator already exists and matches with FoundLHS. 10301 auto *Numerator = getExistingSCEV(LL); 10302 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10303 return false; 10304 10305 // Make sure that the numerator matches with FoundLHS and the denominator 10306 // is positive. 10307 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10308 return false; 10309 10310 auto *DTy = Denominator->getType(); 10311 auto *FRHSTy = FoundRHS->getType(); 10312 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10313 // One of types is a pointer and another one is not. We cannot extend 10314 // them properly to a wider type, so let us just reject this case. 10315 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10316 // to avoid this check. 10317 return false; 10318 10319 // Given that: 10320 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10321 auto *WTy = getWiderType(DTy, FRHSTy); 10322 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10323 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10324 10325 // Try to prove the following rule: 10326 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10327 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10328 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10329 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10330 if (isKnownNonPositive(RHS) && 10331 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10332 return true; 10333 10334 // Try to prove the following rule: 10335 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10336 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10337 // If we divide it by Denominator > 2, then: 10338 // 1. If FoundLHS is negative, then the result is 0. 10339 // 2. If FoundLHS is non-negative, then the result is non-negative. 10340 // Anyways, the result is non-negative. 10341 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10342 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10343 if (isKnownNegative(RHS) && 10344 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10345 return true; 10346 } 10347 } 10348 10349 // If our expression contained SCEVUnknown Phis, and we split it down and now 10350 // need to prove something for them, try to prove the predicate for every 10351 // possible incoming values of those Phis. 10352 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10353 return true; 10354 10355 return false; 10356 } 10357 10358 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10359 const SCEV *LHS, const SCEV *RHS) { 10360 // zext x u<= sext x, sext x s<= zext x 10361 switch (Pred) { 10362 case ICmpInst::ICMP_SGE: 10363 std::swap(LHS, RHS); 10364 LLVM_FALLTHROUGH; 10365 case ICmpInst::ICMP_SLE: { 10366 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10367 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10368 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10369 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10370 return true; 10371 break; 10372 } 10373 case ICmpInst::ICMP_UGE: 10374 std::swap(LHS, RHS); 10375 LLVM_FALLTHROUGH; 10376 case ICmpInst::ICMP_ULE: { 10377 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10378 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10379 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10380 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10381 return true; 10382 break; 10383 } 10384 default: 10385 break; 10386 }; 10387 return false; 10388 } 10389 10390 bool 10391 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10392 const SCEV *LHS, const SCEV *RHS) { 10393 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10394 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10395 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10396 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10397 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10398 } 10399 10400 bool 10401 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10402 const SCEV *LHS, const SCEV *RHS, 10403 const SCEV *FoundLHS, 10404 const SCEV *FoundRHS) { 10405 switch (Pred) { 10406 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10407 case ICmpInst::ICMP_EQ: 10408 case ICmpInst::ICMP_NE: 10409 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10410 return true; 10411 break; 10412 case ICmpInst::ICMP_SLT: 10413 case ICmpInst::ICMP_SLE: 10414 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10415 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10416 return true; 10417 break; 10418 case ICmpInst::ICMP_SGT: 10419 case ICmpInst::ICMP_SGE: 10420 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10421 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10422 return true; 10423 break; 10424 case ICmpInst::ICMP_ULT: 10425 case ICmpInst::ICMP_ULE: 10426 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10427 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10428 return true; 10429 break; 10430 case ICmpInst::ICMP_UGT: 10431 case ICmpInst::ICMP_UGE: 10432 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10433 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10434 return true; 10435 break; 10436 } 10437 10438 // Maybe it can be proved via operations? 10439 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10440 return true; 10441 10442 return false; 10443 } 10444 10445 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10446 const SCEV *LHS, 10447 const SCEV *RHS, 10448 const SCEV *FoundLHS, 10449 const SCEV *FoundRHS) { 10450 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10451 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10452 // reduce the compile time impact of this optimization. 10453 return false; 10454 10455 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10456 if (!Addend) 10457 return false; 10458 10459 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10460 10461 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10462 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10463 ConstantRange FoundLHSRange = 10464 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10465 10466 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10467 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10468 10469 // We can also compute the range of values for `LHS` that satisfy the 10470 // consequent, "`LHS` `Pred` `RHS`": 10471 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10472 ConstantRange SatisfyingLHSRange = 10473 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10474 10475 // The antecedent implies the consequent if every value of `LHS` that 10476 // satisfies the antecedent also satisfies the consequent. 10477 return SatisfyingLHSRange.contains(LHSRange); 10478 } 10479 10480 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10481 bool IsSigned, bool NoWrap) { 10482 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10483 10484 if (NoWrap) return false; 10485 10486 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10487 const SCEV *One = getOne(Stride->getType()); 10488 10489 if (IsSigned) { 10490 APInt MaxRHS = getSignedRangeMax(RHS); 10491 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10492 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10493 10494 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10495 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10496 } 10497 10498 APInt MaxRHS = getUnsignedRangeMax(RHS); 10499 APInt MaxValue = APInt::getMaxValue(BitWidth); 10500 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10501 10502 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10503 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10504 } 10505 10506 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10507 bool IsSigned, bool NoWrap) { 10508 if (NoWrap) return false; 10509 10510 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10511 const SCEV *One = getOne(Stride->getType()); 10512 10513 if (IsSigned) { 10514 APInt MinRHS = getSignedRangeMin(RHS); 10515 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10516 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10517 10518 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10519 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10520 } 10521 10522 APInt MinRHS = getUnsignedRangeMin(RHS); 10523 APInt MinValue = APInt::getMinValue(BitWidth); 10524 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10525 10526 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10527 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10528 } 10529 10530 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10531 bool Equality) { 10532 const SCEV *One = getOne(Step->getType()); 10533 Delta = Equality ? getAddExpr(Delta, Step) 10534 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10535 return getUDivExpr(Delta, Step); 10536 } 10537 10538 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10539 const SCEV *Stride, 10540 const SCEV *End, 10541 unsigned BitWidth, 10542 bool IsSigned) { 10543 10544 assert(!isKnownNonPositive(Stride) && 10545 "Stride is expected strictly positive!"); 10546 // Calculate the maximum backedge count based on the range of values 10547 // permitted by Start, End, and Stride. 10548 const SCEV *MaxBECount; 10549 APInt MinStart = 10550 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10551 10552 APInt StrideForMaxBECount = 10553 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10554 10555 // We already know that the stride is positive, so we paper over conservatism 10556 // in our range computation by forcing StrideForMaxBECount to be at least one. 10557 // In theory this is unnecessary, but we expect MaxBECount to be a 10558 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10559 // is nothing to constant fold it to). 10560 APInt One(BitWidth, 1, IsSigned); 10561 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10562 10563 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10564 : APInt::getMaxValue(BitWidth); 10565 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10566 10567 // Although End can be a MAX expression we estimate MaxEnd considering only 10568 // the case End = RHS of the loop termination condition. This is safe because 10569 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10570 // taken count. 10571 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10572 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10573 10574 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10575 getConstant(StrideForMaxBECount) /* Step */, 10576 false /* Equality */); 10577 10578 return MaxBECount; 10579 } 10580 10581 ScalarEvolution::ExitLimit 10582 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10583 const Loop *L, bool IsSigned, 10584 bool ControlsExit, bool AllowPredicates) { 10585 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10586 10587 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10588 bool PredicatedIV = false; 10589 10590 if (!IV && AllowPredicates) { 10591 // Try to make this an AddRec using runtime tests, in the first X 10592 // iterations of this loop, where X is the SCEV expression found by the 10593 // algorithm below. 10594 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10595 PredicatedIV = true; 10596 } 10597 10598 // Avoid weird loops 10599 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10600 return getCouldNotCompute(); 10601 10602 bool NoWrap = ControlsExit && 10603 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10604 10605 const SCEV *Stride = IV->getStepRecurrence(*this); 10606 10607 bool PositiveStride = isKnownPositive(Stride); 10608 10609 // Avoid negative or zero stride values. 10610 if (!PositiveStride) { 10611 // We can compute the correct backedge taken count for loops with unknown 10612 // strides if we can prove that the loop is not an infinite loop with side 10613 // effects. Here's the loop structure we are trying to handle - 10614 // 10615 // i = start 10616 // do { 10617 // A[i] = i; 10618 // i += s; 10619 // } while (i < end); 10620 // 10621 // The backedge taken count for such loops is evaluated as - 10622 // (max(end, start + stride) - start - 1) /u stride 10623 // 10624 // The additional preconditions that we need to check to prove correctness 10625 // of the above formula is as follows - 10626 // 10627 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10628 // NoWrap flag). 10629 // b) loop is single exit with no side effects. 10630 // 10631 // 10632 // Precondition a) implies that if the stride is negative, this is a single 10633 // trip loop. The backedge taken count formula reduces to zero in this case. 10634 // 10635 // Precondition b) implies that the unknown stride cannot be zero otherwise 10636 // we have UB. 10637 // 10638 // The positive stride case is the same as isKnownPositive(Stride) returning 10639 // true (original behavior of the function). 10640 // 10641 // We want to make sure that the stride is truly unknown as there are edge 10642 // cases where ScalarEvolution propagates no wrap flags to the 10643 // post-increment/decrement IV even though the increment/decrement operation 10644 // itself is wrapping. The computed backedge taken count may be wrong in 10645 // such cases. This is prevented by checking that the stride is not known to 10646 // be either positive or non-positive. For example, no wrap flags are 10647 // propagated to the post-increment IV of this loop with a trip count of 2 - 10648 // 10649 // unsigned char i; 10650 // for(i=127; i<128; i+=129) 10651 // A[i] = i; 10652 // 10653 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10654 !loopHasNoSideEffects(L)) 10655 return getCouldNotCompute(); 10656 } else if (!Stride->isOne() && 10657 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10658 // Avoid proven overflow cases: this will ensure that the backedge taken 10659 // count will not generate any unsigned overflow. Relaxed no-overflow 10660 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10661 // undefined behaviors like the case of C language. 10662 return getCouldNotCompute(); 10663 10664 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10665 : ICmpInst::ICMP_ULT; 10666 const SCEV *Start = IV->getStart(); 10667 const SCEV *End = RHS; 10668 // When the RHS is not invariant, we do not know the end bound of the loop and 10669 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10670 // calculate the MaxBECount, given the start, stride and max value for the end 10671 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10672 // checked above). 10673 if (!isLoopInvariant(RHS, L)) { 10674 const SCEV *MaxBECount = computeMaxBECountForLT( 10675 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10676 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10677 false /*MaxOrZero*/, Predicates); 10678 } 10679 // If the backedge is taken at least once, then it will be taken 10680 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10681 // is the LHS value of the less-than comparison the first time it is evaluated 10682 // and End is the RHS. 10683 const SCEV *BECountIfBackedgeTaken = 10684 computeBECount(getMinusSCEV(End, Start), Stride, false); 10685 // If the loop entry is guarded by the result of the backedge test of the 10686 // first loop iteration, then we know the backedge will be taken at least 10687 // once and so the backedge taken count is as above. If not then we use the 10688 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10689 // as if the backedge is taken at least once max(End,Start) is End and so the 10690 // result is as above, and if not max(End,Start) is Start so we get a backedge 10691 // count of zero. 10692 const SCEV *BECount; 10693 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10694 BECount = BECountIfBackedgeTaken; 10695 else { 10696 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10697 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10698 } 10699 10700 const SCEV *MaxBECount; 10701 bool MaxOrZero = false; 10702 if (isa<SCEVConstant>(BECount)) 10703 MaxBECount = BECount; 10704 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10705 // If we know exactly how many times the backedge will be taken if it's 10706 // taken at least once, then the backedge count will either be that or 10707 // zero. 10708 MaxBECount = BECountIfBackedgeTaken; 10709 MaxOrZero = true; 10710 } else { 10711 MaxBECount = computeMaxBECountForLT( 10712 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10713 } 10714 10715 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10716 !isa<SCEVCouldNotCompute>(BECount)) 10717 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10718 10719 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10720 } 10721 10722 ScalarEvolution::ExitLimit 10723 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10724 const Loop *L, bool IsSigned, 10725 bool ControlsExit, bool AllowPredicates) { 10726 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10727 // We handle only IV > Invariant 10728 if (!isLoopInvariant(RHS, L)) 10729 return getCouldNotCompute(); 10730 10731 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10732 if (!IV && AllowPredicates) 10733 // Try to make this an AddRec using runtime tests, in the first X 10734 // iterations of this loop, where X is the SCEV expression found by the 10735 // algorithm below. 10736 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10737 10738 // Avoid weird loops 10739 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10740 return getCouldNotCompute(); 10741 10742 bool NoWrap = ControlsExit && 10743 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10744 10745 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10746 10747 // Avoid negative or zero stride values 10748 if (!isKnownPositive(Stride)) 10749 return getCouldNotCompute(); 10750 10751 // Avoid proven overflow cases: this will ensure that the backedge taken count 10752 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10753 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10754 // behaviors like the case of C language. 10755 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10756 return getCouldNotCompute(); 10757 10758 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10759 : ICmpInst::ICMP_UGT; 10760 10761 const SCEV *Start = IV->getStart(); 10762 const SCEV *End = RHS; 10763 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10764 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10765 10766 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10767 10768 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10769 : getUnsignedRangeMax(Start); 10770 10771 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10772 : getUnsignedRangeMin(Stride); 10773 10774 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10775 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10776 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10777 10778 // Although End can be a MIN expression we estimate MinEnd considering only 10779 // the case End = RHS. This is safe because in the other case (Start - End) 10780 // is zero, leading to a zero maximum backedge taken count. 10781 APInt MinEnd = 10782 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10783 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10784 10785 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10786 ? BECount 10787 : computeBECount(getConstant(MaxStart - MinEnd), 10788 getConstant(MinStride), false); 10789 10790 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10791 MaxBECount = BECount; 10792 10793 return ExitLimit(BECount, MaxBECount, false, Predicates); 10794 } 10795 10796 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10797 ScalarEvolution &SE) const { 10798 if (Range.isFullSet()) // Infinite loop. 10799 return SE.getCouldNotCompute(); 10800 10801 // If the start is a non-zero constant, shift the range to simplify things. 10802 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10803 if (!SC->getValue()->isZero()) { 10804 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10805 Operands[0] = SE.getZero(SC->getType()); 10806 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10807 getNoWrapFlags(FlagNW)); 10808 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10809 return ShiftedAddRec->getNumIterationsInRange( 10810 Range.subtract(SC->getAPInt()), SE); 10811 // This is strange and shouldn't happen. 10812 return SE.getCouldNotCompute(); 10813 } 10814 10815 // The only time we can solve this is when we have all constant indices. 10816 // Otherwise, we cannot determine the overflow conditions. 10817 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10818 return SE.getCouldNotCompute(); 10819 10820 // Okay at this point we know that all elements of the chrec are constants and 10821 // that the start element is zero. 10822 10823 // First check to see if the range contains zero. If not, the first 10824 // iteration exits. 10825 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10826 if (!Range.contains(APInt(BitWidth, 0))) 10827 return SE.getZero(getType()); 10828 10829 if (isAffine()) { 10830 // If this is an affine expression then we have this situation: 10831 // Solve {0,+,A} in Range === Ax in Range 10832 10833 // We know that zero is in the range. If A is positive then we know that 10834 // the upper value of the range must be the first possible exit value. 10835 // If A is negative then the lower of the range is the last possible loop 10836 // value. Also note that we already checked for a full range. 10837 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10838 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10839 10840 // The exit value should be (End+A)/A. 10841 APInt ExitVal = (End + A).udiv(A); 10842 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10843 10844 // Evaluate at the exit value. If we really did fall out of the valid 10845 // range, then we computed our trip count, otherwise wrap around or other 10846 // things must have happened. 10847 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10848 if (Range.contains(Val->getValue())) 10849 return SE.getCouldNotCompute(); // Something strange happened 10850 10851 // Ensure that the previous value is in the range. This is a sanity check. 10852 assert(Range.contains( 10853 EvaluateConstantChrecAtConstant(this, 10854 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10855 "Linear scev computation is off in a bad way!"); 10856 return SE.getConstant(ExitValue); 10857 } 10858 10859 if (isQuadratic()) { 10860 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10861 return SE.getConstant(S.getValue()); 10862 } 10863 10864 return SE.getCouldNotCompute(); 10865 } 10866 10867 const SCEVAddRecExpr * 10868 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10869 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10870 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10871 // but in this case we cannot guarantee that the value returned will be an 10872 // AddRec because SCEV does not have a fixed point where it stops 10873 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10874 // may happen if we reach arithmetic depth limit while simplifying. So we 10875 // construct the returned value explicitly. 10876 SmallVector<const SCEV *, 3> Ops; 10877 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10878 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10879 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10880 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10881 // We know that the last operand is not a constant zero (otherwise it would 10882 // have been popped out earlier). This guarantees us that if the result has 10883 // the same last operand, then it will also not be popped out, meaning that 10884 // the returned value will be an AddRec. 10885 const SCEV *Last = getOperand(getNumOperands() - 1); 10886 assert(!Last->isZero() && "Recurrency with zero step?"); 10887 Ops.push_back(Last); 10888 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10889 SCEV::FlagAnyWrap)); 10890 } 10891 10892 // Return true when S contains at least an undef value. 10893 static inline bool containsUndefs(const SCEV *S) { 10894 return SCEVExprContains(S, [](const SCEV *S) { 10895 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10896 return isa<UndefValue>(SU->getValue()); 10897 return false; 10898 }); 10899 } 10900 10901 namespace { 10902 10903 // Collect all steps of SCEV expressions. 10904 struct SCEVCollectStrides { 10905 ScalarEvolution &SE; 10906 SmallVectorImpl<const SCEV *> &Strides; 10907 10908 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10909 : SE(SE), Strides(S) {} 10910 10911 bool follow(const SCEV *S) { 10912 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10913 Strides.push_back(AR->getStepRecurrence(SE)); 10914 return true; 10915 } 10916 10917 bool isDone() const { return false; } 10918 }; 10919 10920 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10921 struct SCEVCollectTerms { 10922 SmallVectorImpl<const SCEV *> &Terms; 10923 10924 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10925 10926 bool follow(const SCEV *S) { 10927 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10928 isa<SCEVSignExtendExpr>(S)) { 10929 if (!containsUndefs(S)) 10930 Terms.push_back(S); 10931 10932 // Stop recursion: once we collected a term, do not walk its operands. 10933 return false; 10934 } 10935 10936 // Keep looking. 10937 return true; 10938 } 10939 10940 bool isDone() const { return false; } 10941 }; 10942 10943 // Check if a SCEV contains an AddRecExpr. 10944 struct SCEVHasAddRec { 10945 bool &ContainsAddRec; 10946 10947 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10948 ContainsAddRec = false; 10949 } 10950 10951 bool follow(const SCEV *S) { 10952 if (isa<SCEVAddRecExpr>(S)) { 10953 ContainsAddRec = true; 10954 10955 // Stop recursion: once we collected a term, do not walk its operands. 10956 return false; 10957 } 10958 10959 // Keep looking. 10960 return true; 10961 } 10962 10963 bool isDone() const { return false; } 10964 }; 10965 10966 // Find factors that are multiplied with an expression that (possibly as a 10967 // subexpression) contains an AddRecExpr. In the expression: 10968 // 10969 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10970 // 10971 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10972 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10973 // parameters as they form a product with an induction variable. 10974 // 10975 // This collector expects all array size parameters to be in the same MulExpr. 10976 // It might be necessary to later add support for collecting parameters that are 10977 // spread over different nested MulExpr. 10978 struct SCEVCollectAddRecMultiplies { 10979 SmallVectorImpl<const SCEV *> &Terms; 10980 ScalarEvolution &SE; 10981 10982 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10983 : Terms(T), SE(SE) {} 10984 10985 bool follow(const SCEV *S) { 10986 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10987 bool HasAddRec = false; 10988 SmallVector<const SCEV *, 0> Operands; 10989 for (auto Op : Mul->operands()) { 10990 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10991 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10992 Operands.push_back(Op); 10993 } else if (Unknown) { 10994 HasAddRec = true; 10995 } else { 10996 bool ContainsAddRec; 10997 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10998 visitAll(Op, ContiansAddRec); 10999 HasAddRec |= ContainsAddRec; 11000 } 11001 } 11002 if (Operands.size() == 0) 11003 return true; 11004 11005 if (!HasAddRec) 11006 return false; 11007 11008 Terms.push_back(SE.getMulExpr(Operands)); 11009 // Stop recursion: once we collected a term, do not walk its operands. 11010 return false; 11011 } 11012 11013 // Keep looking. 11014 return true; 11015 } 11016 11017 bool isDone() const { return false; } 11018 }; 11019 11020 } // end anonymous namespace 11021 11022 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11023 /// two places: 11024 /// 1) The strides of AddRec expressions. 11025 /// 2) Unknowns that are multiplied with AddRec expressions. 11026 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11027 SmallVectorImpl<const SCEV *> &Terms) { 11028 SmallVector<const SCEV *, 4> Strides; 11029 SCEVCollectStrides StrideCollector(*this, Strides); 11030 visitAll(Expr, StrideCollector); 11031 11032 LLVM_DEBUG({ 11033 dbgs() << "Strides:\n"; 11034 for (const SCEV *S : Strides) 11035 dbgs() << *S << "\n"; 11036 }); 11037 11038 for (const SCEV *S : Strides) { 11039 SCEVCollectTerms TermCollector(Terms); 11040 visitAll(S, TermCollector); 11041 } 11042 11043 LLVM_DEBUG({ 11044 dbgs() << "Terms:\n"; 11045 for (const SCEV *T : Terms) 11046 dbgs() << *T << "\n"; 11047 }); 11048 11049 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11050 visitAll(Expr, MulCollector); 11051 } 11052 11053 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11054 SmallVectorImpl<const SCEV *> &Terms, 11055 SmallVectorImpl<const SCEV *> &Sizes) { 11056 int Last = Terms.size() - 1; 11057 const SCEV *Step = Terms[Last]; 11058 11059 // End of recursion. 11060 if (Last == 0) { 11061 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11062 SmallVector<const SCEV *, 2> Qs; 11063 for (const SCEV *Op : M->operands()) 11064 if (!isa<SCEVConstant>(Op)) 11065 Qs.push_back(Op); 11066 11067 Step = SE.getMulExpr(Qs); 11068 } 11069 11070 Sizes.push_back(Step); 11071 return true; 11072 } 11073 11074 for (const SCEV *&Term : Terms) { 11075 // Normalize the terms before the next call to findArrayDimensionsRec. 11076 const SCEV *Q, *R; 11077 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11078 11079 // Bail out when GCD does not evenly divide one of the terms. 11080 if (!R->isZero()) 11081 return false; 11082 11083 Term = Q; 11084 } 11085 11086 // Remove all SCEVConstants. 11087 Terms.erase( 11088 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11089 Terms.end()); 11090 11091 if (Terms.size() > 0) 11092 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11093 return false; 11094 11095 Sizes.push_back(Step); 11096 return true; 11097 } 11098 11099 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11100 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11101 for (const SCEV *T : Terms) 11102 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11103 return true; 11104 return false; 11105 } 11106 11107 // Return the number of product terms in S. 11108 static inline int numberOfTerms(const SCEV *S) { 11109 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11110 return Expr->getNumOperands(); 11111 return 1; 11112 } 11113 11114 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11115 if (isa<SCEVConstant>(T)) 11116 return nullptr; 11117 11118 if (isa<SCEVUnknown>(T)) 11119 return T; 11120 11121 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11122 SmallVector<const SCEV *, 2> Factors; 11123 for (const SCEV *Op : M->operands()) 11124 if (!isa<SCEVConstant>(Op)) 11125 Factors.push_back(Op); 11126 11127 return SE.getMulExpr(Factors); 11128 } 11129 11130 return T; 11131 } 11132 11133 /// Return the size of an element read or written by Inst. 11134 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11135 Type *Ty; 11136 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11137 Ty = Store->getValueOperand()->getType(); 11138 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11139 Ty = Load->getType(); 11140 else 11141 return nullptr; 11142 11143 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11144 return getSizeOfExpr(ETy, Ty); 11145 } 11146 11147 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11148 SmallVectorImpl<const SCEV *> &Sizes, 11149 const SCEV *ElementSize) { 11150 if (Terms.size() < 1 || !ElementSize) 11151 return; 11152 11153 // Early return when Terms do not contain parameters: we do not delinearize 11154 // non parametric SCEVs. 11155 if (!containsParameters(Terms)) 11156 return; 11157 11158 LLVM_DEBUG({ 11159 dbgs() << "Terms:\n"; 11160 for (const SCEV *T : Terms) 11161 dbgs() << *T << "\n"; 11162 }); 11163 11164 // Remove duplicates. 11165 array_pod_sort(Terms.begin(), Terms.end()); 11166 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11167 11168 // Put larger terms first. 11169 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11170 return numberOfTerms(LHS) > numberOfTerms(RHS); 11171 }); 11172 11173 // Try to divide all terms by the element size. If term is not divisible by 11174 // element size, proceed with the original term. 11175 for (const SCEV *&Term : Terms) { 11176 const SCEV *Q, *R; 11177 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11178 if (!Q->isZero()) 11179 Term = Q; 11180 } 11181 11182 SmallVector<const SCEV *, 4> NewTerms; 11183 11184 // Remove constant factors. 11185 for (const SCEV *T : Terms) 11186 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11187 NewTerms.push_back(NewT); 11188 11189 LLVM_DEBUG({ 11190 dbgs() << "Terms after sorting:\n"; 11191 for (const SCEV *T : NewTerms) 11192 dbgs() << *T << "\n"; 11193 }); 11194 11195 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11196 Sizes.clear(); 11197 return; 11198 } 11199 11200 // The last element to be pushed into Sizes is the size of an element. 11201 Sizes.push_back(ElementSize); 11202 11203 LLVM_DEBUG({ 11204 dbgs() << "Sizes:\n"; 11205 for (const SCEV *S : Sizes) 11206 dbgs() << *S << "\n"; 11207 }); 11208 } 11209 11210 void ScalarEvolution::computeAccessFunctions( 11211 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11212 SmallVectorImpl<const SCEV *> &Sizes) { 11213 // Early exit in case this SCEV is not an affine multivariate function. 11214 if (Sizes.empty()) 11215 return; 11216 11217 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11218 if (!AR->isAffine()) 11219 return; 11220 11221 const SCEV *Res = Expr; 11222 int Last = Sizes.size() - 1; 11223 for (int i = Last; i >= 0; i--) { 11224 const SCEV *Q, *R; 11225 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11226 11227 LLVM_DEBUG({ 11228 dbgs() << "Res: " << *Res << "\n"; 11229 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11230 dbgs() << "Res divided by Sizes[i]:\n"; 11231 dbgs() << "Quotient: " << *Q << "\n"; 11232 dbgs() << "Remainder: " << *R << "\n"; 11233 }); 11234 11235 Res = Q; 11236 11237 // Do not record the last subscript corresponding to the size of elements in 11238 // the array. 11239 if (i == Last) { 11240 11241 // Bail out if the remainder is too complex. 11242 if (isa<SCEVAddRecExpr>(R)) { 11243 Subscripts.clear(); 11244 Sizes.clear(); 11245 return; 11246 } 11247 11248 continue; 11249 } 11250 11251 // Record the access function for the current subscript. 11252 Subscripts.push_back(R); 11253 } 11254 11255 // Also push in last position the remainder of the last division: it will be 11256 // the access function of the innermost dimension. 11257 Subscripts.push_back(Res); 11258 11259 std::reverse(Subscripts.begin(), Subscripts.end()); 11260 11261 LLVM_DEBUG({ 11262 dbgs() << "Subscripts:\n"; 11263 for (const SCEV *S : Subscripts) 11264 dbgs() << *S << "\n"; 11265 }); 11266 } 11267 11268 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11269 /// sizes of an array access. Returns the remainder of the delinearization that 11270 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11271 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11272 /// expressions in the stride and base of a SCEV corresponding to the 11273 /// computation of a GCD (greatest common divisor) of base and stride. When 11274 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11275 /// 11276 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11277 /// 11278 /// void foo(long n, long m, long o, double A[n][m][o]) { 11279 /// 11280 /// for (long i = 0; i < n; i++) 11281 /// for (long j = 0; j < m; j++) 11282 /// for (long k = 0; k < o; k++) 11283 /// A[i][j][k] = 1.0; 11284 /// } 11285 /// 11286 /// the delinearization input is the following AddRec SCEV: 11287 /// 11288 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11289 /// 11290 /// From this SCEV, we are able to say that the base offset of the access is %A 11291 /// because it appears as an offset that does not divide any of the strides in 11292 /// the loops: 11293 /// 11294 /// CHECK: Base offset: %A 11295 /// 11296 /// and then SCEV->delinearize determines the size of some of the dimensions of 11297 /// the array as these are the multiples by which the strides are happening: 11298 /// 11299 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11300 /// 11301 /// Note that the outermost dimension remains of UnknownSize because there are 11302 /// no strides that would help identifying the size of the last dimension: when 11303 /// the array has been statically allocated, one could compute the size of that 11304 /// dimension by dividing the overall size of the array by the size of the known 11305 /// dimensions: %m * %o * 8. 11306 /// 11307 /// Finally delinearize provides the access functions for the array reference 11308 /// that does correspond to A[i][j][k] of the above C testcase: 11309 /// 11310 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11311 /// 11312 /// The testcases are checking the output of a function pass: 11313 /// DelinearizationPass that walks through all loads and stores of a function 11314 /// asking for the SCEV of the memory access with respect to all enclosing 11315 /// loops, calling SCEV->delinearize on that and printing the results. 11316 void ScalarEvolution::delinearize(const SCEV *Expr, 11317 SmallVectorImpl<const SCEV *> &Subscripts, 11318 SmallVectorImpl<const SCEV *> &Sizes, 11319 const SCEV *ElementSize) { 11320 // First step: collect parametric terms. 11321 SmallVector<const SCEV *, 4> Terms; 11322 collectParametricTerms(Expr, Terms); 11323 11324 if (Terms.empty()) 11325 return; 11326 11327 // Second step: find subscript sizes. 11328 findArrayDimensions(Terms, Sizes, ElementSize); 11329 11330 if (Sizes.empty()) 11331 return; 11332 11333 // Third step: compute the access functions for each subscript. 11334 computeAccessFunctions(Expr, Subscripts, Sizes); 11335 11336 if (Subscripts.empty()) 11337 return; 11338 11339 LLVM_DEBUG({ 11340 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11341 dbgs() << "ArrayDecl[UnknownSize]"; 11342 for (const SCEV *S : Sizes) 11343 dbgs() << "[" << *S << "]"; 11344 11345 dbgs() << "\nArrayRef"; 11346 for (const SCEV *S : Subscripts) 11347 dbgs() << "[" << *S << "]"; 11348 dbgs() << "\n"; 11349 }); 11350 } 11351 11352 //===----------------------------------------------------------------------===// 11353 // SCEVCallbackVH Class Implementation 11354 //===----------------------------------------------------------------------===// 11355 11356 void ScalarEvolution::SCEVCallbackVH::deleted() { 11357 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11358 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11359 SE->ConstantEvolutionLoopExitValue.erase(PN); 11360 SE->eraseValueFromMap(getValPtr()); 11361 // this now dangles! 11362 } 11363 11364 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11365 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11366 11367 // Forget all the expressions associated with users of the old value, 11368 // so that future queries will recompute the expressions using the new 11369 // value. 11370 Value *Old = getValPtr(); 11371 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11372 SmallPtrSet<User *, 8> Visited; 11373 while (!Worklist.empty()) { 11374 User *U = Worklist.pop_back_val(); 11375 // Deleting the Old value will cause this to dangle. Postpone 11376 // that until everything else is done. 11377 if (U == Old) 11378 continue; 11379 if (!Visited.insert(U).second) 11380 continue; 11381 if (PHINode *PN = dyn_cast<PHINode>(U)) 11382 SE->ConstantEvolutionLoopExitValue.erase(PN); 11383 SE->eraseValueFromMap(U); 11384 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11385 } 11386 // Delete the Old value. 11387 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11388 SE->ConstantEvolutionLoopExitValue.erase(PN); 11389 SE->eraseValueFromMap(Old); 11390 // this now dangles! 11391 } 11392 11393 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11394 : CallbackVH(V), SE(se) {} 11395 11396 //===----------------------------------------------------------------------===// 11397 // ScalarEvolution Class Implementation 11398 //===----------------------------------------------------------------------===// 11399 11400 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11401 AssumptionCache &AC, DominatorTree &DT, 11402 LoopInfo &LI) 11403 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11404 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11405 LoopDispositions(64), BlockDispositions(64) { 11406 // To use guards for proving predicates, we need to scan every instruction in 11407 // relevant basic blocks, and not just terminators. Doing this is a waste of 11408 // time if the IR does not actually contain any calls to 11409 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11410 // 11411 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11412 // to _add_ guards to the module when there weren't any before, and wants 11413 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11414 // efficient in lieu of being smart in that rather obscure case. 11415 11416 auto *GuardDecl = F.getParent()->getFunction( 11417 Intrinsic::getName(Intrinsic::experimental_guard)); 11418 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11419 } 11420 11421 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11422 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11423 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11424 ValueExprMap(std::move(Arg.ValueExprMap)), 11425 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11426 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11427 PendingMerges(std::move(Arg.PendingMerges)), 11428 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11429 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11430 PredicatedBackedgeTakenCounts( 11431 std::move(Arg.PredicatedBackedgeTakenCounts)), 11432 ConstantEvolutionLoopExitValue( 11433 std::move(Arg.ConstantEvolutionLoopExitValue)), 11434 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11435 LoopDispositions(std::move(Arg.LoopDispositions)), 11436 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11437 BlockDispositions(std::move(Arg.BlockDispositions)), 11438 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11439 SignedRanges(std::move(Arg.SignedRanges)), 11440 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11441 UniquePreds(std::move(Arg.UniquePreds)), 11442 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11443 LoopUsers(std::move(Arg.LoopUsers)), 11444 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11445 FirstUnknown(Arg.FirstUnknown) { 11446 Arg.FirstUnknown = nullptr; 11447 } 11448 11449 ScalarEvolution::~ScalarEvolution() { 11450 // Iterate through all the SCEVUnknown instances and call their 11451 // destructors, so that they release their references to their values. 11452 for (SCEVUnknown *U = FirstUnknown; U;) { 11453 SCEVUnknown *Tmp = U; 11454 U = U->Next; 11455 Tmp->~SCEVUnknown(); 11456 } 11457 FirstUnknown = nullptr; 11458 11459 ExprValueMap.clear(); 11460 ValueExprMap.clear(); 11461 HasRecMap.clear(); 11462 11463 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11464 // that a loop had multiple computable exits. 11465 for (auto &BTCI : BackedgeTakenCounts) 11466 BTCI.second.clear(); 11467 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11468 BTCI.second.clear(); 11469 11470 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11471 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11472 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11473 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11474 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11475 } 11476 11477 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11478 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11479 } 11480 11481 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11482 const Loop *L) { 11483 // Print all inner loops first 11484 for (Loop *I : *L) 11485 PrintLoopInfo(OS, SE, I); 11486 11487 OS << "Loop "; 11488 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11489 OS << ": "; 11490 11491 SmallVector<BasicBlock *, 8> ExitingBlocks; 11492 L->getExitingBlocks(ExitingBlocks); 11493 if (ExitingBlocks.size() != 1) 11494 OS << "<multiple exits> "; 11495 11496 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11497 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11498 else 11499 OS << "Unpredictable backedge-taken count.\n"; 11500 11501 if (ExitingBlocks.size() > 1) 11502 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11503 OS << " exit count for " << ExitingBlock->getName() << ": " 11504 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11505 } 11506 11507 OS << "Loop "; 11508 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11509 OS << ": "; 11510 11511 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11512 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11513 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11514 OS << ", actual taken count either this or zero."; 11515 } else { 11516 OS << "Unpredictable max backedge-taken count. "; 11517 } 11518 11519 OS << "\n" 11520 "Loop "; 11521 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11522 OS << ": "; 11523 11524 SCEVUnionPredicate Pred; 11525 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11526 if (!isa<SCEVCouldNotCompute>(PBT)) { 11527 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11528 OS << " Predicates:\n"; 11529 Pred.print(OS, 4); 11530 } else { 11531 OS << "Unpredictable predicated backedge-taken count. "; 11532 } 11533 OS << "\n"; 11534 11535 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11536 OS << "Loop "; 11537 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11538 OS << ": "; 11539 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11540 } 11541 } 11542 11543 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11544 switch (LD) { 11545 case ScalarEvolution::LoopVariant: 11546 return "Variant"; 11547 case ScalarEvolution::LoopInvariant: 11548 return "Invariant"; 11549 case ScalarEvolution::LoopComputable: 11550 return "Computable"; 11551 } 11552 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11553 } 11554 11555 void ScalarEvolution::print(raw_ostream &OS) const { 11556 // ScalarEvolution's implementation of the print method is to print 11557 // out SCEV values of all instructions that are interesting. Doing 11558 // this potentially causes it to create new SCEV objects though, 11559 // which technically conflicts with the const qualifier. This isn't 11560 // observable from outside the class though, so casting away the 11561 // const isn't dangerous. 11562 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11563 11564 OS << "Classifying expressions for: "; 11565 F.printAsOperand(OS, /*PrintType=*/false); 11566 OS << "\n"; 11567 for (Instruction &I : instructions(F)) 11568 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11569 OS << I << '\n'; 11570 OS << " --> "; 11571 const SCEV *SV = SE.getSCEV(&I); 11572 SV->print(OS); 11573 if (!isa<SCEVCouldNotCompute>(SV)) { 11574 OS << " U: "; 11575 SE.getUnsignedRange(SV).print(OS); 11576 OS << " S: "; 11577 SE.getSignedRange(SV).print(OS); 11578 } 11579 11580 const Loop *L = LI.getLoopFor(I.getParent()); 11581 11582 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11583 if (AtUse != SV) { 11584 OS << " --> "; 11585 AtUse->print(OS); 11586 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11587 OS << " U: "; 11588 SE.getUnsignedRange(AtUse).print(OS); 11589 OS << " S: "; 11590 SE.getSignedRange(AtUse).print(OS); 11591 } 11592 } 11593 11594 if (L) { 11595 OS << "\t\t" "Exits: "; 11596 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11597 if (!SE.isLoopInvariant(ExitValue, L)) { 11598 OS << "<<Unknown>>"; 11599 } else { 11600 OS << *ExitValue; 11601 } 11602 11603 bool First = true; 11604 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11605 if (First) { 11606 OS << "\t\t" "LoopDispositions: { "; 11607 First = false; 11608 } else { 11609 OS << ", "; 11610 } 11611 11612 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11613 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11614 } 11615 11616 for (auto *InnerL : depth_first(L)) { 11617 if (InnerL == L) 11618 continue; 11619 if (First) { 11620 OS << "\t\t" "LoopDispositions: { "; 11621 First = false; 11622 } else { 11623 OS << ", "; 11624 } 11625 11626 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11627 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11628 } 11629 11630 OS << " }"; 11631 } 11632 11633 OS << "\n"; 11634 } 11635 11636 OS << "Determining loop execution counts for: "; 11637 F.printAsOperand(OS, /*PrintType=*/false); 11638 OS << "\n"; 11639 for (Loop *I : LI) 11640 PrintLoopInfo(OS, &SE, I); 11641 } 11642 11643 ScalarEvolution::LoopDisposition 11644 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11645 auto &Values = LoopDispositions[S]; 11646 for (auto &V : Values) { 11647 if (V.getPointer() == L) 11648 return V.getInt(); 11649 } 11650 Values.emplace_back(L, LoopVariant); 11651 LoopDisposition D = computeLoopDisposition(S, L); 11652 auto &Values2 = LoopDispositions[S]; 11653 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11654 if (V.getPointer() == L) { 11655 V.setInt(D); 11656 break; 11657 } 11658 } 11659 return D; 11660 } 11661 11662 ScalarEvolution::LoopDisposition 11663 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11664 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11665 case scConstant: 11666 return LoopInvariant; 11667 case scTruncate: 11668 case scZeroExtend: 11669 case scSignExtend: 11670 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11671 case scAddRecExpr: { 11672 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11673 11674 // If L is the addrec's loop, it's computable. 11675 if (AR->getLoop() == L) 11676 return LoopComputable; 11677 11678 // Add recurrences are never invariant in the function-body (null loop). 11679 if (!L) 11680 return LoopVariant; 11681 11682 // Everything that is not defined at loop entry is variant. 11683 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11684 return LoopVariant; 11685 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11686 " dominate the contained loop's header?"); 11687 11688 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11689 if (AR->getLoop()->contains(L)) 11690 return LoopInvariant; 11691 11692 // This recurrence is variant w.r.t. L if any of its operands 11693 // are variant. 11694 for (auto *Op : AR->operands()) 11695 if (!isLoopInvariant(Op, L)) 11696 return LoopVariant; 11697 11698 // Otherwise it's loop-invariant. 11699 return LoopInvariant; 11700 } 11701 case scAddExpr: 11702 case scMulExpr: 11703 case scUMaxExpr: 11704 case scSMaxExpr: 11705 case scUMinExpr: 11706 case scSMinExpr: { 11707 bool HasVarying = false; 11708 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11709 LoopDisposition D = getLoopDisposition(Op, L); 11710 if (D == LoopVariant) 11711 return LoopVariant; 11712 if (D == LoopComputable) 11713 HasVarying = true; 11714 } 11715 return HasVarying ? LoopComputable : LoopInvariant; 11716 } 11717 case scUDivExpr: { 11718 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11719 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11720 if (LD == LoopVariant) 11721 return LoopVariant; 11722 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11723 if (RD == LoopVariant) 11724 return LoopVariant; 11725 return (LD == LoopInvariant && RD == LoopInvariant) ? 11726 LoopInvariant : LoopComputable; 11727 } 11728 case scUnknown: 11729 // All non-instruction values are loop invariant. All instructions are loop 11730 // invariant if they are not contained in the specified loop. 11731 // Instructions are never considered invariant in the function body 11732 // (null loop) because they are defined within the "loop". 11733 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11734 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11735 return LoopInvariant; 11736 case scCouldNotCompute: 11737 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11738 } 11739 llvm_unreachable("Unknown SCEV kind!"); 11740 } 11741 11742 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11743 return getLoopDisposition(S, L) == LoopInvariant; 11744 } 11745 11746 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11747 return getLoopDisposition(S, L) == LoopComputable; 11748 } 11749 11750 ScalarEvolution::BlockDisposition 11751 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11752 auto &Values = BlockDispositions[S]; 11753 for (auto &V : Values) { 11754 if (V.getPointer() == BB) 11755 return V.getInt(); 11756 } 11757 Values.emplace_back(BB, DoesNotDominateBlock); 11758 BlockDisposition D = computeBlockDisposition(S, BB); 11759 auto &Values2 = BlockDispositions[S]; 11760 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11761 if (V.getPointer() == BB) { 11762 V.setInt(D); 11763 break; 11764 } 11765 } 11766 return D; 11767 } 11768 11769 ScalarEvolution::BlockDisposition 11770 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11771 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11772 case scConstant: 11773 return ProperlyDominatesBlock; 11774 case scTruncate: 11775 case scZeroExtend: 11776 case scSignExtend: 11777 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11778 case scAddRecExpr: { 11779 // This uses a "dominates" query instead of "properly dominates" query 11780 // to test for proper dominance too, because the instruction which 11781 // produces the addrec's value is a PHI, and a PHI effectively properly 11782 // dominates its entire containing block. 11783 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11784 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11785 return DoesNotDominateBlock; 11786 11787 // Fall through into SCEVNAryExpr handling. 11788 LLVM_FALLTHROUGH; 11789 } 11790 case scAddExpr: 11791 case scMulExpr: 11792 case scUMaxExpr: 11793 case scSMaxExpr: 11794 case scUMinExpr: 11795 case scSMinExpr: { 11796 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11797 bool Proper = true; 11798 for (const SCEV *NAryOp : NAry->operands()) { 11799 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11800 if (D == DoesNotDominateBlock) 11801 return DoesNotDominateBlock; 11802 if (D == DominatesBlock) 11803 Proper = false; 11804 } 11805 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11806 } 11807 case scUDivExpr: { 11808 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11809 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11810 BlockDisposition LD = getBlockDisposition(LHS, BB); 11811 if (LD == DoesNotDominateBlock) 11812 return DoesNotDominateBlock; 11813 BlockDisposition RD = getBlockDisposition(RHS, BB); 11814 if (RD == DoesNotDominateBlock) 11815 return DoesNotDominateBlock; 11816 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11817 ProperlyDominatesBlock : DominatesBlock; 11818 } 11819 case scUnknown: 11820 if (Instruction *I = 11821 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11822 if (I->getParent() == BB) 11823 return DominatesBlock; 11824 if (DT.properlyDominates(I->getParent(), BB)) 11825 return ProperlyDominatesBlock; 11826 return DoesNotDominateBlock; 11827 } 11828 return ProperlyDominatesBlock; 11829 case scCouldNotCompute: 11830 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11831 } 11832 llvm_unreachable("Unknown SCEV kind!"); 11833 } 11834 11835 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11836 return getBlockDisposition(S, BB) >= DominatesBlock; 11837 } 11838 11839 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11840 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11841 } 11842 11843 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11844 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11845 } 11846 11847 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11848 auto IsS = [&](const SCEV *X) { return S == X; }; 11849 auto ContainsS = [&](const SCEV *X) { 11850 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11851 }; 11852 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11853 } 11854 11855 void 11856 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11857 ValuesAtScopes.erase(S); 11858 LoopDispositions.erase(S); 11859 BlockDispositions.erase(S); 11860 UnsignedRanges.erase(S); 11861 SignedRanges.erase(S); 11862 ExprValueMap.erase(S); 11863 HasRecMap.erase(S); 11864 MinTrailingZerosCache.erase(S); 11865 11866 for (auto I = PredicatedSCEVRewrites.begin(); 11867 I != PredicatedSCEVRewrites.end();) { 11868 std::pair<const SCEV *, const Loop *> Entry = I->first; 11869 if (Entry.first == S) 11870 PredicatedSCEVRewrites.erase(I++); 11871 else 11872 ++I; 11873 } 11874 11875 auto RemoveSCEVFromBackedgeMap = 11876 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11877 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11878 BackedgeTakenInfo &BEInfo = I->second; 11879 if (BEInfo.hasOperand(S, this)) { 11880 BEInfo.clear(); 11881 Map.erase(I++); 11882 } else 11883 ++I; 11884 } 11885 }; 11886 11887 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11888 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11889 } 11890 11891 void 11892 ScalarEvolution::getUsedLoops(const SCEV *S, 11893 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11894 struct FindUsedLoops { 11895 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11896 : LoopsUsed(LoopsUsed) {} 11897 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11898 bool follow(const SCEV *S) { 11899 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11900 LoopsUsed.insert(AR->getLoop()); 11901 return true; 11902 } 11903 11904 bool isDone() const { return false; } 11905 }; 11906 11907 FindUsedLoops F(LoopsUsed); 11908 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11909 } 11910 11911 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11912 SmallPtrSet<const Loop *, 8> LoopsUsed; 11913 getUsedLoops(S, LoopsUsed); 11914 for (auto *L : LoopsUsed) 11915 LoopUsers[L].push_back(S); 11916 } 11917 11918 void ScalarEvolution::verify() const { 11919 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11920 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11921 11922 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11923 11924 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11925 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11926 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11927 11928 const SCEV *visitConstant(const SCEVConstant *Constant) { 11929 return SE.getConstant(Constant->getAPInt()); 11930 } 11931 11932 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11933 return SE.getUnknown(Expr->getValue()); 11934 } 11935 11936 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11937 return SE.getCouldNotCompute(); 11938 } 11939 }; 11940 11941 SCEVMapper SCM(SE2); 11942 11943 while (!LoopStack.empty()) { 11944 auto *L = LoopStack.pop_back_val(); 11945 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11946 11947 auto *CurBECount = SCM.visit( 11948 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11949 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11950 11951 if (CurBECount == SE2.getCouldNotCompute() || 11952 NewBECount == SE2.getCouldNotCompute()) { 11953 // NB! This situation is legal, but is very suspicious -- whatever pass 11954 // change the loop to make a trip count go from could not compute to 11955 // computable or vice-versa *should have* invalidated SCEV. However, we 11956 // choose not to assert here (for now) since we don't want false 11957 // positives. 11958 continue; 11959 } 11960 11961 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11962 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11963 // not propagate undef aggressively). This means we can (and do) fail 11964 // verification in cases where a transform makes the trip count of a loop 11965 // go from "undef" to "undef+1" (say). The transform is fine, since in 11966 // both cases the loop iterates "undef" times, but SCEV thinks we 11967 // increased the trip count of the loop by 1 incorrectly. 11968 continue; 11969 } 11970 11971 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11972 SE.getTypeSizeInBits(NewBECount->getType())) 11973 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11974 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11975 SE.getTypeSizeInBits(NewBECount->getType())) 11976 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11977 11978 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 11979 11980 // Unless VerifySCEVStrict is set, we only compare constant deltas. 11981 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 11982 dbgs() << "Trip Count for " << *L << " Changed!\n"; 11983 dbgs() << "Old: " << *CurBECount << "\n"; 11984 dbgs() << "New: " << *NewBECount << "\n"; 11985 dbgs() << "Delta: " << *Delta << "\n"; 11986 std::abort(); 11987 } 11988 } 11989 } 11990 11991 bool ScalarEvolution::invalidate( 11992 Function &F, const PreservedAnalyses &PA, 11993 FunctionAnalysisManager::Invalidator &Inv) { 11994 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11995 // of its dependencies is invalidated. 11996 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11997 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11998 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11999 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12000 Inv.invalidate<LoopAnalysis>(F, PA); 12001 } 12002 12003 AnalysisKey ScalarEvolutionAnalysis::Key; 12004 12005 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12006 FunctionAnalysisManager &AM) { 12007 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12008 AM.getResult<AssumptionAnalysis>(F), 12009 AM.getResult<DominatorTreeAnalysis>(F), 12010 AM.getResult<LoopAnalysis>(F)); 12011 } 12012 12013 PreservedAnalyses 12014 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12015 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12016 return PreservedAnalyses::all(); 12017 } 12018 12019 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12020 "Scalar Evolution Analysis", false, true) 12021 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12022 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12023 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12024 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12025 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12026 "Scalar Evolution Analysis", false, true) 12027 12028 char ScalarEvolutionWrapperPass::ID = 0; 12029 12030 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12031 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12032 } 12033 12034 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12035 SE.reset(new ScalarEvolution( 12036 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12037 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12038 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12039 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12040 return false; 12041 } 12042 12043 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12044 12045 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12046 SE->print(OS); 12047 } 12048 12049 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12050 if (!VerifySCEV) 12051 return; 12052 12053 SE->verify(); 12054 } 12055 12056 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12057 AU.setPreservesAll(); 12058 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12059 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12060 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12061 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12062 } 12063 12064 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12065 const SCEV *RHS) { 12066 FoldingSetNodeID ID; 12067 assert(LHS->getType() == RHS->getType() && 12068 "Type mismatch between LHS and RHS"); 12069 // Unique this node based on the arguments 12070 ID.AddInteger(SCEVPredicate::P_Equal); 12071 ID.AddPointer(LHS); 12072 ID.AddPointer(RHS); 12073 void *IP = nullptr; 12074 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12075 return S; 12076 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12077 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12078 UniquePreds.InsertNode(Eq, IP); 12079 return Eq; 12080 } 12081 12082 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12083 const SCEVAddRecExpr *AR, 12084 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12085 FoldingSetNodeID ID; 12086 // Unique this node based on the arguments 12087 ID.AddInteger(SCEVPredicate::P_Wrap); 12088 ID.AddPointer(AR); 12089 ID.AddInteger(AddedFlags); 12090 void *IP = nullptr; 12091 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12092 return S; 12093 auto *OF = new (SCEVAllocator) 12094 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12095 UniquePreds.InsertNode(OF, IP); 12096 return OF; 12097 } 12098 12099 namespace { 12100 12101 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12102 public: 12103 12104 /// Rewrites \p S in the context of a loop L and the SCEV predication 12105 /// infrastructure. 12106 /// 12107 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12108 /// equivalences present in \p Pred. 12109 /// 12110 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12111 /// \p NewPreds such that the result will be an AddRecExpr. 12112 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12113 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12114 SCEVUnionPredicate *Pred) { 12115 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12116 return Rewriter.visit(S); 12117 } 12118 12119 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12120 if (Pred) { 12121 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12122 for (auto *Pred : ExprPreds) 12123 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12124 if (IPred->getLHS() == Expr) 12125 return IPred->getRHS(); 12126 } 12127 return convertToAddRecWithPreds(Expr); 12128 } 12129 12130 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12131 const SCEV *Operand = visit(Expr->getOperand()); 12132 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12133 if (AR && AR->getLoop() == L && AR->isAffine()) { 12134 // This couldn't be folded because the operand didn't have the nuw 12135 // flag. Add the nusw flag as an assumption that we could make. 12136 const SCEV *Step = AR->getStepRecurrence(SE); 12137 Type *Ty = Expr->getType(); 12138 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12139 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12140 SE.getSignExtendExpr(Step, Ty), L, 12141 AR->getNoWrapFlags()); 12142 } 12143 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12144 } 12145 12146 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12147 const SCEV *Operand = visit(Expr->getOperand()); 12148 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12149 if (AR && AR->getLoop() == L && AR->isAffine()) { 12150 // This couldn't be folded because the operand didn't have the nsw 12151 // flag. Add the nssw flag as an assumption that we could make. 12152 const SCEV *Step = AR->getStepRecurrence(SE); 12153 Type *Ty = Expr->getType(); 12154 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12155 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12156 SE.getSignExtendExpr(Step, Ty), L, 12157 AR->getNoWrapFlags()); 12158 } 12159 return SE.getSignExtendExpr(Operand, Expr->getType()); 12160 } 12161 12162 private: 12163 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12164 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12165 SCEVUnionPredicate *Pred) 12166 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12167 12168 bool addOverflowAssumption(const SCEVPredicate *P) { 12169 if (!NewPreds) { 12170 // Check if we've already made this assumption. 12171 return Pred && Pred->implies(P); 12172 } 12173 NewPreds->insert(P); 12174 return true; 12175 } 12176 12177 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12178 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12179 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12180 return addOverflowAssumption(A); 12181 } 12182 12183 // If \p Expr represents a PHINode, we try to see if it can be represented 12184 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12185 // to add this predicate as a runtime overflow check, we return the AddRec. 12186 // If \p Expr does not meet these conditions (is not a PHI node, or we 12187 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12188 // return \p Expr. 12189 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12190 if (!isa<PHINode>(Expr->getValue())) 12191 return Expr; 12192 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12193 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12194 if (!PredicatedRewrite) 12195 return Expr; 12196 for (auto *P : PredicatedRewrite->second){ 12197 // Wrap predicates from outer loops are not supported. 12198 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12199 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12200 if (L != AR->getLoop()) 12201 return Expr; 12202 } 12203 if (!addOverflowAssumption(P)) 12204 return Expr; 12205 } 12206 return PredicatedRewrite->first; 12207 } 12208 12209 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12210 SCEVUnionPredicate *Pred; 12211 const Loop *L; 12212 }; 12213 12214 } // end anonymous namespace 12215 12216 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12217 SCEVUnionPredicate &Preds) { 12218 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12219 } 12220 12221 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12222 const SCEV *S, const Loop *L, 12223 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12224 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12225 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12226 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12227 12228 if (!AddRec) 12229 return nullptr; 12230 12231 // Since the transformation was successful, we can now transfer the SCEV 12232 // predicates. 12233 for (auto *P : TransformPreds) 12234 Preds.insert(P); 12235 12236 return AddRec; 12237 } 12238 12239 /// SCEV predicates 12240 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12241 SCEVPredicateKind Kind) 12242 : FastID(ID), Kind(Kind) {} 12243 12244 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12245 const SCEV *LHS, const SCEV *RHS) 12246 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12247 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12248 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12249 } 12250 12251 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12252 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12253 12254 if (!Op) 12255 return false; 12256 12257 return Op->LHS == LHS && Op->RHS == RHS; 12258 } 12259 12260 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12261 12262 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12263 12264 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12265 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12266 } 12267 12268 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12269 const SCEVAddRecExpr *AR, 12270 IncrementWrapFlags Flags) 12271 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12272 12273 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12274 12275 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12276 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12277 12278 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12279 } 12280 12281 bool SCEVWrapPredicate::isAlwaysTrue() const { 12282 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12283 IncrementWrapFlags IFlags = Flags; 12284 12285 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12286 IFlags = clearFlags(IFlags, IncrementNSSW); 12287 12288 return IFlags == IncrementAnyWrap; 12289 } 12290 12291 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12292 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12293 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12294 OS << "<nusw>"; 12295 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12296 OS << "<nssw>"; 12297 OS << "\n"; 12298 } 12299 12300 SCEVWrapPredicate::IncrementWrapFlags 12301 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12302 ScalarEvolution &SE) { 12303 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12304 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12305 12306 // We can safely transfer the NSW flag as NSSW. 12307 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12308 ImpliedFlags = IncrementNSSW; 12309 12310 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12311 // If the increment is positive, the SCEV NUW flag will also imply the 12312 // WrapPredicate NUSW flag. 12313 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12314 if (Step->getValue()->getValue().isNonNegative()) 12315 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12316 } 12317 12318 return ImpliedFlags; 12319 } 12320 12321 /// Union predicates don't get cached so create a dummy set ID for it. 12322 SCEVUnionPredicate::SCEVUnionPredicate() 12323 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12324 12325 bool SCEVUnionPredicate::isAlwaysTrue() const { 12326 return all_of(Preds, 12327 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12328 } 12329 12330 ArrayRef<const SCEVPredicate *> 12331 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12332 auto I = SCEVToPreds.find(Expr); 12333 if (I == SCEVToPreds.end()) 12334 return ArrayRef<const SCEVPredicate *>(); 12335 return I->second; 12336 } 12337 12338 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12339 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12340 return all_of(Set->Preds, 12341 [this](const SCEVPredicate *I) { return this->implies(I); }); 12342 12343 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12344 if (ScevPredsIt == SCEVToPreds.end()) 12345 return false; 12346 auto &SCEVPreds = ScevPredsIt->second; 12347 12348 return any_of(SCEVPreds, 12349 [N](const SCEVPredicate *I) { return I->implies(N); }); 12350 } 12351 12352 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12353 12354 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12355 for (auto Pred : Preds) 12356 Pred->print(OS, Depth); 12357 } 12358 12359 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12360 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12361 for (auto Pred : Set->Preds) 12362 add(Pred); 12363 return; 12364 } 12365 12366 if (implies(N)) 12367 return; 12368 12369 const SCEV *Key = N->getExpr(); 12370 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12371 " associated expression!"); 12372 12373 SCEVToPreds[Key].push_back(N); 12374 Preds.push_back(N); 12375 } 12376 12377 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12378 Loop &L) 12379 : SE(SE), L(L) {} 12380 12381 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12382 const SCEV *Expr = SE.getSCEV(V); 12383 RewriteEntry &Entry = RewriteMap[Expr]; 12384 12385 // If we already have an entry and the version matches, return it. 12386 if (Entry.second && Generation == Entry.first) 12387 return Entry.second; 12388 12389 // We found an entry but it's stale. Rewrite the stale entry 12390 // according to the current predicate. 12391 if (Entry.second) 12392 Expr = Entry.second; 12393 12394 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12395 Entry = {Generation, NewSCEV}; 12396 12397 return NewSCEV; 12398 } 12399 12400 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12401 if (!BackedgeCount) { 12402 SCEVUnionPredicate BackedgePred; 12403 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12404 addPredicate(BackedgePred); 12405 } 12406 return BackedgeCount; 12407 } 12408 12409 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12410 if (Preds.implies(&Pred)) 12411 return; 12412 Preds.add(&Pred); 12413 updateGeneration(); 12414 } 12415 12416 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12417 return Preds; 12418 } 12419 12420 void PredicatedScalarEvolution::updateGeneration() { 12421 // If the generation number wrapped recompute everything. 12422 if (++Generation == 0) { 12423 for (auto &II : RewriteMap) { 12424 const SCEV *Rewritten = II.second.second; 12425 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12426 } 12427 } 12428 } 12429 12430 void PredicatedScalarEvolution::setNoOverflow( 12431 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12432 const SCEV *Expr = getSCEV(V); 12433 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12434 12435 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12436 12437 // Clear the statically implied flags. 12438 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12439 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12440 12441 auto II = FlagsMap.insert({V, Flags}); 12442 if (!II.second) 12443 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12444 } 12445 12446 bool PredicatedScalarEvolution::hasNoOverflow( 12447 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12448 const SCEV *Expr = getSCEV(V); 12449 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12450 12451 Flags = SCEVWrapPredicate::clearFlags( 12452 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12453 12454 auto II = FlagsMap.find(V); 12455 12456 if (II != FlagsMap.end()) 12457 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12458 12459 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12460 } 12461 12462 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12463 const SCEV *Expr = this->getSCEV(V); 12464 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12465 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12466 12467 if (!New) 12468 return nullptr; 12469 12470 for (auto *P : NewPreds) 12471 Preds.add(P); 12472 12473 updateGeneration(); 12474 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12475 return New; 12476 } 12477 12478 PredicatedScalarEvolution::PredicatedScalarEvolution( 12479 const PredicatedScalarEvolution &Init) 12480 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12481 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12482 for (const auto &I : Init.FlagsMap) 12483 FlagsMap.insert(I); 12484 } 12485 12486 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12487 // For each block. 12488 for (auto *BB : L.getBlocks()) 12489 for (auto &I : *BB) { 12490 if (!SE.isSCEVable(I.getType())) 12491 continue; 12492 12493 auto *Expr = SE.getSCEV(&I); 12494 auto II = RewriteMap.find(Expr); 12495 12496 if (II == RewriteMap.end()) 12497 continue; 12498 12499 // Don't print things that are not interesting. 12500 if (II->second.second == Expr) 12501 continue; 12502 12503 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12504 OS.indent(Depth + 2) << *Expr << "\n"; 12505 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12506 } 12507 } 12508 12509 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12510 // arbitrary expressions. 12511 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12512 // 4, A / B becomes X / 8). 12513 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12514 const SCEV *&RHS) { 12515 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12516 if (Add == nullptr || Add->getNumOperands() != 2) 12517 return false; 12518 12519 const SCEV *A = Add->getOperand(1); 12520 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12521 12522 if (Mul == nullptr) 12523 return false; 12524 12525 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12526 // (SomeExpr + (-(SomeExpr / B) * B)). 12527 if (Expr == getURemExpr(A, B)) { 12528 LHS = A; 12529 RHS = B; 12530 return true; 12531 } 12532 return false; 12533 }; 12534 12535 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12536 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12537 return MatchURemWithDivisor(Mul->getOperand(1)) || 12538 MatchURemWithDivisor(Mul->getOperand(2)); 12539 12540 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12541 if (Mul->getNumOperands() == 2) 12542 return MatchURemWithDivisor(Mul->getOperand(1)) || 12543 MatchURemWithDivisor(Mul->getOperand(0)) || 12544 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12545 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12546 return false; 12547 } 12548