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> 162 VerifySCEVMap("verify-scev-maps", cl::Hidden, 163 cl::desc("Verify no dangling value in ScalarEvolution's " 164 "ExprValueMap (slow)")); 165 166 static cl::opt<bool> VerifyIR( 167 "scev-verify-ir", cl::Hidden, 168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 169 cl::init(false)); 170 171 static cl::opt<unsigned> MulOpsInlineThreshold( 172 "scev-mulops-inline-threshold", cl::Hidden, 173 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 174 cl::init(32)); 175 176 static cl::opt<unsigned> AddOpsInlineThreshold( 177 "scev-addops-inline-threshold", cl::Hidden, 178 cl::desc("Threshold for inlining addition operands into a SCEV"), 179 cl::init(500)); 180 181 static cl::opt<unsigned> MaxSCEVCompareDepth( 182 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 184 cl::init(32)); 185 186 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 187 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 188 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 189 cl::init(2)); 190 191 static cl::opt<unsigned> MaxValueCompareDepth( 192 "scalar-evolution-max-value-compare-depth", cl::Hidden, 193 cl::desc("Maximum depth of recursive value complexity comparisons"), 194 cl::init(2)); 195 196 static cl::opt<unsigned> 197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 198 cl::desc("Maximum depth of recursive arithmetics"), 199 cl::init(32)); 200 201 static cl::opt<unsigned> MaxConstantEvolvingDepth( 202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 204 205 static cl::opt<unsigned> 206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 208 cl::init(8)); 209 210 static cl::opt<unsigned> 211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 212 cl::desc("Max coefficients in AddRec during evolving"), 213 cl::init(8)); 214 215 static cl::opt<unsigned> 216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 217 cl::desc("Size of the expression which is considered huge"), 218 cl::init(4096)); 219 220 //===----------------------------------------------------------------------===// 221 // SCEV class definitions 222 //===----------------------------------------------------------------------===// 223 224 //===----------------------------------------------------------------------===// 225 // Implementation of the SCEV class. 226 // 227 228 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 229 LLVM_DUMP_METHOD void SCEV::dump() const { 230 print(dbgs()); 231 dbgs() << '\n'; 232 } 233 #endif 234 235 void SCEV::print(raw_ostream &OS) const { 236 switch (static_cast<SCEVTypes>(getSCEVType())) { 237 case scConstant: 238 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 239 return; 240 case scTruncate: { 241 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 242 const SCEV *Op = Trunc->getOperand(); 243 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 244 << *Trunc->getType() << ")"; 245 return; 246 } 247 case scZeroExtend: { 248 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 249 const SCEV *Op = ZExt->getOperand(); 250 OS << "(zext " << *Op->getType() << " " << *Op << " to " 251 << *ZExt->getType() << ")"; 252 return; 253 } 254 case scSignExtend: { 255 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 256 const SCEV *Op = SExt->getOperand(); 257 OS << "(sext " << *Op->getType() << " " << *Op << " to " 258 << *SExt->getType() << ")"; 259 return; 260 } 261 case scAddRecExpr: { 262 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 263 OS << "{" << *AR->getOperand(0); 264 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 265 OS << ",+," << *AR->getOperand(i); 266 OS << "}<"; 267 if (AR->hasNoUnsignedWrap()) 268 OS << "nuw><"; 269 if (AR->hasNoSignedWrap()) 270 OS << "nsw><"; 271 if (AR->hasNoSelfWrap() && 272 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 273 OS << "nw><"; 274 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 275 OS << ">"; 276 return; 277 } 278 case scAddExpr: 279 case scMulExpr: 280 case scUMaxExpr: 281 case scSMaxExpr: 282 case scUMinExpr: 283 case scSMinExpr: { 284 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 285 const char *OpStr = nullptr; 286 switch (NAry->getSCEVType()) { 287 case scAddExpr: OpStr = " + "; break; 288 case scMulExpr: OpStr = " * "; break; 289 case scUMaxExpr: OpStr = " umax "; break; 290 case scSMaxExpr: OpStr = " smax "; break; 291 case scUMinExpr: 292 OpStr = " umin "; 293 break; 294 case scSMinExpr: 295 OpStr = " smin "; 296 break; 297 } 298 OS << "("; 299 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 300 I != E; ++I) { 301 OS << **I; 302 if (std::next(I) != E) 303 OS << OpStr; 304 } 305 OS << ")"; 306 switch (NAry->getSCEVType()) { 307 case scAddExpr: 308 case scMulExpr: 309 if (NAry->hasNoUnsignedWrap()) 310 OS << "<nuw>"; 311 if (NAry->hasNoSignedWrap()) 312 OS << "<nsw>"; 313 } 314 return; 315 } 316 case scUDivExpr: { 317 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 318 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 319 return; 320 } 321 case scUnknown: { 322 const SCEVUnknown *U = cast<SCEVUnknown>(this); 323 Type *AllocTy; 324 if (U->isSizeOf(AllocTy)) { 325 OS << "sizeof(" << *AllocTy << ")"; 326 return; 327 } 328 if (U->isAlignOf(AllocTy)) { 329 OS << "alignof(" << *AllocTy << ")"; 330 return; 331 } 332 333 Type *CTy; 334 Constant *FieldNo; 335 if (U->isOffsetOf(CTy, FieldNo)) { 336 OS << "offsetof(" << *CTy << ", "; 337 FieldNo->printAsOperand(OS, false); 338 OS << ")"; 339 return; 340 } 341 342 // Otherwise just print it normally. 343 U->getValue()->printAsOperand(OS, false); 344 return; 345 } 346 case scCouldNotCompute: 347 OS << "***COULDNOTCOMPUTE***"; 348 return; 349 } 350 llvm_unreachable("Unknown SCEV kind!"); 351 } 352 353 Type *SCEV::getType() const { 354 switch (static_cast<SCEVTypes>(getSCEVType())) { 355 case scConstant: 356 return cast<SCEVConstant>(this)->getType(); 357 case scTruncate: 358 case scZeroExtend: 359 case scSignExtend: 360 return cast<SCEVCastExpr>(this)->getType(); 361 case scAddRecExpr: 362 case scMulExpr: 363 case scUMaxExpr: 364 case scSMaxExpr: 365 case scUMinExpr: 366 case scSMinExpr: 367 return cast<SCEVNAryExpr>(this)->getType(); 368 case scAddExpr: 369 return cast<SCEVAddExpr>(this)->getType(); 370 case scUDivExpr: 371 return cast<SCEVUDivExpr>(this)->getType(); 372 case scUnknown: 373 return cast<SCEVUnknown>(this)->getType(); 374 case scCouldNotCompute: 375 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 376 } 377 llvm_unreachable("Unknown SCEV kind!"); 378 } 379 380 bool SCEV::isZero() const { 381 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 382 return SC->getValue()->isZero(); 383 return false; 384 } 385 386 bool SCEV::isOne() const { 387 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 388 return SC->getValue()->isOne(); 389 return false; 390 } 391 392 bool SCEV::isAllOnesValue() const { 393 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 394 return SC->getValue()->isMinusOne(); 395 return false; 396 } 397 398 bool SCEV::isNonConstantNegative() const { 399 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 400 if (!Mul) return false; 401 402 // If there is a constant factor, it will be first. 403 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 404 if (!SC) return false; 405 406 // Return true if the value is negative, this matches things like (-42 * V). 407 return SC->getAPInt().isNegative(); 408 } 409 410 SCEVCouldNotCompute::SCEVCouldNotCompute() : 411 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 412 413 bool SCEVCouldNotCompute::classof(const SCEV *S) { 414 return S->getSCEVType() == scCouldNotCompute; 415 } 416 417 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 418 FoldingSetNodeID ID; 419 ID.AddInteger(scConstant); 420 ID.AddPointer(V); 421 void *IP = nullptr; 422 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 423 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 424 UniqueSCEVs.InsertNode(S, IP); 425 return S; 426 } 427 428 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 429 return getConstant(ConstantInt::get(getContext(), Val)); 430 } 431 432 const SCEV * 433 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 434 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 435 return getConstant(ConstantInt::get(ITy, V, isSigned)); 436 } 437 438 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 439 unsigned SCEVTy, const SCEV *op, Type *ty) 440 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 441 442 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 443 const SCEV *op, Type *ty) 444 : SCEVCastExpr(ID, scTruncate, op, ty) { 445 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 446 "Cannot truncate non-integer value!"); 447 } 448 449 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 450 const SCEV *op, Type *ty) 451 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 452 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 453 "Cannot zero extend non-integer value!"); 454 } 455 456 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 457 const SCEV *op, Type *ty) 458 : SCEVCastExpr(ID, scSignExtend, op, ty) { 459 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 460 "Cannot sign extend non-integer value!"); 461 } 462 463 void SCEVUnknown::deleted() { 464 // Clear this SCEVUnknown from various maps. 465 SE->forgetMemoizedResults(this); 466 467 // Remove this SCEVUnknown from the uniquing map. 468 SE->UniqueSCEVs.RemoveNode(this); 469 470 // Release the value. 471 setValPtr(nullptr); 472 } 473 474 void SCEVUnknown::allUsesReplacedWith(Value *New) { 475 // Remove this SCEVUnknown from the uniquing map. 476 SE->UniqueSCEVs.RemoveNode(this); 477 478 // Update this SCEVUnknown to point to the new value. This is needed 479 // because there may still be outstanding SCEVs which still point to 480 // this SCEVUnknown. 481 setValPtr(New); 482 } 483 484 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 485 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 486 if (VCE->getOpcode() == Instruction::PtrToInt) 487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 488 if (CE->getOpcode() == Instruction::GetElementPtr && 489 CE->getOperand(0)->isNullValue() && 490 CE->getNumOperands() == 2) 491 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 492 if (CI->isOne()) { 493 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 494 ->getElementType(); 495 return true; 496 } 497 498 return false; 499 } 500 501 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 502 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 503 if (VCE->getOpcode() == Instruction::PtrToInt) 504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 505 if (CE->getOpcode() == Instruction::GetElementPtr && 506 CE->getOperand(0)->isNullValue()) { 507 Type *Ty = 508 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 509 if (StructType *STy = dyn_cast<StructType>(Ty)) 510 if (!STy->isPacked() && 511 CE->getNumOperands() == 3 && 512 CE->getOperand(1)->isNullValue()) { 513 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 514 if (CI->isOne() && 515 STy->getNumElements() == 2 && 516 STy->getElementType(0)->isIntegerTy(1)) { 517 AllocTy = STy->getElementType(1); 518 return true; 519 } 520 } 521 } 522 523 return false; 524 } 525 526 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 527 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 528 if (VCE->getOpcode() == Instruction::PtrToInt) 529 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 530 if (CE->getOpcode() == Instruction::GetElementPtr && 531 CE->getNumOperands() == 3 && 532 CE->getOperand(0)->isNullValue() && 533 CE->getOperand(1)->isNullValue()) { 534 Type *Ty = 535 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 536 // Ignore vector types here so that ScalarEvolutionExpander doesn't 537 // emit getelementptrs that index into vectors. 538 if (Ty->isStructTy() || Ty->isArrayTy()) { 539 CTy = Ty; 540 FieldNo = CE->getOperand(2); 541 return true; 542 } 543 } 544 545 return false; 546 } 547 548 //===----------------------------------------------------------------------===// 549 // SCEV Utilities 550 //===----------------------------------------------------------------------===// 551 552 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 553 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 554 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 555 /// have been previously deemed to be "equally complex" by this routine. It is 556 /// intended to avoid exponential time complexity in cases like: 557 /// 558 /// %a = f(%x, %y) 559 /// %b = f(%a, %a) 560 /// %c = f(%b, %b) 561 /// 562 /// %d = f(%x, %y) 563 /// %e = f(%d, %d) 564 /// %f = f(%e, %e) 565 /// 566 /// CompareValueComplexity(%f, %c) 567 /// 568 /// Since we do not continue running this routine on expression trees once we 569 /// have seen unequal values, there is no need to track them in the cache. 570 static int 571 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 572 const LoopInfo *const LI, Value *LV, Value *RV, 573 unsigned Depth) { 574 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 575 return 0; 576 577 // Order pointer values after integer values. This helps SCEVExpander form 578 // GEPs. 579 bool LIsPointer = LV->getType()->isPointerTy(), 580 RIsPointer = RV->getType()->isPointerTy(); 581 if (LIsPointer != RIsPointer) 582 return (int)LIsPointer - (int)RIsPointer; 583 584 // Compare getValueID values. 585 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 586 if (LID != RID) 587 return (int)LID - (int)RID; 588 589 // Sort arguments by their position. 590 if (const auto *LA = dyn_cast<Argument>(LV)) { 591 const auto *RA = cast<Argument>(RV); 592 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 593 return (int)LArgNo - (int)RArgNo; 594 } 595 596 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 597 const auto *RGV = cast<GlobalValue>(RV); 598 599 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 600 auto LT = GV->getLinkage(); 601 return !(GlobalValue::isPrivateLinkage(LT) || 602 GlobalValue::isInternalLinkage(LT)); 603 }; 604 605 // Use the names to distinguish the two values, but only if the 606 // names are semantically important. 607 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 608 return LGV->getName().compare(RGV->getName()); 609 } 610 611 // For instructions, compare their loop depth, and their operand count. This 612 // is pretty loose. 613 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 614 const auto *RInst = cast<Instruction>(RV); 615 616 // Compare loop depths. 617 const BasicBlock *LParent = LInst->getParent(), 618 *RParent = RInst->getParent(); 619 if (LParent != RParent) { 620 unsigned LDepth = LI->getLoopDepth(LParent), 621 RDepth = LI->getLoopDepth(RParent); 622 if (LDepth != RDepth) 623 return (int)LDepth - (int)RDepth; 624 } 625 626 // Compare the number of operands. 627 unsigned LNumOps = LInst->getNumOperands(), 628 RNumOps = RInst->getNumOperands(); 629 if (LNumOps != RNumOps) 630 return (int)LNumOps - (int)RNumOps; 631 632 for (unsigned Idx : seq(0u, LNumOps)) { 633 int Result = 634 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 635 RInst->getOperand(Idx), Depth + 1); 636 if (Result != 0) 637 return Result; 638 } 639 } 640 641 EqCacheValue.unionSets(LV, RV); 642 return 0; 643 } 644 645 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 646 // than RHS, respectively. A three-way result allows recursive comparisons to be 647 // more efficient. 648 static int CompareSCEVComplexity( 649 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 650 EquivalenceClasses<const Value *> &EqCacheValue, 651 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 652 DominatorTree &DT, unsigned Depth = 0) { 653 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 654 if (LHS == RHS) 655 return 0; 656 657 // Primarily, sort the SCEVs by their getSCEVType(). 658 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 659 if (LType != RType) 660 return (int)LType - (int)RType; 661 662 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 663 return 0; 664 // Aside from the getSCEVType() ordering, the particular ordering 665 // isn't very important except that it's beneficial to be consistent, 666 // so that (a + b) and (b + a) don't end up as different expressions. 667 switch (static_cast<SCEVTypes>(LType)) { 668 case scUnknown: { 669 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 670 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 671 672 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 673 RU->getValue(), Depth + 1); 674 if (X == 0) 675 EqCacheSCEV.unionSets(LHS, RHS); 676 return X; 677 } 678 679 case scConstant: { 680 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 681 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 682 683 // Compare constant values. 684 const APInt &LA = LC->getAPInt(); 685 const APInt &RA = RC->getAPInt(); 686 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 687 if (LBitWidth != RBitWidth) 688 return (int)LBitWidth - (int)RBitWidth; 689 return LA.ult(RA) ? -1 : 1; 690 } 691 692 case scAddRecExpr: { 693 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 694 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 695 696 // There is always a dominance between two recs that are used by one SCEV, 697 // so we can safely sort recs by loop header dominance. We require such 698 // order in getAddExpr. 699 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 700 if (LLoop != RLoop) { 701 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 702 assert(LHead != RHead && "Two loops share the same header?"); 703 if (DT.dominates(LHead, RHead)) 704 return 1; 705 else 706 assert(DT.dominates(RHead, LHead) && 707 "No dominance between recurrences used by one SCEV?"); 708 return -1; 709 } 710 711 // Addrec complexity grows with operand count. 712 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 713 if (LNumOps != RNumOps) 714 return (int)LNumOps - (int)RNumOps; 715 716 // Lexicographically compare. 717 for (unsigned i = 0; i != LNumOps; ++i) { 718 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 719 LA->getOperand(i), RA->getOperand(i), DT, 720 Depth + 1); 721 if (X != 0) 722 return X; 723 } 724 EqCacheSCEV.unionSets(LHS, RHS); 725 return 0; 726 } 727 728 case scAddExpr: 729 case scMulExpr: 730 case scSMaxExpr: 731 case scUMaxExpr: 732 case scSMinExpr: 733 case scUMinExpr: { 734 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 735 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 736 737 // Lexicographically compare n-ary expressions. 738 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 739 if (LNumOps != RNumOps) 740 return (int)LNumOps - (int)RNumOps; 741 742 for (unsigned i = 0; i != LNumOps; ++i) { 743 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 744 LC->getOperand(i), RC->getOperand(i), DT, 745 Depth + 1); 746 if (X != 0) 747 return X; 748 } 749 EqCacheSCEV.unionSets(LHS, RHS); 750 return 0; 751 } 752 753 case scUDivExpr: { 754 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 755 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 756 757 // Lexicographically compare udiv expressions. 758 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 759 RC->getLHS(), DT, Depth + 1); 760 if (X != 0) 761 return X; 762 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 763 RC->getRHS(), DT, Depth + 1); 764 if (X == 0) 765 EqCacheSCEV.unionSets(LHS, RHS); 766 return X; 767 } 768 769 case scTruncate: 770 case scZeroExtend: 771 case scSignExtend: { 772 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 773 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 774 775 // Compare cast expressions by operand. 776 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 777 LC->getOperand(), RC->getOperand(), DT, 778 Depth + 1); 779 if (X == 0) 780 EqCacheSCEV.unionSets(LHS, RHS); 781 return X; 782 } 783 784 case scCouldNotCompute: 785 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 786 } 787 llvm_unreachable("Unknown SCEV kind!"); 788 } 789 790 /// Given a list of SCEV objects, order them by their complexity, and group 791 /// objects of the same complexity together by value. When this routine is 792 /// finished, we know that any duplicates in the vector are consecutive and that 793 /// complexity is monotonically increasing. 794 /// 795 /// Note that we go take special precautions to ensure that we get deterministic 796 /// results from this routine. In other words, we don't want the results of 797 /// this to depend on where the addresses of various SCEV objects happened to 798 /// land in memory. 799 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 800 LoopInfo *LI, DominatorTree &DT) { 801 if (Ops.size() < 2) return; // Noop 802 803 EquivalenceClasses<const SCEV *> EqCacheSCEV; 804 EquivalenceClasses<const Value *> EqCacheValue; 805 if (Ops.size() == 2) { 806 // This is the common case, which also happens to be trivially simple. 807 // Special case it. 808 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 809 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 810 std::swap(LHS, RHS); 811 return; 812 } 813 814 // Do the rough sort by complexity. 815 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 816 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 817 0; 818 }); 819 820 // Now that we are sorted by complexity, group elements of the same 821 // complexity. Note that this is, at worst, N^2, but the vector is likely to 822 // be extremely short in practice. Note that we take this approach because we 823 // do not want to depend on the addresses of the objects we are grouping. 824 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 825 const SCEV *S = Ops[i]; 826 unsigned Complexity = S->getSCEVType(); 827 828 // If there are any objects of the same complexity and same value as this 829 // one, group them. 830 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 831 if (Ops[j] == S) { // Found a duplicate. 832 // Move it to immediately after i'th element. 833 std::swap(Ops[i+1], Ops[j]); 834 ++i; // no need to rescan it. 835 if (i == e-2) return; // Done! 836 } 837 } 838 } 839 } 840 841 // Returns the size of the SCEV S. 842 static inline int sizeOfSCEV(const SCEV *S) { 843 struct FindSCEVSize { 844 int Size = 0; 845 846 FindSCEVSize() = default; 847 848 bool follow(const SCEV *S) { 849 ++Size; 850 // Keep looking at all operands of S. 851 return true; 852 } 853 854 bool isDone() const { 855 return false; 856 } 857 }; 858 859 FindSCEVSize F; 860 SCEVTraversal<FindSCEVSize> ST(F); 861 ST.visitAll(S); 862 return F.Size; 863 } 864 865 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 866 /// nodes. 867 static bool isHugeExpression(const SCEV *S) { 868 return S->getExpressionSize() >= HugeExprThreshold; 869 } 870 871 /// Returns true of \p Ops contains a huge SCEV (see definition above). 872 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 873 return any_of(Ops, isHugeExpression); 874 } 875 876 namespace { 877 878 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 879 public: 880 // Computes the Quotient and Remainder of the division of Numerator by 881 // Denominator. 882 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 883 const SCEV *Denominator, const SCEV **Quotient, 884 const SCEV **Remainder) { 885 assert(Numerator && Denominator && "Uninitialized SCEV"); 886 887 SCEVDivision D(SE, Numerator, Denominator); 888 889 // Check for the trivial case here to avoid having to check for it in the 890 // rest of the code. 891 if (Numerator == Denominator) { 892 *Quotient = D.One; 893 *Remainder = D.Zero; 894 return; 895 } 896 897 if (Numerator->isZero()) { 898 *Quotient = D.Zero; 899 *Remainder = D.Zero; 900 return; 901 } 902 903 // A simple case when N/1. The quotient is N. 904 if (Denominator->isOne()) { 905 *Quotient = Numerator; 906 *Remainder = D.Zero; 907 return; 908 } 909 910 // Split the Denominator when it is a product. 911 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 912 const SCEV *Q, *R; 913 *Quotient = Numerator; 914 for (const SCEV *Op : T->operands()) { 915 divide(SE, *Quotient, Op, &Q, &R); 916 *Quotient = Q; 917 918 // Bail out when the Numerator is not divisible by one of the terms of 919 // the Denominator. 920 if (!R->isZero()) { 921 *Quotient = D.Zero; 922 *Remainder = Numerator; 923 return; 924 } 925 } 926 *Remainder = D.Zero; 927 return; 928 } 929 930 D.visit(Numerator); 931 *Quotient = D.Quotient; 932 *Remainder = D.Remainder; 933 } 934 935 // Except in the trivial case described above, we do not know how to divide 936 // Expr by Denominator for the following functions with empty implementation. 937 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 938 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 939 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 940 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 941 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 942 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 943 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 944 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 945 void visitUnknown(const SCEVUnknown *Numerator) {} 946 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 947 948 void visitConstant(const SCEVConstant *Numerator) { 949 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 950 APInt NumeratorVal = Numerator->getAPInt(); 951 APInt DenominatorVal = D->getAPInt(); 952 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 953 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 954 955 if (NumeratorBW > DenominatorBW) 956 DenominatorVal = DenominatorVal.sext(NumeratorBW); 957 else if (NumeratorBW < DenominatorBW) 958 NumeratorVal = NumeratorVal.sext(DenominatorBW); 959 960 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 961 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 962 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 963 Quotient = SE.getConstant(QuotientVal); 964 Remainder = SE.getConstant(RemainderVal); 965 return; 966 } 967 } 968 969 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 970 const SCEV *StartQ, *StartR, *StepQ, *StepR; 971 if (!Numerator->isAffine()) 972 return cannotDivide(Numerator); 973 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 974 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 975 // Bail out if the types do not match. 976 Type *Ty = Denominator->getType(); 977 if (Ty != StartQ->getType() || Ty != StartR->getType() || 978 Ty != StepQ->getType() || Ty != StepR->getType()) 979 return cannotDivide(Numerator); 980 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 981 Numerator->getNoWrapFlags()); 982 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 983 Numerator->getNoWrapFlags()); 984 } 985 986 void visitAddExpr(const SCEVAddExpr *Numerator) { 987 SmallVector<const SCEV *, 2> Qs, Rs; 988 Type *Ty = Denominator->getType(); 989 990 for (const SCEV *Op : Numerator->operands()) { 991 const SCEV *Q, *R; 992 divide(SE, Op, Denominator, &Q, &R); 993 994 // Bail out if types do not match. 995 if (Ty != Q->getType() || Ty != R->getType()) 996 return cannotDivide(Numerator); 997 998 Qs.push_back(Q); 999 Rs.push_back(R); 1000 } 1001 1002 if (Qs.size() == 1) { 1003 Quotient = Qs[0]; 1004 Remainder = Rs[0]; 1005 return; 1006 } 1007 1008 Quotient = SE.getAddExpr(Qs); 1009 Remainder = SE.getAddExpr(Rs); 1010 } 1011 1012 void visitMulExpr(const SCEVMulExpr *Numerator) { 1013 SmallVector<const SCEV *, 2> Qs; 1014 Type *Ty = Denominator->getType(); 1015 1016 bool FoundDenominatorTerm = false; 1017 for (const SCEV *Op : Numerator->operands()) { 1018 // Bail out if types do not match. 1019 if (Ty != Op->getType()) 1020 return cannotDivide(Numerator); 1021 1022 if (FoundDenominatorTerm) { 1023 Qs.push_back(Op); 1024 continue; 1025 } 1026 1027 // Check whether Denominator divides one of the product operands. 1028 const SCEV *Q, *R; 1029 divide(SE, Op, Denominator, &Q, &R); 1030 if (!R->isZero()) { 1031 Qs.push_back(Op); 1032 continue; 1033 } 1034 1035 // Bail out if types do not match. 1036 if (Ty != Q->getType()) 1037 return cannotDivide(Numerator); 1038 1039 FoundDenominatorTerm = true; 1040 Qs.push_back(Q); 1041 } 1042 1043 if (FoundDenominatorTerm) { 1044 Remainder = Zero; 1045 if (Qs.size() == 1) 1046 Quotient = Qs[0]; 1047 else 1048 Quotient = SE.getMulExpr(Qs); 1049 return; 1050 } 1051 1052 if (!isa<SCEVUnknown>(Denominator)) 1053 return cannotDivide(Numerator); 1054 1055 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1056 ValueToValueMap RewriteMap; 1057 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1058 cast<SCEVConstant>(Zero)->getValue(); 1059 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1060 1061 if (Remainder->isZero()) { 1062 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1063 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1064 cast<SCEVConstant>(One)->getValue(); 1065 Quotient = 1066 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1067 return; 1068 } 1069 1070 // Quotient is (Numerator - Remainder) divided by Denominator. 1071 const SCEV *Q, *R; 1072 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1073 // This SCEV does not seem to simplify: fail the division here. 1074 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1075 return cannotDivide(Numerator); 1076 divide(SE, Diff, Denominator, &Q, &R); 1077 if (R != Zero) 1078 return cannotDivide(Numerator); 1079 Quotient = Q; 1080 } 1081 1082 private: 1083 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1084 const SCEV *Denominator) 1085 : SE(S), Denominator(Denominator) { 1086 Zero = SE.getZero(Denominator->getType()); 1087 One = SE.getOne(Denominator->getType()); 1088 1089 // We generally do not know how to divide Expr by Denominator. We 1090 // initialize the division to a "cannot divide" state to simplify the rest 1091 // of the code. 1092 cannotDivide(Numerator); 1093 } 1094 1095 // Convenience function for giving up on the division. We set the quotient to 1096 // be equal to zero and the remainder to be equal to the numerator. 1097 void cannotDivide(const SCEV *Numerator) { 1098 Quotient = Zero; 1099 Remainder = Numerator; 1100 } 1101 1102 ScalarEvolution &SE; 1103 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1104 }; 1105 1106 } // end anonymous namespace 1107 1108 //===----------------------------------------------------------------------===// 1109 // Simple SCEV method implementations 1110 //===----------------------------------------------------------------------===// 1111 1112 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1113 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1114 ScalarEvolution &SE, 1115 Type *ResultTy) { 1116 // Handle the simplest case efficiently. 1117 if (K == 1) 1118 return SE.getTruncateOrZeroExtend(It, ResultTy); 1119 1120 // We are using the following formula for BC(It, K): 1121 // 1122 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1123 // 1124 // Suppose, W is the bitwidth of the return value. We must be prepared for 1125 // overflow. Hence, we must assure that the result of our computation is 1126 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1127 // safe in modular arithmetic. 1128 // 1129 // However, this code doesn't use exactly that formula; the formula it uses 1130 // is something like the following, where T is the number of factors of 2 in 1131 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1132 // exponentiation: 1133 // 1134 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1135 // 1136 // This formula is trivially equivalent to the previous formula. However, 1137 // this formula can be implemented much more efficiently. The trick is that 1138 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1139 // arithmetic. To do exact division in modular arithmetic, all we have 1140 // to do is multiply by the inverse. Therefore, this step can be done at 1141 // width W. 1142 // 1143 // The next issue is how to safely do the division by 2^T. The way this 1144 // is done is by doing the multiplication step at a width of at least W + T 1145 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1146 // when we perform the division by 2^T (which is equivalent to a right shift 1147 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1148 // truncated out after the division by 2^T. 1149 // 1150 // In comparison to just directly using the first formula, this technique 1151 // is much more efficient; using the first formula requires W * K bits, 1152 // but this formula less than W + K bits. Also, the first formula requires 1153 // a division step, whereas this formula only requires multiplies and shifts. 1154 // 1155 // It doesn't matter whether the subtraction step is done in the calculation 1156 // width or the input iteration count's width; if the subtraction overflows, 1157 // the result must be zero anyway. We prefer here to do it in the width of 1158 // the induction variable because it helps a lot for certain cases; CodeGen 1159 // isn't smart enough to ignore the overflow, which leads to much less 1160 // efficient code if the width of the subtraction is wider than the native 1161 // register width. 1162 // 1163 // (It's possible to not widen at all by pulling out factors of 2 before 1164 // the multiplication; for example, K=2 can be calculated as 1165 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1166 // extra arithmetic, so it's not an obvious win, and it gets 1167 // much more complicated for K > 3.) 1168 1169 // Protection from insane SCEVs; this bound is conservative, 1170 // but it probably doesn't matter. 1171 if (K > 1000) 1172 return SE.getCouldNotCompute(); 1173 1174 unsigned W = SE.getTypeSizeInBits(ResultTy); 1175 1176 // Calculate K! / 2^T and T; we divide out the factors of two before 1177 // multiplying for calculating K! / 2^T to avoid overflow. 1178 // Other overflow doesn't matter because we only care about the bottom 1179 // W bits of the result. 1180 APInt OddFactorial(W, 1); 1181 unsigned T = 1; 1182 for (unsigned i = 3; i <= K; ++i) { 1183 APInt Mult(W, i); 1184 unsigned TwoFactors = Mult.countTrailingZeros(); 1185 T += TwoFactors; 1186 Mult.lshrInPlace(TwoFactors); 1187 OddFactorial *= Mult; 1188 } 1189 1190 // We need at least W + T bits for the multiplication step 1191 unsigned CalculationBits = W + T; 1192 1193 // Calculate 2^T, at width T+W. 1194 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1195 1196 // Calculate the multiplicative inverse of K! / 2^T; 1197 // this multiplication factor will perform the exact division by 1198 // K! / 2^T. 1199 APInt Mod = APInt::getSignedMinValue(W+1); 1200 APInt MultiplyFactor = OddFactorial.zext(W+1); 1201 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1202 MultiplyFactor = MultiplyFactor.trunc(W); 1203 1204 // Calculate the product, at width T+W 1205 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1206 CalculationBits); 1207 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1208 for (unsigned i = 1; i != K; ++i) { 1209 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1210 Dividend = SE.getMulExpr(Dividend, 1211 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1212 } 1213 1214 // Divide by 2^T 1215 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1216 1217 // Truncate the result, and divide by K! / 2^T. 1218 1219 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1220 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1221 } 1222 1223 /// Return the value of this chain of recurrences at the specified iteration 1224 /// number. We can evaluate this recurrence by multiplying each element in the 1225 /// chain by the binomial coefficient corresponding to it. In other words, we 1226 /// can evaluate {A,+,B,+,C,+,D} as: 1227 /// 1228 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1229 /// 1230 /// where BC(It, k) stands for binomial coefficient. 1231 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1232 ScalarEvolution &SE) const { 1233 const SCEV *Result = getStart(); 1234 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1235 // The computation is correct in the face of overflow provided that the 1236 // multiplication is performed _after_ the evaluation of the binomial 1237 // coefficient. 1238 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1239 if (isa<SCEVCouldNotCompute>(Coeff)) 1240 return Coeff; 1241 1242 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1243 } 1244 return Result; 1245 } 1246 1247 //===----------------------------------------------------------------------===// 1248 // SCEV Expression folder implementations 1249 //===----------------------------------------------------------------------===// 1250 1251 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1252 unsigned Depth) { 1253 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1254 "This is not a truncating conversion!"); 1255 assert(isSCEVable(Ty) && 1256 "This is not a conversion to a SCEVable type!"); 1257 Ty = getEffectiveSCEVType(Ty); 1258 1259 FoldingSetNodeID ID; 1260 ID.AddInteger(scTruncate); 1261 ID.AddPointer(Op); 1262 ID.AddPointer(Ty); 1263 void *IP = nullptr; 1264 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1265 1266 // Fold if the operand is constant. 1267 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1268 return getConstant( 1269 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1270 1271 // trunc(trunc(x)) --> trunc(x) 1272 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1273 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1274 1275 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1276 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1277 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1278 1279 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1280 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1281 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1282 1283 if (Depth > MaxCastDepth) { 1284 SCEV *S = 1285 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1286 UniqueSCEVs.InsertNode(S, IP); 1287 addToLoopUseLists(S); 1288 return S; 1289 } 1290 1291 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1292 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1293 // if after transforming we have at most one truncate, not counting truncates 1294 // that replace other casts. 1295 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1296 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1297 SmallVector<const SCEV *, 4> Operands; 1298 unsigned numTruncs = 0; 1299 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1300 ++i) { 1301 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1302 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1303 numTruncs++; 1304 Operands.push_back(S); 1305 } 1306 if (numTruncs < 2) { 1307 if (isa<SCEVAddExpr>(Op)) 1308 return getAddExpr(Operands); 1309 else if (isa<SCEVMulExpr>(Op)) 1310 return getMulExpr(Operands); 1311 else 1312 llvm_unreachable("Unexpected SCEV type for Op."); 1313 } 1314 // Although we checked in the beginning that ID is not in the cache, it is 1315 // possible that during recursion and different modification ID was inserted 1316 // into the cache. So if we find it, just return it. 1317 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1318 return S; 1319 } 1320 1321 // If the input value is a chrec scev, truncate the chrec's operands. 1322 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1323 SmallVector<const SCEV *, 4> Operands; 1324 for (const SCEV *Op : AddRec->operands()) 1325 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1326 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1327 } 1328 1329 // The cast wasn't folded; create an explicit cast node. We can reuse 1330 // the existing insert position since if we get here, we won't have 1331 // made any changes which would invalidate it. 1332 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1333 Op, Ty); 1334 UniqueSCEVs.InsertNode(S, IP); 1335 addToLoopUseLists(S); 1336 return S; 1337 } 1338 1339 // Get the limit of a recurrence such that incrementing by Step cannot cause 1340 // signed overflow as long as the value of the recurrence within the 1341 // loop does not exceed this limit before incrementing. 1342 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1343 ICmpInst::Predicate *Pred, 1344 ScalarEvolution *SE) { 1345 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1346 if (SE->isKnownPositive(Step)) { 1347 *Pred = ICmpInst::ICMP_SLT; 1348 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1349 SE->getSignedRangeMax(Step)); 1350 } 1351 if (SE->isKnownNegative(Step)) { 1352 *Pred = ICmpInst::ICMP_SGT; 1353 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1354 SE->getSignedRangeMin(Step)); 1355 } 1356 return nullptr; 1357 } 1358 1359 // Get the limit of a recurrence such that incrementing by Step cannot cause 1360 // unsigned overflow as long as the value of the recurrence within the loop does 1361 // not exceed this limit before incrementing. 1362 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1363 ICmpInst::Predicate *Pred, 1364 ScalarEvolution *SE) { 1365 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1366 *Pred = ICmpInst::ICMP_ULT; 1367 1368 return SE->getConstant(APInt::getMinValue(BitWidth) - 1369 SE->getUnsignedRangeMax(Step)); 1370 } 1371 1372 namespace { 1373 1374 struct ExtendOpTraitsBase { 1375 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1376 unsigned); 1377 }; 1378 1379 // Used to make code generic over signed and unsigned overflow. 1380 template <typename ExtendOp> struct ExtendOpTraits { 1381 // Members present: 1382 // 1383 // static const SCEV::NoWrapFlags WrapType; 1384 // 1385 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1386 // 1387 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1388 // ICmpInst::Predicate *Pred, 1389 // ScalarEvolution *SE); 1390 }; 1391 1392 template <> 1393 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1394 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1395 1396 static const GetExtendExprTy GetExtendExpr; 1397 1398 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1399 ICmpInst::Predicate *Pred, 1400 ScalarEvolution *SE) { 1401 return getSignedOverflowLimitForStep(Step, Pred, SE); 1402 } 1403 }; 1404 1405 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1406 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1407 1408 template <> 1409 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1410 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1411 1412 static const GetExtendExprTy GetExtendExpr; 1413 1414 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1415 ICmpInst::Predicate *Pred, 1416 ScalarEvolution *SE) { 1417 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1418 } 1419 }; 1420 1421 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1422 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1423 1424 } // end anonymous namespace 1425 1426 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1427 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1428 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1429 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1430 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1431 // expression "Step + sext/zext(PreIncAR)" is congruent with 1432 // "sext/zext(PostIncAR)" 1433 template <typename ExtendOpTy> 1434 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1435 ScalarEvolution *SE, unsigned Depth) { 1436 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1437 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1438 1439 const Loop *L = AR->getLoop(); 1440 const SCEV *Start = AR->getStart(); 1441 const SCEV *Step = AR->getStepRecurrence(*SE); 1442 1443 // Check for a simple looking step prior to loop entry. 1444 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1445 if (!SA) 1446 return nullptr; 1447 1448 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1449 // subtraction is expensive. For this purpose, perform a quick and dirty 1450 // difference, by checking for Step in the operand list. 1451 SmallVector<const SCEV *, 4> DiffOps; 1452 for (const SCEV *Op : SA->operands()) 1453 if (Op != Step) 1454 DiffOps.push_back(Op); 1455 1456 if (DiffOps.size() == SA->getNumOperands()) 1457 return nullptr; 1458 1459 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1460 // `Step`: 1461 1462 // 1. NSW/NUW flags on the step increment. 1463 auto PreStartFlags = 1464 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1465 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1466 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1467 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1468 1469 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1470 // "S+X does not sign/unsign-overflow". 1471 // 1472 1473 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1474 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1475 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1476 return PreStart; 1477 1478 // 2. Direct overflow check on the step operation's expression. 1479 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1480 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1481 const SCEV *OperandExtendedStart = 1482 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1483 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1484 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1485 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1486 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1487 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1488 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1489 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1490 } 1491 return PreStart; 1492 } 1493 1494 // 3. Loop precondition. 1495 ICmpInst::Predicate Pred; 1496 const SCEV *OverflowLimit = 1497 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1498 1499 if (OverflowLimit && 1500 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1501 return PreStart; 1502 1503 return nullptr; 1504 } 1505 1506 // Get the normalized zero or sign extended expression for this AddRec's Start. 1507 template <typename ExtendOpTy> 1508 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1509 ScalarEvolution *SE, 1510 unsigned Depth) { 1511 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1512 1513 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1514 if (!PreStart) 1515 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1516 1517 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1518 Depth), 1519 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1520 } 1521 1522 // Try to prove away overflow by looking at "nearby" add recurrences. A 1523 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1524 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1525 // 1526 // Formally: 1527 // 1528 // {S,+,X} == {S-T,+,X} + T 1529 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1530 // 1531 // If ({S-T,+,X} + T) does not overflow ... (1) 1532 // 1533 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1534 // 1535 // If {S-T,+,X} does not overflow ... (2) 1536 // 1537 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1538 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1539 // 1540 // If (S-T)+T does not overflow ... (3) 1541 // 1542 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1543 // == {Ext(S),+,Ext(X)} == LHS 1544 // 1545 // Thus, if (1), (2) and (3) are true for some T, then 1546 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1547 // 1548 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1549 // does not overflow" restricted to the 0th iteration. Therefore we only need 1550 // to check for (1) and (2). 1551 // 1552 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1553 // is `Delta` (defined below). 1554 template <typename ExtendOpTy> 1555 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1556 const SCEV *Step, 1557 const Loop *L) { 1558 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1559 1560 // We restrict `Start` to a constant to prevent SCEV from spending too much 1561 // time here. It is correct (but more expensive) to continue with a 1562 // non-constant `Start` and do a general SCEV subtraction to compute 1563 // `PreStart` below. 1564 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1565 if (!StartC) 1566 return false; 1567 1568 APInt StartAI = StartC->getAPInt(); 1569 1570 for (unsigned Delta : {-2, -1, 1, 2}) { 1571 const SCEV *PreStart = getConstant(StartAI - Delta); 1572 1573 FoldingSetNodeID ID; 1574 ID.AddInteger(scAddRecExpr); 1575 ID.AddPointer(PreStart); 1576 ID.AddPointer(Step); 1577 ID.AddPointer(L); 1578 void *IP = nullptr; 1579 const auto *PreAR = 1580 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1581 1582 // Give up if we don't already have the add recurrence we need because 1583 // actually constructing an add recurrence is relatively expensive. 1584 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1585 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1586 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1587 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1588 DeltaS, &Pred, this); 1589 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1590 return true; 1591 } 1592 } 1593 1594 return false; 1595 } 1596 1597 // Finds an integer D for an expression (C + x + y + ...) such that the top 1598 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1599 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1600 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1601 // the (C + x + y + ...) expression is \p WholeAddExpr. 1602 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1603 const SCEVConstant *ConstantTerm, 1604 const SCEVAddExpr *WholeAddExpr) { 1605 const APInt C = ConstantTerm->getAPInt(); 1606 const unsigned BitWidth = C.getBitWidth(); 1607 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1608 uint32_t TZ = BitWidth; 1609 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1610 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1611 if (TZ) { 1612 // Set D to be as many least significant bits of C as possible while still 1613 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1614 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1615 } 1616 return APInt(BitWidth, 0); 1617 } 1618 1619 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1620 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1621 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1622 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1623 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1624 const APInt &ConstantStart, 1625 const SCEV *Step) { 1626 const unsigned BitWidth = ConstantStart.getBitWidth(); 1627 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1628 if (TZ) 1629 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1630 : ConstantStart; 1631 return APInt(BitWidth, 0); 1632 } 1633 1634 const SCEV * 1635 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1636 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1637 "This is not an extending conversion!"); 1638 assert(isSCEVable(Ty) && 1639 "This is not a conversion to a SCEVable type!"); 1640 Ty = getEffectiveSCEVType(Ty); 1641 1642 // Fold if the operand is constant. 1643 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1644 return getConstant( 1645 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1646 1647 // zext(zext(x)) --> zext(x) 1648 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1649 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1650 1651 // Before doing any expensive analysis, check to see if we've already 1652 // computed a SCEV for this Op and Ty. 1653 FoldingSetNodeID ID; 1654 ID.AddInteger(scZeroExtend); 1655 ID.AddPointer(Op); 1656 ID.AddPointer(Ty); 1657 void *IP = nullptr; 1658 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1659 if (Depth > MaxCastDepth) { 1660 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1661 Op, Ty); 1662 UniqueSCEVs.InsertNode(S, IP); 1663 addToLoopUseLists(S); 1664 return S; 1665 } 1666 1667 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1668 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1669 // It's possible the bits taken off by the truncate were all zero bits. If 1670 // so, we should be able to simplify this further. 1671 const SCEV *X = ST->getOperand(); 1672 ConstantRange CR = getUnsignedRange(X); 1673 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1674 unsigned NewBits = getTypeSizeInBits(Ty); 1675 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1676 CR.zextOrTrunc(NewBits))) 1677 return getTruncateOrZeroExtend(X, Ty, Depth); 1678 } 1679 1680 // If the input value is a chrec scev, and we can prove that the value 1681 // did not overflow the old, smaller, value, we can zero extend all of the 1682 // operands (often constants). This allows analysis of something like 1683 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1684 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1685 if (AR->isAffine()) { 1686 const SCEV *Start = AR->getStart(); 1687 const SCEV *Step = AR->getStepRecurrence(*this); 1688 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1689 const Loop *L = AR->getLoop(); 1690 1691 if (!AR->hasNoUnsignedWrap()) { 1692 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1693 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1694 } 1695 1696 // If we have special knowledge that this addrec won't overflow, 1697 // we don't need to do any further analysis. 1698 if (AR->hasNoUnsignedWrap()) 1699 return getAddRecExpr( 1700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1701 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1702 1703 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1704 // Note that this serves two purposes: It filters out loops that are 1705 // simply not analyzable, and it covers the case where this code is 1706 // being called from within backedge-taken count analysis, such that 1707 // attempting to ask for the backedge-taken count would likely result 1708 // in infinite recursion. In the later case, the analysis code will 1709 // cope with a conservative value, and it will take care to purge 1710 // that value once it has finished. 1711 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1712 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1713 // Manually compute the final value for AR, checking for 1714 // overflow. 1715 1716 // Check whether the backedge-taken count can be losslessly casted to 1717 // the addrec's type. The count is always unsigned. 1718 const SCEV *CastedMaxBECount = 1719 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1720 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1721 CastedMaxBECount, MaxBECount->getType(), Depth); 1722 if (MaxBECount == RecastedMaxBECount) { 1723 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1724 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1725 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1726 SCEV::FlagAnyWrap, Depth + 1); 1727 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1728 SCEV::FlagAnyWrap, 1729 Depth + 1), 1730 WideTy, Depth + 1); 1731 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1732 const SCEV *WideMaxBECount = 1733 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1734 const SCEV *OperandExtendedAdd = 1735 getAddExpr(WideStart, 1736 getMulExpr(WideMaxBECount, 1737 getZeroExtendExpr(Step, WideTy, Depth + 1), 1738 SCEV::FlagAnyWrap, Depth + 1), 1739 SCEV::FlagAnyWrap, Depth + 1); 1740 if (ZAdd == OperandExtendedAdd) { 1741 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1742 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1743 // Return the expression with the addrec on the outside. 1744 return getAddRecExpr( 1745 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1746 Depth + 1), 1747 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1748 AR->getNoWrapFlags()); 1749 } 1750 // Similar to above, only this time treat the step value as signed. 1751 // This covers loops that count down. 1752 OperandExtendedAdd = 1753 getAddExpr(WideStart, 1754 getMulExpr(WideMaxBECount, 1755 getSignExtendExpr(Step, WideTy, Depth + 1), 1756 SCEV::FlagAnyWrap, Depth + 1), 1757 SCEV::FlagAnyWrap, Depth + 1); 1758 if (ZAdd == OperandExtendedAdd) { 1759 // Cache knowledge of AR NW, which is propagated to this AddRec. 1760 // Negative step causes unsigned wrap, but it still can't self-wrap. 1761 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1762 // Return the expression with the addrec on the outside. 1763 return getAddRecExpr( 1764 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1765 Depth + 1), 1766 getSignExtendExpr(Step, Ty, Depth + 1), L, 1767 AR->getNoWrapFlags()); 1768 } 1769 } 1770 } 1771 1772 // Normally, in the cases we can prove no-overflow via a 1773 // backedge guarding condition, we can also compute a backedge 1774 // taken count for the loop. The exceptions are assumptions and 1775 // guards present in the loop -- SCEV is not great at exploiting 1776 // these to compute max backedge taken counts, but can still use 1777 // these to prove lack of overflow. Use this fact to avoid 1778 // doing extra work that may not pay off. 1779 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1780 !AC.assumptions().empty()) { 1781 // If the backedge is guarded by a comparison with the pre-inc 1782 // value the addrec is safe. Also, if the entry is guarded by 1783 // a comparison with the start value and the backedge is 1784 // guarded by a comparison with the post-inc value, the addrec 1785 // is safe. 1786 if (isKnownPositive(Step)) { 1787 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1788 getUnsignedRangeMax(Step)); 1789 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1790 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1791 // Cache knowledge of AR NUW, which is propagated to this 1792 // AddRec. 1793 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1794 // Return the expression with the addrec on the outside. 1795 return getAddRecExpr( 1796 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1797 Depth + 1), 1798 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1799 AR->getNoWrapFlags()); 1800 } 1801 } else if (isKnownNegative(Step)) { 1802 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1803 getSignedRangeMin(Step)); 1804 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1805 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1806 // Cache knowledge of AR NW, which is propagated to this 1807 // AddRec. Negative step causes unsigned wrap, but it 1808 // still can't self-wrap. 1809 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1810 // Return the expression with the addrec on the outside. 1811 return getAddRecExpr( 1812 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1813 Depth + 1), 1814 getSignExtendExpr(Step, Ty, Depth + 1), L, 1815 AR->getNoWrapFlags()); 1816 } 1817 } 1818 } 1819 1820 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1821 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1822 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1823 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1824 const APInt &C = SC->getAPInt(); 1825 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1826 if (D != 0) { 1827 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1828 const SCEV *SResidual = 1829 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1830 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1831 return getAddExpr(SZExtD, SZExtR, 1832 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1833 Depth + 1); 1834 } 1835 } 1836 1837 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1838 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1839 return getAddRecExpr( 1840 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1841 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1842 } 1843 } 1844 1845 // zext(A % B) --> zext(A) % zext(B) 1846 { 1847 const SCEV *LHS; 1848 const SCEV *RHS; 1849 if (matchURem(Op, LHS, RHS)) 1850 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1851 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1852 } 1853 1854 // zext(A / B) --> zext(A) / zext(B). 1855 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1856 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1857 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1858 1859 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1860 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1861 if (SA->hasNoUnsignedWrap()) { 1862 // If the addition does not unsign overflow then we can, by definition, 1863 // commute the zero extension with the addition operation. 1864 SmallVector<const SCEV *, 4> Ops; 1865 for (const auto *Op : SA->operands()) 1866 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1867 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1868 } 1869 1870 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1871 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1872 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1873 // 1874 // Often address arithmetics contain expressions like 1875 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1876 // This transformation is useful while proving that such expressions are 1877 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1878 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1879 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1880 if (D != 0) { 1881 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1882 const SCEV *SResidual = 1883 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1884 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1885 return getAddExpr(SZExtD, SZExtR, 1886 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1887 Depth + 1); 1888 } 1889 } 1890 } 1891 1892 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1893 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1894 if (SM->hasNoUnsignedWrap()) { 1895 // If the multiply does not unsign overflow then we can, by definition, 1896 // commute the zero extension with the multiply operation. 1897 SmallVector<const SCEV *, 4> Ops; 1898 for (const auto *Op : SM->operands()) 1899 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1900 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1901 } 1902 1903 // zext(2^K * (trunc X to iN)) to iM -> 1904 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1905 // 1906 // Proof: 1907 // 1908 // zext(2^K * (trunc X to iN)) to iM 1909 // = zext((trunc X to iN) << K) to iM 1910 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1911 // (because shl removes the top K bits) 1912 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1913 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1914 // 1915 if (SM->getNumOperands() == 2) 1916 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1917 if (MulLHS->getAPInt().isPowerOf2()) 1918 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1919 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1920 MulLHS->getAPInt().logBase2(); 1921 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1922 return getMulExpr( 1923 getZeroExtendExpr(MulLHS, Ty), 1924 getZeroExtendExpr( 1925 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1926 SCEV::FlagNUW, Depth + 1); 1927 } 1928 } 1929 1930 // The cast wasn't folded; create an explicit cast node. 1931 // Recompute the insert position, as it may have been invalidated. 1932 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1933 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1934 Op, Ty); 1935 UniqueSCEVs.InsertNode(S, IP); 1936 addToLoopUseLists(S); 1937 return S; 1938 } 1939 1940 const SCEV * 1941 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1942 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1943 "This is not an extending conversion!"); 1944 assert(isSCEVable(Ty) && 1945 "This is not a conversion to a SCEVable type!"); 1946 Ty = getEffectiveSCEVType(Ty); 1947 1948 // Fold if the operand is constant. 1949 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1950 return getConstant( 1951 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1952 1953 // sext(sext(x)) --> sext(x) 1954 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1955 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1956 1957 // sext(zext(x)) --> zext(x) 1958 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1959 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1960 1961 // Before doing any expensive analysis, check to see if we've already 1962 // computed a SCEV for this Op and Ty. 1963 FoldingSetNodeID ID; 1964 ID.AddInteger(scSignExtend); 1965 ID.AddPointer(Op); 1966 ID.AddPointer(Ty); 1967 void *IP = nullptr; 1968 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1969 // Limit recursion depth. 1970 if (Depth > MaxCastDepth) { 1971 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1972 Op, Ty); 1973 UniqueSCEVs.InsertNode(S, IP); 1974 addToLoopUseLists(S); 1975 return S; 1976 } 1977 1978 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1979 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1980 // It's possible the bits taken off by the truncate were all sign bits. If 1981 // so, we should be able to simplify this further. 1982 const SCEV *X = ST->getOperand(); 1983 ConstantRange CR = getSignedRange(X); 1984 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1985 unsigned NewBits = getTypeSizeInBits(Ty); 1986 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1987 CR.sextOrTrunc(NewBits))) 1988 return getTruncateOrSignExtend(X, Ty, Depth); 1989 } 1990 1991 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1992 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1993 if (SA->hasNoSignedWrap()) { 1994 // If the addition does not sign overflow then we can, by definition, 1995 // commute the sign extension with the addition operation. 1996 SmallVector<const SCEV *, 4> Ops; 1997 for (const auto *Op : SA->operands()) 1998 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1999 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2000 } 2001 2002 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2003 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2004 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2005 // 2006 // For instance, this will bring two seemingly different expressions: 2007 // 1 + sext(5 + 20 * %x + 24 * %y) and 2008 // sext(6 + 20 * %x + 24 * %y) 2009 // to the same form: 2010 // 2 + sext(4 + 20 * %x + 24 * %y) 2011 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2012 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2013 if (D != 0) { 2014 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2015 const SCEV *SResidual = 2016 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2017 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2018 return getAddExpr(SSExtD, SSExtR, 2019 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2020 Depth + 1); 2021 } 2022 } 2023 } 2024 // If the input value is a chrec scev, and we can prove that the value 2025 // did not overflow the old, smaller, value, we can sign extend all of the 2026 // operands (often constants). This allows analysis of something like 2027 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2028 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2029 if (AR->isAffine()) { 2030 const SCEV *Start = AR->getStart(); 2031 const SCEV *Step = AR->getStepRecurrence(*this); 2032 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2033 const Loop *L = AR->getLoop(); 2034 2035 if (!AR->hasNoSignedWrap()) { 2036 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2037 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2038 } 2039 2040 // If we have special knowledge that this addrec won't overflow, 2041 // we don't need to do any further analysis. 2042 if (AR->hasNoSignedWrap()) 2043 return getAddRecExpr( 2044 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2045 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2046 2047 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2048 // Note that this serves two purposes: It filters out loops that are 2049 // simply not analyzable, and it covers the case where this code is 2050 // being called from within backedge-taken count analysis, such that 2051 // attempting to ask for the backedge-taken count would likely result 2052 // in infinite recursion. In the later case, the analysis code will 2053 // cope with a conservative value, and it will take care to purge 2054 // that value once it has finished. 2055 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2056 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2057 // Manually compute the final value for AR, checking for 2058 // overflow. 2059 2060 // Check whether the backedge-taken count can be losslessly casted to 2061 // the addrec's type. The count is always unsigned. 2062 const SCEV *CastedMaxBECount = 2063 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2064 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2065 CastedMaxBECount, MaxBECount->getType(), Depth); 2066 if (MaxBECount == RecastedMaxBECount) { 2067 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2068 // Check whether Start+Step*MaxBECount has no signed overflow. 2069 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2070 SCEV::FlagAnyWrap, Depth + 1); 2071 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2072 SCEV::FlagAnyWrap, 2073 Depth + 1), 2074 WideTy, Depth + 1); 2075 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2076 const SCEV *WideMaxBECount = 2077 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2078 const SCEV *OperandExtendedAdd = 2079 getAddExpr(WideStart, 2080 getMulExpr(WideMaxBECount, 2081 getSignExtendExpr(Step, WideTy, Depth + 1), 2082 SCEV::FlagAnyWrap, Depth + 1), 2083 SCEV::FlagAnyWrap, Depth + 1); 2084 if (SAdd == OperandExtendedAdd) { 2085 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2086 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2087 // Return the expression with the addrec on the outside. 2088 return getAddRecExpr( 2089 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2090 Depth + 1), 2091 getSignExtendExpr(Step, Ty, Depth + 1), L, 2092 AR->getNoWrapFlags()); 2093 } 2094 // Similar to above, only this time treat the step value as unsigned. 2095 // This covers loops that count up with an unsigned step. 2096 OperandExtendedAdd = 2097 getAddExpr(WideStart, 2098 getMulExpr(WideMaxBECount, 2099 getZeroExtendExpr(Step, WideTy, Depth + 1), 2100 SCEV::FlagAnyWrap, Depth + 1), 2101 SCEV::FlagAnyWrap, Depth + 1); 2102 if (SAdd == OperandExtendedAdd) { 2103 // If AR wraps around then 2104 // 2105 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2106 // => SAdd != OperandExtendedAdd 2107 // 2108 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2109 // (SAdd == OperandExtendedAdd => AR is NW) 2110 2111 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2112 2113 // Return the expression with the addrec on the outside. 2114 return getAddRecExpr( 2115 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2116 Depth + 1), 2117 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2118 AR->getNoWrapFlags()); 2119 } 2120 } 2121 } 2122 2123 // Normally, in the cases we can prove no-overflow via a 2124 // backedge guarding condition, we can also compute a backedge 2125 // taken count for the loop. The exceptions are assumptions and 2126 // guards present in the loop -- SCEV is not great at exploiting 2127 // these to compute max backedge taken counts, but can still use 2128 // these to prove lack of overflow. Use this fact to avoid 2129 // doing extra work that may not pay off. 2130 2131 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2132 !AC.assumptions().empty()) { 2133 // If the backedge is guarded by a comparison with the pre-inc 2134 // value the addrec is safe. Also, if the entry is guarded by 2135 // a comparison with the start value and the backedge is 2136 // guarded by a comparison with the post-inc value, the addrec 2137 // is safe. 2138 ICmpInst::Predicate Pred; 2139 const SCEV *OverflowLimit = 2140 getSignedOverflowLimitForStep(Step, &Pred, this); 2141 if (OverflowLimit && 2142 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2143 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2144 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2145 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2146 return getAddRecExpr( 2147 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2148 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2149 } 2150 } 2151 2152 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2153 // if D + (C - D + Step * n) could be proven to not signed wrap 2154 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2155 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2156 const APInt &C = SC->getAPInt(); 2157 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2158 if (D != 0) { 2159 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2160 const SCEV *SResidual = 2161 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2162 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2163 return getAddExpr(SSExtD, SSExtR, 2164 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2165 Depth + 1); 2166 } 2167 } 2168 2169 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2170 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2171 return getAddRecExpr( 2172 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2173 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2174 } 2175 } 2176 2177 // If the input value is provably positive and we could not simplify 2178 // away the sext build a zext instead. 2179 if (isKnownNonNegative(Op)) 2180 return getZeroExtendExpr(Op, Ty, Depth + 1); 2181 2182 // The cast wasn't folded; create an explicit cast node. 2183 // Recompute the insert position, as it may have been invalidated. 2184 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2185 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2186 Op, Ty); 2187 UniqueSCEVs.InsertNode(S, IP); 2188 addToLoopUseLists(S); 2189 return S; 2190 } 2191 2192 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2193 /// unspecified bits out to the given type. 2194 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2195 Type *Ty) { 2196 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2197 "This is not an extending conversion!"); 2198 assert(isSCEVable(Ty) && 2199 "This is not a conversion to a SCEVable type!"); 2200 Ty = getEffectiveSCEVType(Ty); 2201 2202 // Sign-extend negative constants. 2203 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2204 if (SC->getAPInt().isNegative()) 2205 return getSignExtendExpr(Op, Ty); 2206 2207 // Peel off a truncate cast. 2208 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2209 const SCEV *NewOp = T->getOperand(); 2210 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2211 return getAnyExtendExpr(NewOp, Ty); 2212 return getTruncateOrNoop(NewOp, Ty); 2213 } 2214 2215 // Next try a zext cast. If the cast is folded, use it. 2216 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2217 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2218 return ZExt; 2219 2220 // Next try a sext cast. If the cast is folded, use it. 2221 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2222 if (!isa<SCEVSignExtendExpr>(SExt)) 2223 return SExt; 2224 2225 // Force the cast to be folded into the operands of an addrec. 2226 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2227 SmallVector<const SCEV *, 4> Ops; 2228 for (const SCEV *Op : AR->operands()) 2229 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2230 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2231 } 2232 2233 // If the expression is obviously signed, use the sext cast value. 2234 if (isa<SCEVSMaxExpr>(Op)) 2235 return SExt; 2236 2237 // Absent any other information, use the zext cast value. 2238 return ZExt; 2239 } 2240 2241 /// Process the given Ops list, which is a list of operands to be added under 2242 /// the given scale, update the given map. This is a helper function for 2243 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2244 /// that would form an add expression like this: 2245 /// 2246 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2247 /// 2248 /// where A and B are constants, update the map with these values: 2249 /// 2250 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2251 /// 2252 /// and add 13 + A*B*29 to AccumulatedConstant. 2253 /// This will allow getAddRecExpr to produce this: 2254 /// 2255 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2256 /// 2257 /// This form often exposes folding opportunities that are hidden in 2258 /// the original operand list. 2259 /// 2260 /// Return true iff it appears that any interesting folding opportunities 2261 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2262 /// the common case where no interesting opportunities are present, and 2263 /// is also used as a check to avoid infinite recursion. 2264 static bool 2265 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2266 SmallVectorImpl<const SCEV *> &NewOps, 2267 APInt &AccumulatedConstant, 2268 const SCEV *const *Ops, size_t NumOperands, 2269 const APInt &Scale, 2270 ScalarEvolution &SE) { 2271 bool Interesting = false; 2272 2273 // Iterate over the add operands. They are sorted, with constants first. 2274 unsigned i = 0; 2275 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2276 ++i; 2277 // Pull a buried constant out to the outside. 2278 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2279 Interesting = true; 2280 AccumulatedConstant += Scale * C->getAPInt(); 2281 } 2282 2283 // Next comes everything else. We're especially interested in multiplies 2284 // here, but they're in the middle, so just visit the rest with one loop. 2285 for (; i != NumOperands; ++i) { 2286 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2287 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2288 APInt NewScale = 2289 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2290 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2291 // A multiplication of a constant with another add; recurse. 2292 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2293 Interesting |= 2294 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2295 Add->op_begin(), Add->getNumOperands(), 2296 NewScale, SE); 2297 } else { 2298 // A multiplication of a constant with some other value. Update 2299 // the map. 2300 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2301 const SCEV *Key = SE.getMulExpr(MulOps); 2302 auto Pair = M.insert({Key, NewScale}); 2303 if (Pair.second) { 2304 NewOps.push_back(Pair.first->first); 2305 } else { 2306 Pair.first->second += NewScale; 2307 // The map already had an entry for this value, which may indicate 2308 // a folding opportunity. 2309 Interesting = true; 2310 } 2311 } 2312 } else { 2313 // An ordinary operand. Update the map. 2314 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2315 M.insert({Ops[i], Scale}); 2316 if (Pair.second) { 2317 NewOps.push_back(Pair.first->first); 2318 } else { 2319 Pair.first->second += Scale; 2320 // The map already had an entry for this value, which may indicate 2321 // a folding opportunity. 2322 Interesting = true; 2323 } 2324 } 2325 } 2326 2327 return Interesting; 2328 } 2329 2330 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2331 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2332 // can't-overflow flags for the operation if possible. 2333 static SCEV::NoWrapFlags 2334 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2335 const ArrayRef<const SCEV *> Ops, 2336 SCEV::NoWrapFlags Flags) { 2337 using namespace std::placeholders; 2338 2339 using OBO = OverflowingBinaryOperator; 2340 2341 bool CanAnalyze = 2342 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2343 (void)CanAnalyze; 2344 assert(CanAnalyze && "don't call from other places!"); 2345 2346 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2347 SCEV::NoWrapFlags SignOrUnsignWrap = 2348 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2349 2350 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2351 auto IsKnownNonNegative = [&](const SCEV *S) { 2352 return SE->isKnownNonNegative(S); 2353 }; 2354 2355 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2356 Flags = 2357 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2358 2359 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2360 2361 if (SignOrUnsignWrap != SignOrUnsignMask && 2362 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2363 isa<SCEVConstant>(Ops[0])) { 2364 2365 auto Opcode = [&] { 2366 switch (Type) { 2367 case scAddExpr: 2368 return Instruction::Add; 2369 case scMulExpr: 2370 return Instruction::Mul; 2371 default: 2372 llvm_unreachable("Unexpected SCEV op."); 2373 } 2374 }(); 2375 2376 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2377 2378 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2379 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2380 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2381 Opcode, C, OBO::NoSignedWrap); 2382 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2383 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2384 } 2385 2386 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2387 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2388 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2389 Opcode, C, OBO::NoUnsignedWrap); 2390 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2391 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2392 } 2393 } 2394 2395 return Flags; 2396 } 2397 2398 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2399 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2400 } 2401 2402 /// Get a canonical add expression, or something simpler if possible. 2403 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2404 SCEV::NoWrapFlags Flags, 2405 unsigned Depth) { 2406 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2407 "only nuw or nsw allowed"); 2408 assert(!Ops.empty() && "Cannot get empty add!"); 2409 if (Ops.size() == 1) return Ops[0]; 2410 #ifndef NDEBUG 2411 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2412 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2413 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2414 "SCEVAddExpr operand types don't match!"); 2415 #endif 2416 2417 // Sort by complexity, this groups all similar expression types together. 2418 GroupByComplexity(Ops, &LI, DT); 2419 2420 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2421 2422 // If there are any constants, fold them together. 2423 unsigned Idx = 0; 2424 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2425 ++Idx; 2426 assert(Idx < Ops.size()); 2427 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2428 // We found two constants, fold them together! 2429 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2430 if (Ops.size() == 2) return Ops[0]; 2431 Ops.erase(Ops.begin()+1); // Erase the folded element 2432 LHSC = cast<SCEVConstant>(Ops[0]); 2433 } 2434 2435 // If we are left with a constant zero being added, strip it off. 2436 if (LHSC->getValue()->isZero()) { 2437 Ops.erase(Ops.begin()); 2438 --Idx; 2439 } 2440 2441 if (Ops.size() == 1) return Ops[0]; 2442 } 2443 2444 // Limit recursion calls depth. 2445 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2446 return getOrCreateAddExpr(Ops, Flags); 2447 2448 // Okay, check to see if the same value occurs in the operand list more than 2449 // once. If so, merge them together into an multiply expression. Since we 2450 // sorted the list, these values are required to be adjacent. 2451 Type *Ty = Ops[0]->getType(); 2452 bool FoundMatch = false; 2453 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2454 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2455 // Scan ahead to count how many equal operands there are. 2456 unsigned Count = 2; 2457 while (i+Count != e && Ops[i+Count] == Ops[i]) 2458 ++Count; 2459 // Merge the values into a multiply. 2460 const SCEV *Scale = getConstant(Ty, Count); 2461 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2462 if (Ops.size() == Count) 2463 return Mul; 2464 Ops[i] = Mul; 2465 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2466 --i; e -= Count - 1; 2467 FoundMatch = true; 2468 } 2469 if (FoundMatch) 2470 return getAddExpr(Ops, Flags, Depth + 1); 2471 2472 // Check for truncates. If all the operands are truncated from the same 2473 // type, see if factoring out the truncate would permit the result to be 2474 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2475 // if the contents of the resulting outer trunc fold to something simple. 2476 auto FindTruncSrcType = [&]() -> Type * { 2477 // We're ultimately looking to fold an addrec of truncs and muls of only 2478 // constants and truncs, so if we find any other types of SCEV 2479 // as operands of the addrec then we bail and return nullptr here. 2480 // Otherwise, we return the type of the operand of a trunc that we find. 2481 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2482 return T->getOperand()->getType(); 2483 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2484 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2485 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2486 return T->getOperand()->getType(); 2487 } 2488 return nullptr; 2489 }; 2490 if (auto *SrcType = FindTruncSrcType()) { 2491 SmallVector<const SCEV *, 8> LargeOps; 2492 bool Ok = true; 2493 // Check all the operands to see if they can be represented in the 2494 // source type of the truncate. 2495 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2496 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2497 if (T->getOperand()->getType() != SrcType) { 2498 Ok = false; 2499 break; 2500 } 2501 LargeOps.push_back(T->getOperand()); 2502 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2503 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2504 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2505 SmallVector<const SCEV *, 8> LargeMulOps; 2506 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2507 if (const SCEVTruncateExpr *T = 2508 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2509 if (T->getOperand()->getType() != SrcType) { 2510 Ok = false; 2511 break; 2512 } 2513 LargeMulOps.push_back(T->getOperand()); 2514 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2515 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2516 } else { 2517 Ok = false; 2518 break; 2519 } 2520 } 2521 if (Ok) 2522 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2523 } else { 2524 Ok = false; 2525 break; 2526 } 2527 } 2528 if (Ok) { 2529 // Evaluate the expression in the larger type. 2530 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2531 // If it folds to something simple, use it. Otherwise, don't. 2532 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2533 return getTruncateExpr(Fold, Ty); 2534 } 2535 } 2536 2537 // Skip past any other cast SCEVs. 2538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2539 ++Idx; 2540 2541 // If there are add operands they would be next. 2542 if (Idx < Ops.size()) { 2543 bool DeletedAdd = false; 2544 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2545 if (Ops.size() > AddOpsInlineThreshold || 2546 Add->getNumOperands() > AddOpsInlineThreshold) 2547 break; 2548 // If we have an add, expand the add operands onto the end of the operands 2549 // list. 2550 Ops.erase(Ops.begin()+Idx); 2551 Ops.append(Add->op_begin(), Add->op_end()); 2552 DeletedAdd = true; 2553 } 2554 2555 // If we deleted at least one add, we added operands to the end of the list, 2556 // and they are not necessarily sorted. Recurse to resort and resimplify 2557 // any operands we just acquired. 2558 if (DeletedAdd) 2559 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2560 } 2561 2562 // Skip over the add expression until we get to a multiply. 2563 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2564 ++Idx; 2565 2566 // Check to see if there are any folding opportunities present with 2567 // operands multiplied by constant values. 2568 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2569 uint64_t BitWidth = getTypeSizeInBits(Ty); 2570 DenseMap<const SCEV *, APInt> M; 2571 SmallVector<const SCEV *, 8> NewOps; 2572 APInt AccumulatedConstant(BitWidth, 0); 2573 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2574 Ops.data(), Ops.size(), 2575 APInt(BitWidth, 1), *this)) { 2576 struct APIntCompare { 2577 bool operator()(const APInt &LHS, const APInt &RHS) const { 2578 return LHS.ult(RHS); 2579 } 2580 }; 2581 2582 // Some interesting folding opportunity is present, so its worthwhile to 2583 // re-generate the operands list. Group the operands by constant scale, 2584 // to avoid multiplying by the same constant scale multiple times. 2585 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2586 for (const SCEV *NewOp : NewOps) 2587 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2588 // Re-generate the operands list. 2589 Ops.clear(); 2590 if (AccumulatedConstant != 0) 2591 Ops.push_back(getConstant(AccumulatedConstant)); 2592 for (auto &MulOp : MulOpLists) 2593 if (MulOp.first != 0) 2594 Ops.push_back(getMulExpr( 2595 getConstant(MulOp.first), 2596 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2597 SCEV::FlagAnyWrap, Depth + 1)); 2598 if (Ops.empty()) 2599 return getZero(Ty); 2600 if (Ops.size() == 1) 2601 return Ops[0]; 2602 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2603 } 2604 } 2605 2606 // If we are adding something to a multiply expression, make sure the 2607 // something is not already an operand of the multiply. If so, merge it into 2608 // the multiply. 2609 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2610 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2611 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2612 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2613 if (isa<SCEVConstant>(MulOpSCEV)) 2614 continue; 2615 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2616 if (MulOpSCEV == Ops[AddOp]) { 2617 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2618 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2619 if (Mul->getNumOperands() != 2) { 2620 // If the multiply has more than two operands, we must get the 2621 // Y*Z term. 2622 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2623 Mul->op_begin()+MulOp); 2624 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2625 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2626 } 2627 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2628 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2629 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2630 SCEV::FlagAnyWrap, Depth + 1); 2631 if (Ops.size() == 2) return OuterMul; 2632 if (AddOp < Idx) { 2633 Ops.erase(Ops.begin()+AddOp); 2634 Ops.erase(Ops.begin()+Idx-1); 2635 } else { 2636 Ops.erase(Ops.begin()+Idx); 2637 Ops.erase(Ops.begin()+AddOp-1); 2638 } 2639 Ops.push_back(OuterMul); 2640 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2641 } 2642 2643 // Check this multiply against other multiplies being added together. 2644 for (unsigned OtherMulIdx = Idx+1; 2645 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2646 ++OtherMulIdx) { 2647 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2648 // If MulOp occurs in OtherMul, we can fold the two multiplies 2649 // together. 2650 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2651 OMulOp != e; ++OMulOp) 2652 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2653 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2654 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2655 if (Mul->getNumOperands() != 2) { 2656 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2657 Mul->op_begin()+MulOp); 2658 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2659 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2660 } 2661 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2662 if (OtherMul->getNumOperands() != 2) { 2663 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2664 OtherMul->op_begin()+OMulOp); 2665 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2666 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2667 } 2668 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2669 const SCEV *InnerMulSum = 2670 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2671 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2672 SCEV::FlagAnyWrap, Depth + 1); 2673 if (Ops.size() == 2) return OuterMul; 2674 Ops.erase(Ops.begin()+Idx); 2675 Ops.erase(Ops.begin()+OtherMulIdx-1); 2676 Ops.push_back(OuterMul); 2677 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2678 } 2679 } 2680 } 2681 } 2682 2683 // If there are any add recurrences in the operands list, see if any other 2684 // added values are loop invariant. If so, we can fold them into the 2685 // recurrence. 2686 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2687 ++Idx; 2688 2689 // Scan over all recurrences, trying to fold loop invariants into them. 2690 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2691 // Scan all of the other operands to this add and add them to the vector if 2692 // they are loop invariant w.r.t. the recurrence. 2693 SmallVector<const SCEV *, 8> LIOps; 2694 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2695 const Loop *AddRecLoop = AddRec->getLoop(); 2696 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2697 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2698 LIOps.push_back(Ops[i]); 2699 Ops.erase(Ops.begin()+i); 2700 --i; --e; 2701 } 2702 2703 // If we found some loop invariants, fold them into the recurrence. 2704 if (!LIOps.empty()) { 2705 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2706 LIOps.push_back(AddRec->getStart()); 2707 2708 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2709 AddRec->op_end()); 2710 // This follows from the fact that the no-wrap flags on the outer add 2711 // expression are applicable on the 0th iteration, when the add recurrence 2712 // will be equal to its start value. 2713 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2714 2715 // Build the new addrec. Propagate the NUW and NSW flags if both the 2716 // outer add and the inner addrec are guaranteed to have no overflow. 2717 // Always propagate NW. 2718 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2719 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2720 2721 // If all of the other operands were loop invariant, we are done. 2722 if (Ops.size() == 1) return NewRec; 2723 2724 // Otherwise, add the folded AddRec by the non-invariant parts. 2725 for (unsigned i = 0;; ++i) 2726 if (Ops[i] == AddRec) { 2727 Ops[i] = NewRec; 2728 break; 2729 } 2730 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2731 } 2732 2733 // Okay, if there weren't any loop invariants to be folded, check to see if 2734 // there are multiple AddRec's with the same loop induction variable being 2735 // added together. If so, we can fold them. 2736 for (unsigned OtherIdx = Idx+1; 2737 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2738 ++OtherIdx) { 2739 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2740 // so that the 1st found AddRecExpr is dominated by all others. 2741 assert(DT.dominates( 2742 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2743 AddRec->getLoop()->getHeader()) && 2744 "AddRecExprs are not sorted in reverse dominance order?"); 2745 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2746 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2747 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2748 AddRec->op_end()); 2749 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2750 ++OtherIdx) { 2751 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2752 if (OtherAddRec->getLoop() == AddRecLoop) { 2753 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2754 i != e; ++i) { 2755 if (i >= AddRecOps.size()) { 2756 AddRecOps.append(OtherAddRec->op_begin()+i, 2757 OtherAddRec->op_end()); 2758 break; 2759 } 2760 SmallVector<const SCEV *, 2> TwoOps = { 2761 AddRecOps[i], OtherAddRec->getOperand(i)}; 2762 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2763 } 2764 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2765 } 2766 } 2767 // Step size has changed, so we cannot guarantee no self-wraparound. 2768 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2769 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2770 } 2771 } 2772 2773 // Otherwise couldn't fold anything into this recurrence. Move onto the 2774 // next one. 2775 } 2776 2777 // Okay, it looks like we really DO need an add expr. Check to see if we 2778 // already have one, otherwise create a new one. 2779 return getOrCreateAddExpr(Ops, Flags); 2780 } 2781 2782 const SCEV * 2783 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2784 SCEV::NoWrapFlags Flags) { 2785 FoldingSetNodeID ID; 2786 ID.AddInteger(scAddExpr); 2787 for (const SCEV *Op : Ops) 2788 ID.AddPointer(Op); 2789 void *IP = nullptr; 2790 SCEVAddExpr *S = 2791 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2792 if (!S) { 2793 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2794 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2795 S = new (SCEVAllocator) 2796 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2797 UniqueSCEVs.InsertNode(S, IP); 2798 addToLoopUseLists(S); 2799 } 2800 S->setNoWrapFlags(Flags); 2801 return S; 2802 } 2803 2804 const SCEV * 2805 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2806 const Loop *L, SCEV::NoWrapFlags Flags) { 2807 FoldingSetNodeID ID; 2808 ID.AddInteger(scAddRecExpr); 2809 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2810 ID.AddPointer(Ops[i]); 2811 ID.AddPointer(L); 2812 void *IP = nullptr; 2813 SCEVAddRecExpr *S = 2814 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2815 if (!S) { 2816 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2817 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2818 S = new (SCEVAllocator) 2819 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2820 UniqueSCEVs.InsertNode(S, IP); 2821 addToLoopUseLists(S); 2822 } 2823 S->setNoWrapFlags(Flags); 2824 return S; 2825 } 2826 2827 const SCEV * 2828 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2829 SCEV::NoWrapFlags Flags) { 2830 FoldingSetNodeID ID; 2831 ID.AddInteger(scMulExpr); 2832 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2833 ID.AddPointer(Ops[i]); 2834 void *IP = nullptr; 2835 SCEVMulExpr *S = 2836 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2837 if (!S) { 2838 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2839 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2840 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2841 O, Ops.size()); 2842 UniqueSCEVs.InsertNode(S, IP); 2843 addToLoopUseLists(S); 2844 } 2845 S->setNoWrapFlags(Flags); 2846 return S; 2847 } 2848 2849 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2850 uint64_t k = i*j; 2851 if (j > 1 && k / j != i) Overflow = true; 2852 return k; 2853 } 2854 2855 /// Compute the result of "n choose k", the binomial coefficient. If an 2856 /// intermediate computation overflows, Overflow will be set and the return will 2857 /// be garbage. Overflow is not cleared on absence of overflow. 2858 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2859 // We use the multiplicative formula: 2860 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2861 // At each iteration, we take the n-th term of the numeral and divide by the 2862 // (k-n)th term of the denominator. This division will always produce an 2863 // integral result, and helps reduce the chance of overflow in the 2864 // intermediate computations. However, we can still overflow even when the 2865 // final result would fit. 2866 2867 if (n == 0 || n == k) return 1; 2868 if (k > n) return 0; 2869 2870 if (k > n/2) 2871 k = n-k; 2872 2873 uint64_t r = 1; 2874 for (uint64_t i = 1; i <= k; ++i) { 2875 r = umul_ov(r, n-(i-1), Overflow); 2876 r /= i; 2877 } 2878 return r; 2879 } 2880 2881 /// Determine if any of the operands in this SCEV are a constant or if 2882 /// any of the add or multiply expressions in this SCEV contain a constant. 2883 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2884 struct FindConstantInAddMulChain { 2885 bool FoundConstant = false; 2886 2887 bool follow(const SCEV *S) { 2888 FoundConstant |= isa<SCEVConstant>(S); 2889 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2890 } 2891 2892 bool isDone() const { 2893 return FoundConstant; 2894 } 2895 }; 2896 2897 FindConstantInAddMulChain F; 2898 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2899 ST.visitAll(StartExpr); 2900 return F.FoundConstant; 2901 } 2902 2903 /// Get a canonical multiply expression, or something simpler if possible. 2904 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2905 SCEV::NoWrapFlags Flags, 2906 unsigned Depth) { 2907 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2908 "only nuw or nsw allowed"); 2909 assert(!Ops.empty() && "Cannot get empty mul!"); 2910 if (Ops.size() == 1) return Ops[0]; 2911 #ifndef NDEBUG 2912 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2913 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2914 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2915 "SCEVMulExpr operand types don't match!"); 2916 #endif 2917 2918 // Sort by complexity, this groups all similar expression types together. 2919 GroupByComplexity(Ops, &LI, DT); 2920 2921 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2922 2923 // Limit recursion calls depth. 2924 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2925 return getOrCreateMulExpr(Ops, Flags); 2926 2927 // If there are any constants, fold them together. 2928 unsigned Idx = 0; 2929 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2930 2931 if (Ops.size() == 2) 2932 // C1*(C2+V) -> C1*C2 + C1*V 2933 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2934 // If any of Add's ops are Adds or Muls with a constant, apply this 2935 // transformation as well. 2936 // 2937 // TODO: There are some cases where this transformation is not 2938 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2939 // this transformation should be narrowed down. 2940 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2941 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2942 SCEV::FlagAnyWrap, Depth + 1), 2943 getMulExpr(LHSC, Add->getOperand(1), 2944 SCEV::FlagAnyWrap, Depth + 1), 2945 SCEV::FlagAnyWrap, Depth + 1); 2946 2947 ++Idx; 2948 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2949 // We found two constants, fold them together! 2950 ConstantInt *Fold = 2951 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2952 Ops[0] = getConstant(Fold); 2953 Ops.erase(Ops.begin()+1); // Erase the folded element 2954 if (Ops.size() == 1) return Ops[0]; 2955 LHSC = cast<SCEVConstant>(Ops[0]); 2956 } 2957 2958 // If we are left with a constant one being multiplied, strip it off. 2959 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2960 Ops.erase(Ops.begin()); 2961 --Idx; 2962 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2963 // If we have a multiply of zero, it will always be zero. 2964 return Ops[0]; 2965 } else if (Ops[0]->isAllOnesValue()) { 2966 // If we have a mul by -1 of an add, try distributing the -1 among the 2967 // add operands. 2968 if (Ops.size() == 2) { 2969 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2970 SmallVector<const SCEV *, 4> NewOps; 2971 bool AnyFolded = false; 2972 for (const SCEV *AddOp : Add->operands()) { 2973 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2974 Depth + 1); 2975 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2976 NewOps.push_back(Mul); 2977 } 2978 if (AnyFolded) 2979 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2980 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2981 // Negation preserves a recurrence's no self-wrap property. 2982 SmallVector<const SCEV *, 4> Operands; 2983 for (const SCEV *AddRecOp : AddRec->operands()) 2984 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2985 Depth + 1)); 2986 2987 return getAddRecExpr(Operands, AddRec->getLoop(), 2988 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2989 } 2990 } 2991 } 2992 2993 if (Ops.size() == 1) 2994 return Ops[0]; 2995 } 2996 2997 // Skip over the add expression until we get to a multiply. 2998 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2999 ++Idx; 3000 3001 // If there are mul operands inline them all into this expression. 3002 if (Idx < Ops.size()) { 3003 bool DeletedMul = false; 3004 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3005 if (Ops.size() > MulOpsInlineThreshold) 3006 break; 3007 // If we have an mul, expand the mul operands onto the end of the 3008 // operands list. 3009 Ops.erase(Ops.begin()+Idx); 3010 Ops.append(Mul->op_begin(), Mul->op_end()); 3011 DeletedMul = true; 3012 } 3013 3014 // If we deleted at least one mul, we added operands to the end of the 3015 // list, and they are not necessarily sorted. Recurse to resort and 3016 // resimplify any operands we just acquired. 3017 if (DeletedMul) 3018 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3019 } 3020 3021 // If there are any add recurrences in the operands list, see if any other 3022 // added values are loop invariant. If so, we can fold them into the 3023 // recurrence. 3024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3025 ++Idx; 3026 3027 // Scan over all recurrences, trying to fold loop invariants into them. 3028 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3029 // Scan all of the other operands to this mul and add them to the vector 3030 // if they are loop invariant w.r.t. the recurrence. 3031 SmallVector<const SCEV *, 8> LIOps; 3032 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3033 const Loop *AddRecLoop = AddRec->getLoop(); 3034 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3035 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3036 LIOps.push_back(Ops[i]); 3037 Ops.erase(Ops.begin()+i); 3038 --i; --e; 3039 } 3040 3041 // If we found some loop invariants, fold them into the recurrence. 3042 if (!LIOps.empty()) { 3043 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3044 SmallVector<const SCEV *, 4> NewOps; 3045 NewOps.reserve(AddRec->getNumOperands()); 3046 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3047 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3048 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3049 SCEV::FlagAnyWrap, Depth + 1)); 3050 3051 // Build the new addrec. Propagate the NUW and NSW flags if both the 3052 // outer mul and the inner addrec are guaranteed to have no overflow. 3053 // 3054 // No self-wrap cannot be guaranteed after changing the step size, but 3055 // will be inferred if either NUW or NSW is true. 3056 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3057 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3058 3059 // If all of the other operands were loop invariant, we are done. 3060 if (Ops.size() == 1) return NewRec; 3061 3062 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3063 for (unsigned i = 0;; ++i) 3064 if (Ops[i] == AddRec) { 3065 Ops[i] = NewRec; 3066 break; 3067 } 3068 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3069 } 3070 3071 // Okay, if there weren't any loop invariants to be folded, check to see 3072 // if there are multiple AddRec's with the same loop induction variable 3073 // being multiplied together. If so, we can fold them. 3074 3075 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3076 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3077 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3078 // ]]],+,...up to x=2n}. 3079 // Note that the arguments to choose() are always integers with values 3080 // known at compile time, never SCEV objects. 3081 // 3082 // The implementation avoids pointless extra computations when the two 3083 // addrec's are of different length (mathematically, it's equivalent to 3084 // an infinite stream of zeros on the right). 3085 bool OpsModified = false; 3086 for (unsigned OtherIdx = Idx+1; 3087 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3088 ++OtherIdx) { 3089 const SCEVAddRecExpr *OtherAddRec = 3090 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3091 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3092 continue; 3093 3094 // Limit max number of arguments to avoid creation of unreasonably big 3095 // SCEVAddRecs with very complex operands. 3096 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3097 MaxAddRecSize || isHugeExpression(AddRec) || 3098 isHugeExpression(OtherAddRec)) 3099 continue; 3100 3101 bool Overflow = false; 3102 Type *Ty = AddRec->getType(); 3103 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3104 SmallVector<const SCEV*, 7> AddRecOps; 3105 for (int x = 0, xe = AddRec->getNumOperands() + 3106 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3107 SmallVector <const SCEV *, 7> SumOps; 3108 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3109 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3110 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3111 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3112 z < ze && !Overflow; ++z) { 3113 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3114 uint64_t Coeff; 3115 if (LargerThan64Bits) 3116 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3117 else 3118 Coeff = Coeff1*Coeff2; 3119 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3120 const SCEV *Term1 = AddRec->getOperand(y-z); 3121 const SCEV *Term2 = OtherAddRec->getOperand(z); 3122 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3123 SCEV::FlagAnyWrap, Depth + 1)); 3124 } 3125 } 3126 if (SumOps.empty()) 3127 SumOps.push_back(getZero(Ty)); 3128 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3129 } 3130 if (!Overflow) { 3131 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3132 SCEV::FlagAnyWrap); 3133 if (Ops.size() == 2) return NewAddRec; 3134 Ops[Idx] = NewAddRec; 3135 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3136 OpsModified = true; 3137 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3138 if (!AddRec) 3139 break; 3140 } 3141 } 3142 if (OpsModified) 3143 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3144 3145 // Otherwise couldn't fold anything into this recurrence. Move onto the 3146 // next one. 3147 } 3148 3149 // Okay, it looks like we really DO need an mul expr. Check to see if we 3150 // already have one, otherwise create a new one. 3151 return getOrCreateMulExpr(Ops, Flags); 3152 } 3153 3154 /// Represents an unsigned remainder expression based on unsigned division. 3155 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3156 const SCEV *RHS) { 3157 assert(getEffectiveSCEVType(LHS->getType()) == 3158 getEffectiveSCEVType(RHS->getType()) && 3159 "SCEVURemExpr operand types don't match!"); 3160 3161 // Short-circuit easy cases 3162 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3163 // If constant is one, the result is trivial 3164 if (RHSC->getValue()->isOne()) 3165 return getZero(LHS->getType()); // X urem 1 --> 0 3166 3167 // If constant is a power of two, fold into a zext(trunc(LHS)). 3168 if (RHSC->getAPInt().isPowerOf2()) { 3169 Type *FullTy = LHS->getType(); 3170 Type *TruncTy = 3171 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3172 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3173 } 3174 } 3175 3176 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3177 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3178 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3179 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3180 } 3181 3182 /// Get a canonical unsigned division expression, or something simpler if 3183 /// possible. 3184 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3185 const SCEV *RHS) { 3186 assert(getEffectiveSCEVType(LHS->getType()) == 3187 getEffectiveSCEVType(RHS->getType()) && 3188 "SCEVUDivExpr operand types don't match!"); 3189 3190 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3191 if (RHSC->getValue()->isOne()) 3192 return LHS; // X udiv 1 --> x 3193 // If the denominator is zero, the result of the udiv is undefined. Don't 3194 // try to analyze it, because the resolution chosen here may differ from 3195 // the resolution chosen in other parts of the compiler. 3196 if (!RHSC->getValue()->isZero()) { 3197 // Determine if the division can be folded into the operands of 3198 // its operands. 3199 // TODO: Generalize this to non-constants by using known-bits information. 3200 Type *Ty = LHS->getType(); 3201 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3202 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3203 // For non-power-of-two values, effectively round the value up to the 3204 // nearest power of two. 3205 if (!RHSC->getAPInt().isPowerOf2()) 3206 ++MaxShiftAmt; 3207 IntegerType *ExtTy = 3208 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3209 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3210 if (const SCEVConstant *Step = 3211 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3212 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3213 const APInt &StepInt = Step->getAPInt(); 3214 const APInt &DivInt = RHSC->getAPInt(); 3215 if (!StepInt.urem(DivInt) && 3216 getZeroExtendExpr(AR, ExtTy) == 3217 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3218 getZeroExtendExpr(Step, ExtTy), 3219 AR->getLoop(), SCEV::FlagAnyWrap)) { 3220 SmallVector<const SCEV *, 4> Operands; 3221 for (const SCEV *Op : AR->operands()) 3222 Operands.push_back(getUDivExpr(Op, RHS)); 3223 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3224 } 3225 /// Get a canonical UDivExpr for a recurrence. 3226 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3227 // We can currently only fold X%N if X is constant. 3228 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3229 if (StartC && !DivInt.urem(StepInt) && 3230 getZeroExtendExpr(AR, ExtTy) == 3231 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3232 getZeroExtendExpr(Step, ExtTy), 3233 AR->getLoop(), SCEV::FlagAnyWrap)) { 3234 const APInt &StartInt = StartC->getAPInt(); 3235 const APInt &StartRem = StartInt.urem(StepInt); 3236 if (StartRem != 0) 3237 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3238 AR->getLoop(), SCEV::FlagNW); 3239 } 3240 } 3241 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3242 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3243 SmallVector<const SCEV *, 4> Operands; 3244 for (const SCEV *Op : M->operands()) 3245 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3246 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3247 // Find an operand that's safely divisible. 3248 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3249 const SCEV *Op = M->getOperand(i); 3250 const SCEV *Div = getUDivExpr(Op, RHSC); 3251 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3252 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3253 M->op_end()); 3254 Operands[i] = Div; 3255 return getMulExpr(Operands); 3256 } 3257 } 3258 } 3259 3260 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3261 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3262 if (auto *DivisorConstant = 3263 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3264 bool Overflow = false; 3265 APInt NewRHS = 3266 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3267 if (Overflow) { 3268 return getConstant(RHSC->getType(), 0, false); 3269 } 3270 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3271 } 3272 } 3273 3274 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3275 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3276 SmallVector<const SCEV *, 4> Operands; 3277 for (const SCEV *Op : A->operands()) 3278 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3279 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3280 Operands.clear(); 3281 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3282 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3283 if (isa<SCEVUDivExpr>(Op) || 3284 getMulExpr(Op, RHS) != A->getOperand(i)) 3285 break; 3286 Operands.push_back(Op); 3287 } 3288 if (Operands.size() == A->getNumOperands()) 3289 return getAddExpr(Operands); 3290 } 3291 } 3292 3293 // Fold if both operands are constant. 3294 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3295 Constant *LHSCV = LHSC->getValue(); 3296 Constant *RHSCV = RHSC->getValue(); 3297 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3298 RHSCV))); 3299 } 3300 } 3301 } 3302 3303 FoldingSetNodeID ID; 3304 ID.AddInteger(scUDivExpr); 3305 ID.AddPointer(LHS); 3306 ID.AddPointer(RHS); 3307 void *IP = nullptr; 3308 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3309 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3310 LHS, RHS); 3311 UniqueSCEVs.InsertNode(S, IP); 3312 addToLoopUseLists(S); 3313 return S; 3314 } 3315 3316 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3317 APInt A = C1->getAPInt().abs(); 3318 APInt B = C2->getAPInt().abs(); 3319 uint32_t ABW = A.getBitWidth(); 3320 uint32_t BBW = B.getBitWidth(); 3321 3322 if (ABW > BBW) 3323 B = B.zext(ABW); 3324 else if (ABW < BBW) 3325 A = A.zext(BBW); 3326 3327 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3328 } 3329 3330 /// Get a canonical unsigned division expression, or something simpler if 3331 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3332 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3333 /// it's not exact because the udiv may be clearing bits. 3334 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3335 const SCEV *RHS) { 3336 // TODO: we could try to find factors in all sorts of things, but for now we 3337 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3338 // end of this file for inspiration. 3339 3340 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3341 if (!Mul || !Mul->hasNoUnsignedWrap()) 3342 return getUDivExpr(LHS, RHS); 3343 3344 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3345 // If the mulexpr multiplies by a constant, then that constant must be the 3346 // first element of the mulexpr. 3347 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3348 if (LHSCst == RHSCst) { 3349 SmallVector<const SCEV *, 2> Operands; 3350 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3351 return getMulExpr(Operands); 3352 } 3353 3354 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3355 // that there's a factor provided by one of the other terms. We need to 3356 // check. 3357 APInt Factor = gcd(LHSCst, RHSCst); 3358 if (!Factor.isIntN(1)) { 3359 LHSCst = 3360 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3361 RHSCst = 3362 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3363 SmallVector<const SCEV *, 2> Operands; 3364 Operands.push_back(LHSCst); 3365 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3366 LHS = getMulExpr(Operands); 3367 RHS = RHSCst; 3368 Mul = dyn_cast<SCEVMulExpr>(LHS); 3369 if (!Mul) 3370 return getUDivExactExpr(LHS, RHS); 3371 } 3372 } 3373 } 3374 3375 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3376 if (Mul->getOperand(i) == RHS) { 3377 SmallVector<const SCEV *, 2> Operands; 3378 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3379 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3380 return getMulExpr(Operands); 3381 } 3382 } 3383 3384 return getUDivExpr(LHS, RHS); 3385 } 3386 3387 /// Get an add recurrence expression for the specified loop. Simplify the 3388 /// expression as much as possible. 3389 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3390 const Loop *L, 3391 SCEV::NoWrapFlags Flags) { 3392 SmallVector<const SCEV *, 4> Operands; 3393 Operands.push_back(Start); 3394 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3395 if (StepChrec->getLoop() == L) { 3396 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3397 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3398 } 3399 3400 Operands.push_back(Step); 3401 return getAddRecExpr(Operands, L, Flags); 3402 } 3403 3404 /// Get an add recurrence expression for the specified loop. Simplify the 3405 /// expression as much as possible. 3406 const SCEV * 3407 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3408 const Loop *L, SCEV::NoWrapFlags Flags) { 3409 if (Operands.size() == 1) return Operands[0]; 3410 #ifndef NDEBUG 3411 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3412 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3413 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3414 "SCEVAddRecExpr operand types don't match!"); 3415 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3416 assert(isLoopInvariant(Operands[i], L) && 3417 "SCEVAddRecExpr operand is not loop-invariant!"); 3418 #endif 3419 3420 if (Operands.back()->isZero()) { 3421 Operands.pop_back(); 3422 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3423 } 3424 3425 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3426 // use that information to infer NUW and NSW flags. However, computing a 3427 // BE count requires calling getAddRecExpr, so we may not yet have a 3428 // meaningful BE count at this point (and if we don't, we'd be stuck 3429 // with a SCEVCouldNotCompute as the cached BE count). 3430 3431 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3432 3433 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3434 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3435 const Loop *NestedLoop = NestedAR->getLoop(); 3436 if (L->contains(NestedLoop) 3437 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3438 : (!NestedLoop->contains(L) && 3439 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3440 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3441 NestedAR->op_end()); 3442 Operands[0] = NestedAR->getStart(); 3443 // AddRecs require their operands be loop-invariant with respect to their 3444 // loops. Don't perform this transformation if it would break this 3445 // requirement. 3446 bool AllInvariant = all_of( 3447 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3448 3449 if (AllInvariant) { 3450 // Create a recurrence for the outer loop with the same step size. 3451 // 3452 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3453 // inner recurrence has the same property. 3454 SCEV::NoWrapFlags OuterFlags = 3455 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3456 3457 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3458 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3459 return isLoopInvariant(Op, NestedLoop); 3460 }); 3461 3462 if (AllInvariant) { 3463 // Ok, both add recurrences are valid after the transformation. 3464 // 3465 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3466 // the outer recurrence has the same property. 3467 SCEV::NoWrapFlags InnerFlags = 3468 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3469 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3470 } 3471 } 3472 // Reset Operands to its original state. 3473 Operands[0] = NestedAR; 3474 } 3475 } 3476 3477 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3478 // already have one, otherwise create a new one. 3479 return getOrCreateAddRecExpr(Operands, L, Flags); 3480 } 3481 3482 const SCEV * 3483 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3484 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3485 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3486 // getSCEV(Base)->getType() has the same address space as Base->getType() 3487 // because SCEV::getType() preserves the address space. 3488 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3489 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3490 // instruction to its SCEV, because the Instruction may be guarded by control 3491 // flow and the no-overflow bits may not be valid for the expression in any 3492 // context. This can be fixed similarly to how these flags are handled for 3493 // adds. 3494 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3495 : SCEV::FlagAnyWrap; 3496 3497 const SCEV *TotalOffset = getZero(IntPtrTy); 3498 // The array size is unimportant. The first thing we do on CurTy is getting 3499 // its element type. 3500 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3501 for (const SCEV *IndexExpr : IndexExprs) { 3502 // Compute the (potentially symbolic) offset in bytes for this index. 3503 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3504 // For a struct, add the member offset. 3505 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3506 unsigned FieldNo = Index->getZExtValue(); 3507 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3508 3509 // Add the field offset to the running total offset. 3510 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3511 3512 // Update CurTy to the type of the field at Index. 3513 CurTy = STy->getTypeAtIndex(Index); 3514 } else { 3515 // Update CurTy to its element type. 3516 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3517 // For an array, add the element offset, explicitly scaled. 3518 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3519 // Getelementptr indices are signed. 3520 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3521 3522 // Multiply the index by the element size to compute the element offset. 3523 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3524 3525 // Add the element offset to the running total offset. 3526 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3527 } 3528 } 3529 3530 // Add the total offset from all the GEP indices to the base. 3531 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3532 } 3533 3534 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3535 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3536 ArrayRef<const SCEV *> Ops) { 3537 FoldingSetNodeID ID; 3538 void *IP = nullptr; 3539 ID.AddInteger(SCEVType); 3540 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3541 ID.AddPointer(Ops[i]); 3542 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3543 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3544 } 3545 3546 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3547 SmallVectorImpl<const SCEV *> &Ops) { 3548 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3549 if (Ops.size() == 1) return Ops[0]; 3550 #ifndef NDEBUG 3551 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3552 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3553 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3554 "Operand types don't match!"); 3555 #endif 3556 3557 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3558 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3559 3560 // Sort by complexity, this groups all similar expression types together. 3561 GroupByComplexity(Ops, &LI, DT); 3562 3563 // Check if we have created the same expression before. 3564 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3565 return S; 3566 } 3567 3568 // If there are any constants, fold them together. 3569 unsigned Idx = 0; 3570 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3571 ++Idx; 3572 assert(Idx < Ops.size()); 3573 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3574 if (Kind == scSMaxExpr) 3575 return APIntOps::smax(LHS, RHS); 3576 else if (Kind == scSMinExpr) 3577 return APIntOps::smin(LHS, RHS); 3578 else if (Kind == scUMaxExpr) 3579 return APIntOps::umax(LHS, RHS); 3580 else if (Kind == scUMinExpr) 3581 return APIntOps::umin(LHS, RHS); 3582 llvm_unreachable("Unknown SCEV min/max opcode"); 3583 }; 3584 3585 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3586 // We found two constants, fold them together! 3587 ConstantInt *Fold = ConstantInt::get( 3588 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3589 Ops[0] = getConstant(Fold); 3590 Ops.erase(Ops.begin()+1); // Erase the folded element 3591 if (Ops.size() == 1) return Ops[0]; 3592 LHSC = cast<SCEVConstant>(Ops[0]); 3593 } 3594 3595 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3596 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3597 3598 if (IsMax ? IsMinV : IsMaxV) { 3599 // If we are left with a constant minimum(/maximum)-int, strip it off. 3600 Ops.erase(Ops.begin()); 3601 --Idx; 3602 } else if (IsMax ? IsMaxV : IsMinV) { 3603 // If we have a max(/min) with a constant maximum(/minimum)-int, 3604 // it will always be the extremum. 3605 return LHSC; 3606 } 3607 3608 if (Ops.size() == 1) return Ops[0]; 3609 } 3610 3611 // Find the first operation of the same kind 3612 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3613 ++Idx; 3614 3615 // Check to see if one of the operands is of the same kind. If so, expand its 3616 // operands onto our operand list, and recurse to simplify. 3617 if (Idx < Ops.size()) { 3618 bool DeletedAny = false; 3619 while (Ops[Idx]->getSCEVType() == Kind) { 3620 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3621 Ops.erase(Ops.begin()+Idx); 3622 Ops.append(SMME->op_begin(), SMME->op_end()); 3623 DeletedAny = true; 3624 } 3625 3626 if (DeletedAny) 3627 return getMinMaxExpr(Kind, Ops); 3628 } 3629 3630 // Okay, check to see if the same value occurs in the operand list twice. If 3631 // so, delete one. Since we sorted the list, these values are required to 3632 // be adjacent. 3633 llvm::CmpInst::Predicate GEPred = 3634 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3635 llvm::CmpInst::Predicate LEPred = 3636 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3637 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3638 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3639 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3640 if (Ops[i] == Ops[i + 1] || 3641 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3642 // X op Y op Y --> X op Y 3643 // X op Y --> X, if we know X, Y are ordered appropriately 3644 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3645 --i; 3646 --e; 3647 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3648 Ops[i + 1])) { 3649 // X op Y --> Y, if we know X, Y are ordered appropriately 3650 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3651 --i; 3652 --e; 3653 } 3654 } 3655 3656 if (Ops.size() == 1) return Ops[0]; 3657 3658 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3659 3660 // Okay, it looks like we really DO need an expr. Check to see if we 3661 // already have one, otherwise create a new one. 3662 const SCEV *ExistingSCEV; 3663 FoldingSetNodeID ID; 3664 void *IP; 3665 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3666 if (ExistingSCEV) 3667 return ExistingSCEV; 3668 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3669 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3670 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3671 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3672 3673 UniqueSCEVs.InsertNode(S, IP); 3674 addToLoopUseLists(S); 3675 return S; 3676 } 3677 3678 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3679 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3680 return getSMaxExpr(Ops); 3681 } 3682 3683 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3684 return getMinMaxExpr(scSMaxExpr, Ops); 3685 } 3686 3687 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3688 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3689 return getUMaxExpr(Ops); 3690 } 3691 3692 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3693 return getMinMaxExpr(scUMaxExpr, Ops); 3694 } 3695 3696 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3697 const SCEV *RHS) { 3698 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3699 return getSMinExpr(Ops); 3700 } 3701 3702 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3703 return getMinMaxExpr(scSMinExpr, Ops); 3704 } 3705 3706 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3707 const SCEV *RHS) { 3708 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3709 return getUMinExpr(Ops); 3710 } 3711 3712 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3713 return getMinMaxExpr(scUMinExpr, Ops); 3714 } 3715 3716 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3717 // We can bypass creating a target-independent 3718 // constant expression and then folding it back into a ConstantInt. 3719 // This is just a compile-time optimization. 3720 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3721 } 3722 3723 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3724 StructType *STy, 3725 unsigned FieldNo) { 3726 // We can bypass creating a target-independent 3727 // constant expression and then folding it back into a ConstantInt. 3728 // This is just a compile-time optimization. 3729 return getConstant( 3730 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3731 } 3732 3733 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3734 // Don't attempt to do anything other than create a SCEVUnknown object 3735 // here. createSCEV only calls getUnknown after checking for all other 3736 // interesting possibilities, and any other code that calls getUnknown 3737 // is doing so in order to hide a value from SCEV canonicalization. 3738 3739 FoldingSetNodeID ID; 3740 ID.AddInteger(scUnknown); 3741 ID.AddPointer(V); 3742 void *IP = nullptr; 3743 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3744 assert(cast<SCEVUnknown>(S)->getValue() == V && 3745 "Stale SCEVUnknown in uniquing map!"); 3746 return S; 3747 } 3748 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3749 FirstUnknown); 3750 FirstUnknown = cast<SCEVUnknown>(S); 3751 UniqueSCEVs.InsertNode(S, IP); 3752 return S; 3753 } 3754 3755 //===----------------------------------------------------------------------===// 3756 // Basic SCEV Analysis and PHI Idiom Recognition Code 3757 // 3758 3759 /// Test if values of the given type are analyzable within the SCEV 3760 /// framework. This primarily includes integer types, and it can optionally 3761 /// include pointer types if the ScalarEvolution class has access to 3762 /// target-specific information. 3763 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3764 // Integers and pointers are always SCEVable. 3765 return Ty->isIntOrPtrTy(); 3766 } 3767 3768 /// Return the size in bits of the specified type, for which isSCEVable must 3769 /// return true. 3770 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3771 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3772 if (Ty->isPointerTy()) 3773 return getDataLayout().getIndexTypeSizeInBits(Ty); 3774 return getDataLayout().getTypeSizeInBits(Ty); 3775 } 3776 3777 /// Return a type with the same bitwidth as the given type and which represents 3778 /// how SCEV will treat the given type, for which isSCEVable must return 3779 /// true. For pointer types, this is the pointer-sized integer type. 3780 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3781 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3782 3783 if (Ty->isIntegerTy()) 3784 return Ty; 3785 3786 // The only other support type is pointer. 3787 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3788 return getDataLayout().getIntPtrType(Ty); 3789 } 3790 3791 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3792 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3793 } 3794 3795 const SCEV *ScalarEvolution::getCouldNotCompute() { 3796 return CouldNotCompute.get(); 3797 } 3798 3799 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3800 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3801 auto *SU = dyn_cast<SCEVUnknown>(S); 3802 return SU && SU->getValue() == nullptr; 3803 }); 3804 3805 return !ContainsNulls; 3806 } 3807 3808 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3809 HasRecMapType::iterator I = HasRecMap.find(S); 3810 if (I != HasRecMap.end()) 3811 return I->second; 3812 3813 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3814 HasRecMap.insert({S, FoundAddRec}); 3815 return FoundAddRec; 3816 } 3817 3818 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3819 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3820 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3821 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3822 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3823 if (!Add) 3824 return {S, nullptr}; 3825 3826 if (Add->getNumOperands() != 2) 3827 return {S, nullptr}; 3828 3829 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3830 if (!ConstOp) 3831 return {S, nullptr}; 3832 3833 return {Add->getOperand(1), ConstOp->getValue()}; 3834 } 3835 3836 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3837 /// by the value and offset from any ValueOffsetPair in the set. 3838 SetVector<ScalarEvolution::ValueOffsetPair> * 3839 ScalarEvolution::getSCEVValues(const SCEV *S) { 3840 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3841 if (SI == ExprValueMap.end()) 3842 return nullptr; 3843 #ifndef NDEBUG 3844 if (VerifySCEVMap) { 3845 // Check there is no dangling Value in the set returned. 3846 for (const auto &VE : SI->second) 3847 assert(ValueExprMap.count(VE.first)); 3848 } 3849 #endif 3850 return &SI->second; 3851 } 3852 3853 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3854 /// cannot be used separately. eraseValueFromMap should be used to remove 3855 /// V from ValueExprMap and ExprValueMap at the same time. 3856 void ScalarEvolution::eraseValueFromMap(Value *V) { 3857 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3858 if (I != ValueExprMap.end()) { 3859 const SCEV *S = I->second; 3860 // Remove {V, 0} from the set of ExprValueMap[S] 3861 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3862 SV->remove({V, nullptr}); 3863 3864 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3865 const SCEV *Stripped; 3866 ConstantInt *Offset; 3867 std::tie(Stripped, Offset) = splitAddExpr(S); 3868 if (Offset != nullptr) { 3869 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3870 SV->remove({V, Offset}); 3871 } 3872 ValueExprMap.erase(V); 3873 } 3874 } 3875 3876 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3877 /// TODO: In reality it is better to check the poison recursively 3878 /// but this is better than nothing. 3879 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3880 if (auto *I = dyn_cast<Instruction>(V)) { 3881 if (isa<OverflowingBinaryOperator>(I)) { 3882 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3883 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3884 return true; 3885 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3886 return true; 3887 } 3888 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3889 return true; 3890 } 3891 return false; 3892 } 3893 3894 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3895 /// create a new one. 3896 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3897 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3898 3899 const SCEV *S = getExistingSCEV(V); 3900 if (S == nullptr) { 3901 S = createSCEV(V); 3902 // During PHI resolution, it is possible to create two SCEVs for the same 3903 // V, so it is needed to double check whether V->S is inserted into 3904 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3905 std::pair<ValueExprMapType::iterator, bool> Pair = 3906 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3907 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3908 ExprValueMap[S].insert({V, nullptr}); 3909 3910 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3911 // ExprValueMap. 3912 const SCEV *Stripped = S; 3913 ConstantInt *Offset = nullptr; 3914 std::tie(Stripped, Offset) = splitAddExpr(S); 3915 // If stripped is SCEVUnknown, don't bother to save 3916 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3917 // increase the complexity of the expansion code. 3918 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3919 // because it may generate add/sub instead of GEP in SCEV expansion. 3920 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3921 !isa<GetElementPtrInst>(V)) 3922 ExprValueMap[Stripped].insert({V, Offset}); 3923 } 3924 } 3925 return S; 3926 } 3927 3928 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3929 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3930 3931 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3932 if (I != ValueExprMap.end()) { 3933 const SCEV *S = I->second; 3934 if (checkValidity(S)) 3935 return S; 3936 eraseValueFromMap(V); 3937 forgetMemoizedResults(S); 3938 } 3939 return nullptr; 3940 } 3941 3942 /// Return a SCEV corresponding to -V = -1*V 3943 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3944 SCEV::NoWrapFlags Flags) { 3945 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3946 return getConstant( 3947 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3948 3949 Type *Ty = V->getType(); 3950 Ty = getEffectiveSCEVType(Ty); 3951 return getMulExpr( 3952 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3953 } 3954 3955 /// If Expr computes ~A, return A else return nullptr 3956 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3957 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3958 if (!Add || Add->getNumOperands() != 2 || 3959 !Add->getOperand(0)->isAllOnesValue()) 3960 return nullptr; 3961 3962 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3963 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3964 !AddRHS->getOperand(0)->isAllOnesValue()) 3965 return nullptr; 3966 3967 return AddRHS->getOperand(1); 3968 } 3969 3970 /// Return a SCEV corresponding to ~V = -1-V 3971 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3972 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3973 return getConstant( 3974 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3975 3976 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3977 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3978 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3979 SmallVector<const SCEV *, 2> MatchedOperands; 3980 for (const SCEV *Operand : MME->operands()) { 3981 const SCEV *Matched = MatchNotExpr(Operand); 3982 if (!Matched) 3983 return (const SCEV *)nullptr; 3984 MatchedOperands.push_back(Matched); 3985 } 3986 return getMinMaxExpr( 3987 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3988 MatchedOperands); 3989 }; 3990 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3991 return Replaced; 3992 } 3993 3994 Type *Ty = V->getType(); 3995 Ty = getEffectiveSCEVType(Ty); 3996 const SCEV *AllOnes = 3997 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3998 return getMinusSCEV(AllOnes, V); 3999 } 4000 4001 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4002 SCEV::NoWrapFlags Flags, 4003 unsigned Depth) { 4004 // Fast path: X - X --> 0. 4005 if (LHS == RHS) 4006 return getZero(LHS->getType()); 4007 4008 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4009 // makes it so that we cannot make much use of NUW. 4010 auto AddFlags = SCEV::FlagAnyWrap; 4011 const bool RHSIsNotMinSigned = 4012 !getSignedRangeMin(RHS).isMinSignedValue(); 4013 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4014 // Let M be the minimum representable signed value. Then (-1)*RHS 4015 // signed-wraps if and only if RHS is M. That can happen even for 4016 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4017 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4018 // (-1)*RHS, we need to prove that RHS != M. 4019 // 4020 // If LHS is non-negative and we know that LHS - RHS does not 4021 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4022 // either by proving that RHS > M or that LHS >= 0. 4023 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4024 AddFlags = SCEV::FlagNSW; 4025 } 4026 } 4027 4028 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4029 // RHS is NSW and LHS >= 0. 4030 // 4031 // The difficulty here is that the NSW flag may have been proven 4032 // relative to a loop that is to be found in a recurrence in LHS and 4033 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4034 // larger scope than intended. 4035 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4036 4037 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4038 } 4039 4040 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4041 unsigned Depth) { 4042 Type *SrcTy = V->getType(); 4043 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4044 "Cannot truncate or zero extend with non-integer arguments!"); 4045 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4046 return V; // No conversion 4047 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4048 return getTruncateExpr(V, Ty, Depth); 4049 return getZeroExtendExpr(V, Ty, Depth); 4050 } 4051 4052 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4053 unsigned Depth) { 4054 Type *SrcTy = V->getType(); 4055 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4056 "Cannot truncate or zero extend with non-integer arguments!"); 4057 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4058 return V; // No conversion 4059 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4060 return getTruncateExpr(V, Ty, Depth); 4061 return getSignExtendExpr(V, Ty, Depth); 4062 } 4063 4064 const SCEV * 4065 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4066 Type *SrcTy = V->getType(); 4067 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4068 "Cannot noop or zero extend with non-integer arguments!"); 4069 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4070 "getNoopOrZeroExtend cannot truncate!"); 4071 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4072 return V; // No conversion 4073 return getZeroExtendExpr(V, Ty); 4074 } 4075 4076 const SCEV * 4077 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4078 Type *SrcTy = V->getType(); 4079 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4080 "Cannot noop or sign extend with non-integer arguments!"); 4081 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4082 "getNoopOrSignExtend cannot truncate!"); 4083 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4084 return V; // No conversion 4085 return getSignExtendExpr(V, Ty); 4086 } 4087 4088 const SCEV * 4089 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4090 Type *SrcTy = V->getType(); 4091 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4092 "Cannot noop or any extend with non-integer arguments!"); 4093 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4094 "getNoopOrAnyExtend cannot truncate!"); 4095 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4096 return V; // No conversion 4097 return getAnyExtendExpr(V, Ty); 4098 } 4099 4100 const SCEV * 4101 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4102 Type *SrcTy = V->getType(); 4103 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4104 "Cannot truncate or noop with non-integer arguments!"); 4105 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4106 "getTruncateOrNoop cannot extend!"); 4107 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4108 return V; // No conversion 4109 return getTruncateExpr(V, Ty); 4110 } 4111 4112 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4113 const SCEV *RHS) { 4114 const SCEV *PromotedLHS = LHS; 4115 const SCEV *PromotedRHS = RHS; 4116 4117 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4118 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4119 else 4120 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4121 4122 return getUMaxExpr(PromotedLHS, PromotedRHS); 4123 } 4124 4125 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4126 const SCEV *RHS) { 4127 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4128 return getUMinFromMismatchedTypes(Ops); 4129 } 4130 4131 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4132 SmallVectorImpl<const SCEV *> &Ops) { 4133 assert(!Ops.empty() && "At least one operand must be!"); 4134 // Trivial case. 4135 if (Ops.size() == 1) 4136 return Ops[0]; 4137 4138 // Find the max type first. 4139 Type *MaxType = nullptr; 4140 for (auto *S : Ops) 4141 if (MaxType) 4142 MaxType = getWiderType(MaxType, S->getType()); 4143 else 4144 MaxType = S->getType(); 4145 4146 // Extend all ops to max type. 4147 SmallVector<const SCEV *, 2> PromotedOps; 4148 for (auto *S : Ops) 4149 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4150 4151 // Generate umin. 4152 return getUMinExpr(PromotedOps); 4153 } 4154 4155 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4156 // A pointer operand may evaluate to a nonpointer expression, such as null. 4157 if (!V->getType()->isPointerTy()) 4158 return V; 4159 4160 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4161 return getPointerBase(Cast->getOperand()); 4162 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4163 const SCEV *PtrOp = nullptr; 4164 for (const SCEV *NAryOp : NAry->operands()) { 4165 if (NAryOp->getType()->isPointerTy()) { 4166 // Cannot find the base of an expression with multiple pointer operands. 4167 if (PtrOp) 4168 return V; 4169 PtrOp = NAryOp; 4170 } 4171 } 4172 if (!PtrOp) 4173 return V; 4174 return getPointerBase(PtrOp); 4175 } 4176 return V; 4177 } 4178 4179 /// Push users of the given Instruction onto the given Worklist. 4180 static void 4181 PushDefUseChildren(Instruction *I, 4182 SmallVectorImpl<Instruction *> &Worklist) { 4183 // Push the def-use children onto the Worklist stack. 4184 for (User *U : I->users()) 4185 Worklist.push_back(cast<Instruction>(U)); 4186 } 4187 4188 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4189 SmallVector<Instruction *, 16> Worklist; 4190 PushDefUseChildren(PN, Worklist); 4191 4192 SmallPtrSet<Instruction *, 8> Visited; 4193 Visited.insert(PN); 4194 while (!Worklist.empty()) { 4195 Instruction *I = Worklist.pop_back_val(); 4196 if (!Visited.insert(I).second) 4197 continue; 4198 4199 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4200 if (It != ValueExprMap.end()) { 4201 const SCEV *Old = It->second; 4202 4203 // Short-circuit the def-use traversal if the symbolic name 4204 // ceases to appear in expressions. 4205 if (Old != SymName && !hasOperand(Old, SymName)) 4206 continue; 4207 4208 // SCEVUnknown for a PHI either means that it has an unrecognized 4209 // structure, it's a PHI that's in the progress of being computed 4210 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4211 // additional loop trip count information isn't going to change anything. 4212 // In the second case, createNodeForPHI will perform the necessary 4213 // updates on its own when it gets to that point. In the third, we do 4214 // want to forget the SCEVUnknown. 4215 if (!isa<PHINode>(I) || 4216 !isa<SCEVUnknown>(Old) || 4217 (I != PN && Old == SymName)) { 4218 eraseValueFromMap(It->first); 4219 forgetMemoizedResults(Old); 4220 } 4221 } 4222 4223 PushDefUseChildren(I, Worklist); 4224 } 4225 } 4226 4227 namespace { 4228 4229 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4230 /// expression in case its Loop is L. If it is not L then 4231 /// if IgnoreOtherLoops is true then use AddRec itself 4232 /// otherwise rewrite cannot be done. 4233 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4234 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4235 public: 4236 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4237 bool IgnoreOtherLoops = true) { 4238 SCEVInitRewriter Rewriter(L, SE); 4239 const SCEV *Result = Rewriter.visit(S); 4240 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4241 return SE.getCouldNotCompute(); 4242 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4243 ? SE.getCouldNotCompute() 4244 : Result; 4245 } 4246 4247 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4248 if (!SE.isLoopInvariant(Expr, L)) 4249 SeenLoopVariantSCEVUnknown = true; 4250 return Expr; 4251 } 4252 4253 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4254 // Only re-write AddRecExprs for this loop. 4255 if (Expr->getLoop() == L) 4256 return Expr->getStart(); 4257 SeenOtherLoops = true; 4258 return Expr; 4259 } 4260 4261 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4262 4263 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4264 4265 private: 4266 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4267 : SCEVRewriteVisitor(SE), L(L) {} 4268 4269 const Loop *L; 4270 bool SeenLoopVariantSCEVUnknown = false; 4271 bool SeenOtherLoops = false; 4272 }; 4273 4274 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4275 /// increment expression in case its Loop is L. If it is not L then 4276 /// use AddRec itself. 4277 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4278 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4279 public: 4280 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4281 SCEVPostIncRewriter Rewriter(L, SE); 4282 const SCEV *Result = Rewriter.visit(S); 4283 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4284 ? SE.getCouldNotCompute() 4285 : Result; 4286 } 4287 4288 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4289 if (!SE.isLoopInvariant(Expr, L)) 4290 SeenLoopVariantSCEVUnknown = true; 4291 return Expr; 4292 } 4293 4294 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4295 // Only re-write AddRecExprs for this loop. 4296 if (Expr->getLoop() == L) 4297 return Expr->getPostIncExpr(SE); 4298 SeenOtherLoops = true; 4299 return Expr; 4300 } 4301 4302 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4303 4304 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4305 4306 private: 4307 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4308 : SCEVRewriteVisitor(SE), L(L) {} 4309 4310 const Loop *L; 4311 bool SeenLoopVariantSCEVUnknown = false; 4312 bool SeenOtherLoops = false; 4313 }; 4314 4315 /// This class evaluates the compare condition by matching it against the 4316 /// condition of loop latch. If there is a match we assume a true value 4317 /// for the condition while building SCEV nodes. 4318 class SCEVBackedgeConditionFolder 4319 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4320 public: 4321 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4322 ScalarEvolution &SE) { 4323 bool IsPosBECond = false; 4324 Value *BECond = nullptr; 4325 if (BasicBlock *Latch = L->getLoopLatch()) { 4326 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4327 if (BI && BI->isConditional()) { 4328 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4329 "Both outgoing branches should not target same header!"); 4330 BECond = BI->getCondition(); 4331 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4332 } else { 4333 return S; 4334 } 4335 } 4336 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4337 return Rewriter.visit(S); 4338 } 4339 4340 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4341 const SCEV *Result = Expr; 4342 bool InvariantF = SE.isLoopInvariant(Expr, L); 4343 4344 if (!InvariantF) { 4345 Instruction *I = cast<Instruction>(Expr->getValue()); 4346 switch (I->getOpcode()) { 4347 case Instruction::Select: { 4348 SelectInst *SI = cast<SelectInst>(I); 4349 Optional<const SCEV *> Res = 4350 compareWithBackedgeCondition(SI->getCondition()); 4351 if (Res.hasValue()) { 4352 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4353 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4354 } 4355 break; 4356 } 4357 default: { 4358 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4359 if (Res.hasValue()) 4360 Result = Res.getValue(); 4361 break; 4362 } 4363 } 4364 } 4365 return Result; 4366 } 4367 4368 private: 4369 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4370 bool IsPosBECond, ScalarEvolution &SE) 4371 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4372 IsPositiveBECond(IsPosBECond) {} 4373 4374 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4375 4376 const Loop *L; 4377 /// Loop back condition. 4378 Value *BackedgeCond = nullptr; 4379 /// Set to true if loop back is on positive branch condition. 4380 bool IsPositiveBECond; 4381 }; 4382 4383 Optional<const SCEV *> 4384 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4385 4386 // If value matches the backedge condition for loop latch, 4387 // then return a constant evolution node based on loopback 4388 // branch taken. 4389 if (BackedgeCond == IC) 4390 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4391 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4392 return None; 4393 } 4394 4395 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4396 public: 4397 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4398 ScalarEvolution &SE) { 4399 SCEVShiftRewriter Rewriter(L, SE); 4400 const SCEV *Result = Rewriter.visit(S); 4401 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4402 } 4403 4404 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4405 // Only allow AddRecExprs for this loop. 4406 if (!SE.isLoopInvariant(Expr, L)) 4407 Valid = false; 4408 return Expr; 4409 } 4410 4411 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4412 if (Expr->getLoop() == L && Expr->isAffine()) 4413 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4414 Valid = false; 4415 return Expr; 4416 } 4417 4418 bool isValid() { return Valid; } 4419 4420 private: 4421 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4422 : SCEVRewriteVisitor(SE), L(L) {} 4423 4424 const Loop *L; 4425 bool Valid = true; 4426 }; 4427 4428 } // end anonymous namespace 4429 4430 SCEV::NoWrapFlags 4431 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4432 if (!AR->isAffine()) 4433 return SCEV::FlagAnyWrap; 4434 4435 using OBO = OverflowingBinaryOperator; 4436 4437 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4438 4439 if (!AR->hasNoSignedWrap()) { 4440 ConstantRange AddRecRange = getSignedRange(AR); 4441 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4442 4443 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4444 Instruction::Add, IncRange, OBO::NoSignedWrap); 4445 if (NSWRegion.contains(AddRecRange)) 4446 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4447 } 4448 4449 if (!AR->hasNoUnsignedWrap()) { 4450 ConstantRange AddRecRange = getUnsignedRange(AR); 4451 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4452 4453 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4454 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4455 if (NUWRegion.contains(AddRecRange)) 4456 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4457 } 4458 4459 return Result; 4460 } 4461 4462 namespace { 4463 4464 /// Represents an abstract binary operation. This may exist as a 4465 /// normal instruction or constant expression, or may have been 4466 /// derived from an expression tree. 4467 struct BinaryOp { 4468 unsigned Opcode; 4469 Value *LHS; 4470 Value *RHS; 4471 bool IsNSW = false; 4472 bool IsNUW = false; 4473 4474 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4475 /// constant expression. 4476 Operator *Op = nullptr; 4477 4478 explicit BinaryOp(Operator *Op) 4479 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4480 Op(Op) { 4481 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4482 IsNSW = OBO->hasNoSignedWrap(); 4483 IsNUW = OBO->hasNoUnsignedWrap(); 4484 } 4485 } 4486 4487 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4488 bool IsNUW = false) 4489 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4490 }; 4491 4492 } // end anonymous namespace 4493 4494 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4495 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4496 auto *Op = dyn_cast<Operator>(V); 4497 if (!Op) 4498 return None; 4499 4500 // Implementation detail: all the cleverness here should happen without 4501 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4502 // SCEV expressions when possible, and we should not break that. 4503 4504 switch (Op->getOpcode()) { 4505 case Instruction::Add: 4506 case Instruction::Sub: 4507 case Instruction::Mul: 4508 case Instruction::UDiv: 4509 case Instruction::URem: 4510 case Instruction::And: 4511 case Instruction::Or: 4512 case Instruction::AShr: 4513 case Instruction::Shl: 4514 return BinaryOp(Op); 4515 4516 case Instruction::Xor: 4517 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4518 // If the RHS of the xor is a signmask, then this is just an add. 4519 // Instcombine turns add of signmask into xor as a strength reduction step. 4520 if (RHSC->getValue().isSignMask()) 4521 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4522 return BinaryOp(Op); 4523 4524 case Instruction::LShr: 4525 // Turn logical shift right of a constant into a unsigned divide. 4526 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4527 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4528 4529 // If the shift count is not less than the bitwidth, the result of 4530 // the shift is undefined. Don't try to analyze it, because the 4531 // resolution chosen here may differ from the resolution chosen in 4532 // other parts of the compiler. 4533 if (SA->getValue().ult(BitWidth)) { 4534 Constant *X = 4535 ConstantInt::get(SA->getContext(), 4536 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4537 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4538 } 4539 } 4540 return BinaryOp(Op); 4541 4542 case Instruction::ExtractValue: { 4543 auto *EVI = cast<ExtractValueInst>(Op); 4544 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4545 break; 4546 4547 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4548 if (!WO) 4549 break; 4550 4551 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4552 bool Signed = WO->isSigned(); 4553 // TODO: Should add nuw/nsw flags for mul as well. 4554 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4555 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4556 4557 // Now that we know that all uses of the arithmetic-result component of 4558 // CI are guarded by the overflow check, we can go ahead and pretend 4559 // that the arithmetic is non-overflowing. 4560 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4561 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4562 } 4563 4564 default: 4565 break; 4566 } 4567 4568 return None; 4569 } 4570 4571 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4572 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4573 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4574 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4575 /// follows one of the following patterns: 4576 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4577 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4578 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4579 /// we return the type of the truncation operation, and indicate whether the 4580 /// truncated type should be treated as signed/unsigned by setting 4581 /// \p Signed to true/false, respectively. 4582 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4583 bool &Signed, ScalarEvolution &SE) { 4584 // The case where Op == SymbolicPHI (that is, with no type conversions on 4585 // the way) is handled by the regular add recurrence creating logic and 4586 // would have already been triggered in createAddRecForPHI. Reaching it here 4587 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4588 // because one of the other operands of the SCEVAddExpr updating this PHI is 4589 // not invariant). 4590 // 4591 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4592 // this case predicates that allow us to prove that Op == SymbolicPHI will 4593 // be added. 4594 if (Op == SymbolicPHI) 4595 return nullptr; 4596 4597 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4598 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4599 if (SourceBits != NewBits) 4600 return nullptr; 4601 4602 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4603 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4604 if (!SExt && !ZExt) 4605 return nullptr; 4606 const SCEVTruncateExpr *Trunc = 4607 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4608 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4609 if (!Trunc) 4610 return nullptr; 4611 const SCEV *X = Trunc->getOperand(); 4612 if (X != SymbolicPHI) 4613 return nullptr; 4614 Signed = SExt != nullptr; 4615 return Trunc->getType(); 4616 } 4617 4618 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4619 if (!PN->getType()->isIntegerTy()) 4620 return nullptr; 4621 const Loop *L = LI.getLoopFor(PN->getParent()); 4622 if (!L || L->getHeader() != PN->getParent()) 4623 return nullptr; 4624 return L; 4625 } 4626 4627 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4628 // computation that updates the phi follows the following pattern: 4629 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4630 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4631 // If so, try to see if it can be rewritten as an AddRecExpr under some 4632 // Predicates. If successful, return them as a pair. Also cache the results 4633 // of the analysis. 4634 // 4635 // Example usage scenario: 4636 // Say the Rewriter is called for the following SCEV: 4637 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4638 // where: 4639 // %X = phi i64 (%Start, %BEValue) 4640 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4641 // and call this function with %SymbolicPHI = %X. 4642 // 4643 // The analysis will find that the value coming around the backedge has 4644 // the following SCEV: 4645 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4646 // Upon concluding that this matches the desired pattern, the function 4647 // will return the pair {NewAddRec, SmallPredsVec} where: 4648 // NewAddRec = {%Start,+,%Step} 4649 // SmallPredsVec = {P1, P2, P3} as follows: 4650 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4651 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4652 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4653 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4654 // under the predicates {P1,P2,P3}. 4655 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4656 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4657 // 4658 // TODO's: 4659 // 4660 // 1) Extend the Induction descriptor to also support inductions that involve 4661 // casts: When needed (namely, when we are called in the context of the 4662 // vectorizer induction analysis), a Set of cast instructions will be 4663 // populated by this method, and provided back to isInductionPHI. This is 4664 // needed to allow the vectorizer to properly record them to be ignored by 4665 // the cost model and to avoid vectorizing them (otherwise these casts, 4666 // which are redundant under the runtime overflow checks, will be 4667 // vectorized, which can be costly). 4668 // 4669 // 2) Support additional induction/PHISCEV patterns: We also want to support 4670 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4671 // after the induction update operation (the induction increment): 4672 // 4673 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4674 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4675 // 4676 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4677 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4678 // 4679 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4680 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4681 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4682 SmallVector<const SCEVPredicate *, 3> Predicates; 4683 4684 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4685 // return an AddRec expression under some predicate. 4686 4687 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4688 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4689 assert(L && "Expecting an integer loop header phi"); 4690 4691 // The loop may have multiple entrances or multiple exits; we can analyze 4692 // this phi as an addrec if it has a unique entry value and a unique 4693 // backedge value. 4694 Value *BEValueV = nullptr, *StartValueV = nullptr; 4695 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4696 Value *V = PN->getIncomingValue(i); 4697 if (L->contains(PN->getIncomingBlock(i))) { 4698 if (!BEValueV) { 4699 BEValueV = V; 4700 } else if (BEValueV != V) { 4701 BEValueV = nullptr; 4702 break; 4703 } 4704 } else if (!StartValueV) { 4705 StartValueV = V; 4706 } else if (StartValueV != V) { 4707 StartValueV = nullptr; 4708 break; 4709 } 4710 } 4711 if (!BEValueV || !StartValueV) 4712 return None; 4713 4714 const SCEV *BEValue = getSCEV(BEValueV); 4715 4716 // If the value coming around the backedge is an add with the symbolic 4717 // value we just inserted, possibly with casts that we can ignore under 4718 // an appropriate runtime guard, then we found a simple induction variable! 4719 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4720 if (!Add) 4721 return None; 4722 4723 // If there is a single occurrence of the symbolic value, possibly 4724 // casted, replace it with a recurrence. 4725 unsigned FoundIndex = Add->getNumOperands(); 4726 Type *TruncTy = nullptr; 4727 bool Signed; 4728 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4729 if ((TruncTy = 4730 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4731 if (FoundIndex == e) { 4732 FoundIndex = i; 4733 break; 4734 } 4735 4736 if (FoundIndex == Add->getNumOperands()) 4737 return None; 4738 4739 // Create an add with everything but the specified operand. 4740 SmallVector<const SCEV *, 8> Ops; 4741 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4742 if (i != FoundIndex) 4743 Ops.push_back(Add->getOperand(i)); 4744 const SCEV *Accum = getAddExpr(Ops); 4745 4746 // The runtime checks will not be valid if the step amount is 4747 // varying inside the loop. 4748 if (!isLoopInvariant(Accum, L)) 4749 return None; 4750 4751 // *** Part2: Create the predicates 4752 4753 // Analysis was successful: we have a phi-with-cast pattern for which we 4754 // can return an AddRec expression under the following predicates: 4755 // 4756 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4757 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4758 // P2: An Equal predicate that guarantees that 4759 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4760 // P3: An Equal predicate that guarantees that 4761 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4762 // 4763 // As we next prove, the above predicates guarantee that: 4764 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4765 // 4766 // 4767 // More formally, we want to prove that: 4768 // Expr(i+1) = Start + (i+1) * Accum 4769 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4770 // 4771 // Given that: 4772 // 1) Expr(0) = Start 4773 // 2) Expr(1) = Start + Accum 4774 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4775 // 3) Induction hypothesis (step i): 4776 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4777 // 4778 // Proof: 4779 // Expr(i+1) = 4780 // = Start + (i+1)*Accum 4781 // = (Start + i*Accum) + Accum 4782 // = Expr(i) + Accum 4783 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4784 // :: from step i 4785 // 4786 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4787 // 4788 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4789 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4790 // + Accum :: from P3 4791 // 4792 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4793 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4794 // 4795 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4796 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4797 // 4798 // By induction, the same applies to all iterations 1<=i<n: 4799 // 4800 4801 // Create a truncated addrec for which we will add a no overflow check (P1). 4802 const SCEV *StartVal = getSCEV(StartValueV); 4803 const SCEV *PHISCEV = 4804 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4805 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4806 4807 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4808 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4809 // will be constant. 4810 // 4811 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4812 // add P1. 4813 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4814 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4815 Signed ? SCEVWrapPredicate::IncrementNSSW 4816 : SCEVWrapPredicate::IncrementNUSW; 4817 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4818 Predicates.push_back(AddRecPred); 4819 } 4820 4821 // Create the Equal Predicates P2,P3: 4822 4823 // It is possible that the predicates P2 and/or P3 are computable at 4824 // compile time due to StartVal and/or Accum being constants. 4825 // If either one is, then we can check that now and escape if either P2 4826 // or P3 is false. 4827 4828 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4829 // for each of StartVal and Accum 4830 auto getExtendedExpr = [&](const SCEV *Expr, 4831 bool CreateSignExtend) -> const SCEV * { 4832 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4833 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4834 const SCEV *ExtendedExpr = 4835 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4836 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4837 return ExtendedExpr; 4838 }; 4839 4840 // Given: 4841 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4842 // = getExtendedExpr(Expr) 4843 // Determine whether the predicate P: Expr == ExtendedExpr 4844 // is known to be false at compile time 4845 auto PredIsKnownFalse = [&](const SCEV *Expr, 4846 const SCEV *ExtendedExpr) -> bool { 4847 return Expr != ExtendedExpr && 4848 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4849 }; 4850 4851 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4852 if (PredIsKnownFalse(StartVal, StartExtended)) { 4853 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4854 return None; 4855 } 4856 4857 // The Step is always Signed (because the overflow checks are either 4858 // NSSW or NUSW) 4859 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4860 if (PredIsKnownFalse(Accum, AccumExtended)) { 4861 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4862 return None; 4863 } 4864 4865 auto AppendPredicate = [&](const SCEV *Expr, 4866 const SCEV *ExtendedExpr) -> void { 4867 if (Expr != ExtendedExpr && 4868 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4869 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4870 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4871 Predicates.push_back(Pred); 4872 } 4873 }; 4874 4875 AppendPredicate(StartVal, StartExtended); 4876 AppendPredicate(Accum, AccumExtended); 4877 4878 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4879 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4880 // into NewAR if it will also add the runtime overflow checks specified in 4881 // Predicates. 4882 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4883 4884 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4885 std::make_pair(NewAR, Predicates); 4886 // Remember the result of the analysis for this SCEV at this locayyytion. 4887 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4888 return PredRewrite; 4889 } 4890 4891 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4892 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4893 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4894 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4895 if (!L) 4896 return None; 4897 4898 // Check to see if we already analyzed this PHI. 4899 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4900 if (I != PredicatedSCEVRewrites.end()) { 4901 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4902 I->second; 4903 // Analysis was done before and failed to create an AddRec: 4904 if (Rewrite.first == SymbolicPHI) 4905 return None; 4906 // Analysis was done before and succeeded to create an AddRec under 4907 // a predicate: 4908 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4909 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4910 return Rewrite; 4911 } 4912 4913 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4914 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4915 4916 // Record in the cache that the analysis failed 4917 if (!Rewrite) { 4918 SmallVector<const SCEVPredicate *, 3> Predicates; 4919 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4920 return None; 4921 } 4922 4923 return Rewrite; 4924 } 4925 4926 // FIXME: This utility is currently required because the Rewriter currently 4927 // does not rewrite this expression: 4928 // {0, +, (sext ix (trunc iy to ix) to iy)} 4929 // into {0, +, %step}, 4930 // even when the following Equal predicate exists: 4931 // "%step == (sext ix (trunc iy to ix) to iy)". 4932 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4933 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4934 if (AR1 == AR2) 4935 return true; 4936 4937 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4938 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4939 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4940 return false; 4941 return true; 4942 }; 4943 4944 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4945 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4946 return false; 4947 return true; 4948 } 4949 4950 /// A helper function for createAddRecFromPHI to handle simple cases. 4951 /// 4952 /// This function tries to find an AddRec expression for the simplest (yet most 4953 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4954 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4955 /// technique for finding the AddRec expression. 4956 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4957 Value *BEValueV, 4958 Value *StartValueV) { 4959 const Loop *L = LI.getLoopFor(PN->getParent()); 4960 assert(L && L->getHeader() == PN->getParent()); 4961 assert(BEValueV && StartValueV); 4962 4963 auto BO = MatchBinaryOp(BEValueV, DT); 4964 if (!BO) 4965 return nullptr; 4966 4967 if (BO->Opcode != Instruction::Add) 4968 return nullptr; 4969 4970 const SCEV *Accum = nullptr; 4971 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4972 Accum = getSCEV(BO->RHS); 4973 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4974 Accum = getSCEV(BO->LHS); 4975 4976 if (!Accum) 4977 return nullptr; 4978 4979 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4980 if (BO->IsNUW) 4981 Flags = setFlags(Flags, SCEV::FlagNUW); 4982 if (BO->IsNSW) 4983 Flags = setFlags(Flags, SCEV::FlagNSW); 4984 4985 const SCEV *StartVal = getSCEV(StartValueV); 4986 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4987 4988 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4989 4990 // We can add Flags to the post-inc expression only if we 4991 // know that it is *undefined behavior* for BEValueV to 4992 // overflow. 4993 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4994 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4995 (void)getAddRecExpr(getAddExpr(StartVal, Accum, Flags), Accum, L, Flags); 4996 4997 return PHISCEV; 4998 } 4999 5000 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5001 const Loop *L = LI.getLoopFor(PN->getParent()); 5002 if (!L || L->getHeader() != PN->getParent()) 5003 return nullptr; 5004 5005 // The loop may have multiple entrances or multiple exits; we can analyze 5006 // this phi as an addrec if it has a unique entry value and a unique 5007 // backedge value. 5008 Value *BEValueV = nullptr, *StartValueV = nullptr; 5009 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5010 Value *V = PN->getIncomingValue(i); 5011 if (L->contains(PN->getIncomingBlock(i))) { 5012 if (!BEValueV) { 5013 BEValueV = V; 5014 } else if (BEValueV != V) { 5015 BEValueV = nullptr; 5016 break; 5017 } 5018 } else if (!StartValueV) { 5019 StartValueV = V; 5020 } else if (StartValueV != V) { 5021 StartValueV = nullptr; 5022 break; 5023 } 5024 } 5025 if (!BEValueV || !StartValueV) 5026 return nullptr; 5027 5028 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5029 "PHI node already processed?"); 5030 5031 // First, try to find AddRec expression without creating a fictituos symbolic 5032 // value for PN. 5033 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5034 return S; 5035 5036 // Handle PHI node value symbolically. 5037 const SCEV *SymbolicName = getUnknown(PN); 5038 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5039 5040 // Using this symbolic name for the PHI, analyze the value coming around 5041 // the back-edge. 5042 const SCEV *BEValue = getSCEV(BEValueV); 5043 5044 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5045 // has a special value for the first iteration of the loop. 5046 5047 // If the value coming around the backedge is an add with the symbolic 5048 // value we just inserted, then we found a simple induction variable! 5049 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5050 // If there is a single occurrence of the symbolic value, replace it 5051 // with a recurrence. 5052 unsigned FoundIndex = Add->getNumOperands(); 5053 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5054 if (Add->getOperand(i) == SymbolicName) 5055 if (FoundIndex == e) { 5056 FoundIndex = i; 5057 break; 5058 } 5059 5060 if (FoundIndex != Add->getNumOperands()) { 5061 // Create an add with everything but the specified operand. 5062 SmallVector<const SCEV *, 8> Ops; 5063 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5064 if (i != FoundIndex) 5065 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5066 L, *this)); 5067 const SCEV *Accum = getAddExpr(Ops); 5068 5069 // This is not a valid addrec if the step amount is varying each 5070 // loop iteration, but is not itself an addrec in this loop. 5071 if (isLoopInvariant(Accum, L) || 5072 (isa<SCEVAddRecExpr>(Accum) && 5073 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5074 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5075 5076 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5077 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5078 if (BO->IsNUW) 5079 Flags = setFlags(Flags, SCEV::FlagNUW); 5080 if (BO->IsNSW) 5081 Flags = setFlags(Flags, SCEV::FlagNSW); 5082 } 5083 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5084 // If the increment is an inbounds GEP, then we know the address 5085 // space cannot be wrapped around. We cannot make any guarantee 5086 // about signed or unsigned overflow because pointers are 5087 // unsigned but we may have a negative index from the base 5088 // pointer. We can guarantee that no unsigned wrap occurs if the 5089 // indices form a positive value. 5090 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5091 Flags = setFlags(Flags, SCEV::FlagNW); 5092 5093 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5094 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5095 Flags = setFlags(Flags, SCEV::FlagNUW); 5096 } 5097 5098 // We cannot transfer nuw and nsw flags from subtraction 5099 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5100 // for instance. 5101 } 5102 5103 const SCEV *StartVal = getSCEV(StartValueV); 5104 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5105 5106 // Okay, for the entire analysis of this edge we assumed the PHI 5107 // to be symbolic. We now need to go back and purge all of the 5108 // entries for the scalars that use the symbolic expression. 5109 forgetSymbolicName(PN, SymbolicName); 5110 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5111 5112 // We can add Flags to the post-inc expression only if we 5113 // know that it is *undefined behavior* for BEValueV to 5114 // overflow. 5115 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5116 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5117 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5118 5119 return PHISCEV; 5120 } 5121 } 5122 } else { 5123 // Otherwise, this could be a loop like this: 5124 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5125 // In this case, j = {1,+,1} and BEValue is j. 5126 // Because the other in-value of i (0) fits the evolution of BEValue 5127 // i really is an addrec evolution. 5128 // 5129 // We can generalize this saying that i is the shifted value of BEValue 5130 // by one iteration: 5131 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5132 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5133 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5134 if (Shifted != getCouldNotCompute() && 5135 Start != getCouldNotCompute()) { 5136 const SCEV *StartVal = getSCEV(StartValueV); 5137 if (Start == StartVal) { 5138 // Okay, for the entire analysis of this edge we assumed the PHI 5139 // to be symbolic. We now need to go back and purge all of the 5140 // entries for the scalars that use the symbolic expression. 5141 forgetSymbolicName(PN, SymbolicName); 5142 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5143 return Shifted; 5144 } 5145 } 5146 } 5147 5148 // Remove the temporary PHI node SCEV that has been inserted while intending 5149 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5150 // as it will prevent later (possibly simpler) SCEV expressions to be added 5151 // to the ValueExprMap. 5152 eraseValueFromMap(PN); 5153 5154 return nullptr; 5155 } 5156 5157 // Checks if the SCEV S is available at BB. S is considered available at BB 5158 // if S can be materialized at BB without introducing a fault. 5159 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5160 BasicBlock *BB) { 5161 struct CheckAvailable { 5162 bool TraversalDone = false; 5163 bool Available = true; 5164 5165 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5166 BasicBlock *BB = nullptr; 5167 DominatorTree &DT; 5168 5169 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5170 : L(L), BB(BB), DT(DT) {} 5171 5172 bool setUnavailable() { 5173 TraversalDone = true; 5174 Available = false; 5175 return false; 5176 } 5177 5178 bool follow(const SCEV *S) { 5179 switch (S->getSCEVType()) { 5180 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5181 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5182 case scUMinExpr: 5183 case scSMinExpr: 5184 // These expressions are available if their operand(s) is/are. 5185 return true; 5186 5187 case scAddRecExpr: { 5188 // We allow add recurrences that are on the loop BB is in, or some 5189 // outer loop. This guarantees availability because the value of the 5190 // add recurrence at BB is simply the "current" value of the induction 5191 // variable. We can relax this in the future; for instance an add 5192 // recurrence on a sibling dominating loop is also available at BB. 5193 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5194 if (L && (ARLoop == L || ARLoop->contains(L))) 5195 return true; 5196 5197 return setUnavailable(); 5198 } 5199 5200 case scUnknown: { 5201 // For SCEVUnknown, we check for simple dominance. 5202 const auto *SU = cast<SCEVUnknown>(S); 5203 Value *V = SU->getValue(); 5204 5205 if (isa<Argument>(V)) 5206 return false; 5207 5208 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5209 return false; 5210 5211 return setUnavailable(); 5212 } 5213 5214 case scUDivExpr: 5215 case scCouldNotCompute: 5216 // We do not try to smart about these at all. 5217 return setUnavailable(); 5218 } 5219 llvm_unreachable("switch should be fully covered!"); 5220 } 5221 5222 bool isDone() { return TraversalDone; } 5223 }; 5224 5225 CheckAvailable CA(L, BB, DT); 5226 SCEVTraversal<CheckAvailable> ST(CA); 5227 5228 ST.visitAll(S); 5229 return CA.Available; 5230 } 5231 5232 // Try to match a control flow sequence that branches out at BI and merges back 5233 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5234 // match. 5235 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5236 Value *&C, Value *&LHS, Value *&RHS) { 5237 C = BI->getCondition(); 5238 5239 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5240 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5241 5242 if (!LeftEdge.isSingleEdge()) 5243 return false; 5244 5245 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5246 5247 Use &LeftUse = Merge->getOperandUse(0); 5248 Use &RightUse = Merge->getOperandUse(1); 5249 5250 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5251 LHS = LeftUse; 5252 RHS = RightUse; 5253 return true; 5254 } 5255 5256 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5257 LHS = RightUse; 5258 RHS = LeftUse; 5259 return true; 5260 } 5261 5262 return false; 5263 } 5264 5265 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5266 auto IsReachable = 5267 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5268 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5269 const Loop *L = LI.getLoopFor(PN->getParent()); 5270 5271 // We don't want to break LCSSA, even in a SCEV expression tree. 5272 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5273 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5274 return nullptr; 5275 5276 // Try to match 5277 // 5278 // br %cond, label %left, label %right 5279 // left: 5280 // br label %merge 5281 // right: 5282 // br label %merge 5283 // merge: 5284 // V = phi [ %x, %left ], [ %y, %right ] 5285 // 5286 // as "select %cond, %x, %y" 5287 5288 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5289 assert(IDom && "At least the entry block should dominate PN"); 5290 5291 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5292 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5293 5294 if (BI && BI->isConditional() && 5295 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5296 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5297 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5298 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5299 } 5300 5301 return nullptr; 5302 } 5303 5304 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5305 if (const SCEV *S = createAddRecFromPHI(PN)) 5306 return S; 5307 5308 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5309 return S; 5310 5311 // If the PHI has a single incoming value, follow that value, unless the 5312 // PHI's incoming blocks are in a different loop, in which case doing so 5313 // risks breaking LCSSA form. Instcombine would normally zap these, but 5314 // it doesn't have DominatorTree information, so it may miss cases. 5315 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5316 if (LI.replacementPreservesLCSSAForm(PN, V)) 5317 return getSCEV(V); 5318 5319 // If it's not a loop phi, we can't handle it yet. 5320 return getUnknown(PN); 5321 } 5322 5323 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5324 Value *Cond, 5325 Value *TrueVal, 5326 Value *FalseVal) { 5327 // Handle "constant" branch or select. This can occur for instance when a 5328 // loop pass transforms an inner loop and moves on to process the outer loop. 5329 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5330 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5331 5332 // Try to match some simple smax or umax patterns. 5333 auto *ICI = dyn_cast<ICmpInst>(Cond); 5334 if (!ICI) 5335 return getUnknown(I); 5336 5337 Value *LHS = ICI->getOperand(0); 5338 Value *RHS = ICI->getOperand(1); 5339 5340 switch (ICI->getPredicate()) { 5341 case ICmpInst::ICMP_SLT: 5342 case ICmpInst::ICMP_SLE: 5343 std::swap(LHS, RHS); 5344 LLVM_FALLTHROUGH; 5345 case ICmpInst::ICMP_SGT: 5346 case ICmpInst::ICMP_SGE: 5347 // a >s b ? a+x : b+x -> smax(a, b)+x 5348 // a >s b ? b+x : a+x -> smin(a, b)+x 5349 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5350 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5351 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5352 const SCEV *LA = getSCEV(TrueVal); 5353 const SCEV *RA = getSCEV(FalseVal); 5354 const SCEV *LDiff = getMinusSCEV(LA, LS); 5355 const SCEV *RDiff = getMinusSCEV(RA, RS); 5356 if (LDiff == RDiff) 5357 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5358 LDiff = getMinusSCEV(LA, RS); 5359 RDiff = getMinusSCEV(RA, LS); 5360 if (LDiff == RDiff) 5361 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5362 } 5363 break; 5364 case ICmpInst::ICMP_ULT: 5365 case ICmpInst::ICMP_ULE: 5366 std::swap(LHS, RHS); 5367 LLVM_FALLTHROUGH; 5368 case ICmpInst::ICMP_UGT: 5369 case ICmpInst::ICMP_UGE: 5370 // a >u b ? a+x : b+x -> umax(a, b)+x 5371 // a >u b ? b+x : a+x -> umin(a, b)+x 5372 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5373 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5374 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5375 const SCEV *LA = getSCEV(TrueVal); 5376 const SCEV *RA = getSCEV(FalseVal); 5377 const SCEV *LDiff = getMinusSCEV(LA, LS); 5378 const SCEV *RDiff = getMinusSCEV(RA, RS); 5379 if (LDiff == RDiff) 5380 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5381 LDiff = getMinusSCEV(LA, RS); 5382 RDiff = getMinusSCEV(RA, LS); 5383 if (LDiff == RDiff) 5384 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5385 } 5386 break; 5387 case ICmpInst::ICMP_NE: 5388 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5389 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5390 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5391 const SCEV *One = getOne(I->getType()); 5392 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5393 const SCEV *LA = getSCEV(TrueVal); 5394 const SCEV *RA = getSCEV(FalseVal); 5395 const SCEV *LDiff = getMinusSCEV(LA, LS); 5396 const SCEV *RDiff = getMinusSCEV(RA, One); 5397 if (LDiff == RDiff) 5398 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5399 } 5400 break; 5401 case ICmpInst::ICMP_EQ: 5402 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5403 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5404 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5405 const SCEV *One = getOne(I->getType()); 5406 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5407 const SCEV *LA = getSCEV(TrueVal); 5408 const SCEV *RA = getSCEV(FalseVal); 5409 const SCEV *LDiff = getMinusSCEV(LA, One); 5410 const SCEV *RDiff = getMinusSCEV(RA, LS); 5411 if (LDiff == RDiff) 5412 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5413 } 5414 break; 5415 default: 5416 break; 5417 } 5418 5419 return getUnknown(I); 5420 } 5421 5422 /// Expand GEP instructions into add and multiply operations. This allows them 5423 /// to be analyzed by regular SCEV code. 5424 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5425 // Don't attempt to analyze GEPs over unsized objects. 5426 if (!GEP->getSourceElementType()->isSized()) 5427 return getUnknown(GEP); 5428 5429 SmallVector<const SCEV *, 4> IndexExprs; 5430 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5431 IndexExprs.push_back(getSCEV(*Index)); 5432 return getGEPExpr(GEP, IndexExprs); 5433 } 5434 5435 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5436 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5437 return C->getAPInt().countTrailingZeros(); 5438 5439 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5440 return std::min(GetMinTrailingZeros(T->getOperand()), 5441 (uint32_t)getTypeSizeInBits(T->getType())); 5442 5443 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5444 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5445 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5446 ? getTypeSizeInBits(E->getType()) 5447 : OpRes; 5448 } 5449 5450 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5451 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5452 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5453 ? getTypeSizeInBits(E->getType()) 5454 : OpRes; 5455 } 5456 5457 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5458 // The result is the min of all operands results. 5459 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5460 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5461 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5462 return MinOpRes; 5463 } 5464 5465 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5466 // The result is the sum of all operands results. 5467 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5468 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5469 for (unsigned i = 1, e = M->getNumOperands(); 5470 SumOpRes != BitWidth && i != e; ++i) 5471 SumOpRes = 5472 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5473 return SumOpRes; 5474 } 5475 5476 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5477 // The result is the min of all operands results. 5478 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5479 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5480 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5481 return MinOpRes; 5482 } 5483 5484 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5485 // The result is the min of all operands results. 5486 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5487 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5488 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5489 return MinOpRes; 5490 } 5491 5492 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5493 // The result is the min of all operands results. 5494 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5495 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5496 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5497 return MinOpRes; 5498 } 5499 5500 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5501 // For a SCEVUnknown, ask ValueTracking. 5502 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5503 return Known.countMinTrailingZeros(); 5504 } 5505 5506 // SCEVUDivExpr 5507 return 0; 5508 } 5509 5510 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5511 auto I = MinTrailingZerosCache.find(S); 5512 if (I != MinTrailingZerosCache.end()) 5513 return I->second; 5514 5515 uint32_t Result = GetMinTrailingZerosImpl(S); 5516 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5517 assert(InsertPair.second && "Should insert a new key"); 5518 return InsertPair.first->second; 5519 } 5520 5521 /// Helper method to assign a range to V from metadata present in the IR. 5522 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5523 if (Instruction *I = dyn_cast<Instruction>(V)) 5524 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5525 return getConstantRangeFromMetadata(*MD); 5526 5527 return None; 5528 } 5529 5530 /// Determine the range for a particular SCEV. If SignHint is 5531 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5532 /// with a "cleaner" unsigned (resp. signed) representation. 5533 const ConstantRange & 5534 ScalarEvolution::getRangeRef(const SCEV *S, 5535 ScalarEvolution::RangeSignHint SignHint) { 5536 DenseMap<const SCEV *, ConstantRange> &Cache = 5537 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5538 : SignedRanges; 5539 ConstantRange::PreferredRangeType RangeType = 5540 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5541 ? ConstantRange::Unsigned : ConstantRange::Signed; 5542 5543 // See if we've computed this range already. 5544 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5545 if (I != Cache.end()) 5546 return I->second; 5547 5548 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5549 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5550 5551 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5552 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5553 5554 // If the value has known zeros, the maximum value will have those known zeros 5555 // as well. 5556 uint32_t TZ = GetMinTrailingZeros(S); 5557 if (TZ != 0) { 5558 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5559 ConservativeResult = 5560 ConstantRange(APInt::getMinValue(BitWidth), 5561 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5562 else 5563 ConservativeResult = ConstantRange( 5564 APInt::getSignedMinValue(BitWidth), 5565 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5566 } 5567 5568 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5569 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5570 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5571 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5572 return setRange(Add, SignHint, 5573 ConservativeResult.intersectWith(X, RangeType)); 5574 } 5575 5576 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5577 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5578 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5579 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5580 return setRange(Mul, SignHint, 5581 ConservativeResult.intersectWith(X, RangeType)); 5582 } 5583 5584 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5585 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5586 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5587 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5588 return setRange(SMax, SignHint, 5589 ConservativeResult.intersectWith(X, RangeType)); 5590 } 5591 5592 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5593 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5594 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5595 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5596 return setRange(UMax, SignHint, 5597 ConservativeResult.intersectWith(X, RangeType)); 5598 } 5599 5600 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5601 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5602 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5603 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5604 return setRange(SMin, SignHint, 5605 ConservativeResult.intersectWith(X, RangeType)); 5606 } 5607 5608 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5609 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5610 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5611 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5612 return setRange(UMin, SignHint, 5613 ConservativeResult.intersectWith(X, RangeType)); 5614 } 5615 5616 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5617 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5618 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5619 return setRange(UDiv, SignHint, 5620 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5621 } 5622 5623 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5624 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5625 return setRange(ZExt, SignHint, 5626 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5627 RangeType)); 5628 } 5629 5630 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5631 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5632 return setRange(SExt, SignHint, 5633 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5634 RangeType)); 5635 } 5636 5637 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5638 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5639 return setRange(Trunc, SignHint, 5640 ConservativeResult.intersectWith(X.truncate(BitWidth), 5641 RangeType)); 5642 } 5643 5644 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5645 // If there's no unsigned wrap, the value will never be less than its 5646 // initial value. 5647 if (AddRec->hasNoUnsignedWrap()) 5648 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5649 if (!C->getValue()->isZero()) 5650 ConservativeResult = ConservativeResult.intersectWith( 5651 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5652 5653 // If there's no signed wrap, and all the operands have the same sign or 5654 // zero, the value won't ever change sign. 5655 if (AddRec->hasNoSignedWrap()) { 5656 bool AllNonNeg = true; 5657 bool AllNonPos = true; 5658 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5659 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5660 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5661 } 5662 if (AllNonNeg) 5663 ConservativeResult = ConservativeResult.intersectWith( 5664 ConstantRange(APInt(BitWidth, 0), 5665 APInt::getSignedMinValue(BitWidth)), RangeType); 5666 else if (AllNonPos) 5667 ConservativeResult = ConservativeResult.intersectWith( 5668 ConstantRange(APInt::getSignedMinValue(BitWidth), 5669 APInt(BitWidth, 1)), RangeType); 5670 } 5671 5672 // TODO: non-affine addrec 5673 if (AddRec->isAffine()) { 5674 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5675 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5676 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5677 auto RangeFromAffine = getRangeForAffineAR( 5678 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5679 BitWidth); 5680 if (!RangeFromAffine.isFullSet()) 5681 ConservativeResult = 5682 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5683 5684 auto RangeFromFactoring = getRangeViaFactoring( 5685 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5686 BitWidth); 5687 if (!RangeFromFactoring.isFullSet()) 5688 ConservativeResult = 5689 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5690 } 5691 } 5692 5693 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5694 } 5695 5696 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5697 // Check if the IR explicitly contains !range metadata. 5698 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5699 if (MDRange.hasValue()) 5700 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5701 RangeType); 5702 5703 // Split here to avoid paying the compile-time cost of calling both 5704 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5705 // if needed. 5706 const DataLayout &DL = getDataLayout(); 5707 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5708 // For a SCEVUnknown, ask ValueTracking. 5709 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5710 if (Known.One != ~Known.Zero + 1) 5711 ConservativeResult = 5712 ConservativeResult.intersectWith( 5713 ConstantRange(Known.One, ~Known.Zero + 1), RangeType); 5714 } else { 5715 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5716 "generalize as needed!"); 5717 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5718 if (NS > 1) 5719 ConservativeResult = ConservativeResult.intersectWith( 5720 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5721 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5722 RangeType); 5723 } 5724 5725 // A range of Phi is a subset of union of all ranges of its input. 5726 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5727 // Make sure that we do not run over cycled Phis. 5728 if (PendingPhiRanges.insert(Phi).second) { 5729 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5730 for (auto &Op : Phi->operands()) { 5731 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5732 RangeFromOps = RangeFromOps.unionWith(OpRange); 5733 // No point to continue if we already have a full set. 5734 if (RangeFromOps.isFullSet()) 5735 break; 5736 } 5737 ConservativeResult = 5738 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5739 bool Erased = PendingPhiRanges.erase(Phi); 5740 assert(Erased && "Failed to erase Phi properly?"); 5741 (void) Erased; 5742 } 5743 } 5744 5745 return setRange(U, SignHint, std::move(ConservativeResult)); 5746 } 5747 5748 return setRange(S, SignHint, std::move(ConservativeResult)); 5749 } 5750 5751 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5752 // values that the expression can take. Initially, the expression has a value 5753 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5754 // argument defines if we treat Step as signed or unsigned. 5755 static ConstantRange getRangeForAffineARHelper(APInt Step, 5756 const ConstantRange &StartRange, 5757 const APInt &MaxBECount, 5758 unsigned BitWidth, bool Signed) { 5759 // If either Step or MaxBECount is 0, then the expression won't change, and we 5760 // just need to return the initial range. 5761 if (Step == 0 || MaxBECount == 0) 5762 return StartRange; 5763 5764 // If we don't know anything about the initial value (i.e. StartRange is 5765 // FullRange), then we don't know anything about the final range either. 5766 // Return FullRange. 5767 if (StartRange.isFullSet()) 5768 return ConstantRange::getFull(BitWidth); 5769 5770 // If Step is signed and negative, then we use its absolute value, but we also 5771 // note that we're moving in the opposite direction. 5772 bool Descending = Signed && Step.isNegative(); 5773 5774 if (Signed) 5775 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5776 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5777 // This equations hold true due to the well-defined wrap-around behavior of 5778 // APInt. 5779 Step = Step.abs(); 5780 5781 // Check if Offset is more than full span of BitWidth. If it is, the 5782 // expression is guaranteed to overflow. 5783 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5784 return ConstantRange::getFull(BitWidth); 5785 5786 // Offset is by how much the expression can change. Checks above guarantee no 5787 // overflow here. 5788 APInt Offset = Step * MaxBECount; 5789 5790 // Minimum value of the final range will match the minimal value of StartRange 5791 // if the expression is increasing and will be decreased by Offset otherwise. 5792 // Maximum value of the final range will match the maximal value of StartRange 5793 // if the expression is decreasing and will be increased by Offset otherwise. 5794 APInt StartLower = StartRange.getLower(); 5795 APInt StartUpper = StartRange.getUpper() - 1; 5796 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5797 : (StartUpper + std::move(Offset)); 5798 5799 // It's possible that the new minimum/maximum value will fall into the initial 5800 // range (due to wrap around). This means that the expression can take any 5801 // value in this bitwidth, and we have to return full range. 5802 if (StartRange.contains(MovedBoundary)) 5803 return ConstantRange::getFull(BitWidth); 5804 5805 APInt NewLower = 5806 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5807 APInt NewUpper = 5808 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5809 NewUpper += 1; 5810 5811 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5812 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5813 } 5814 5815 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5816 const SCEV *Step, 5817 const SCEV *MaxBECount, 5818 unsigned BitWidth) { 5819 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5820 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5821 "Precondition!"); 5822 5823 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5824 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5825 5826 // First, consider step signed. 5827 ConstantRange StartSRange = getSignedRange(Start); 5828 ConstantRange StepSRange = getSignedRange(Step); 5829 5830 // If Step can be both positive and negative, we need to find ranges for the 5831 // maximum absolute step values in both directions and union them. 5832 ConstantRange SR = 5833 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5834 MaxBECountValue, BitWidth, /* Signed = */ true); 5835 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5836 StartSRange, MaxBECountValue, 5837 BitWidth, /* Signed = */ true)); 5838 5839 // Next, consider step unsigned. 5840 ConstantRange UR = getRangeForAffineARHelper( 5841 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5842 MaxBECountValue, BitWidth, /* Signed = */ false); 5843 5844 // Finally, intersect signed and unsigned ranges. 5845 return SR.intersectWith(UR, ConstantRange::Smallest); 5846 } 5847 5848 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5849 const SCEV *Step, 5850 const SCEV *MaxBECount, 5851 unsigned BitWidth) { 5852 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5853 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5854 5855 struct SelectPattern { 5856 Value *Condition = nullptr; 5857 APInt TrueValue; 5858 APInt FalseValue; 5859 5860 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5861 const SCEV *S) { 5862 Optional<unsigned> CastOp; 5863 APInt Offset(BitWidth, 0); 5864 5865 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5866 "Should be!"); 5867 5868 // Peel off a constant offset: 5869 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5870 // In the future we could consider being smarter here and handle 5871 // {Start+Step,+,Step} too. 5872 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5873 return; 5874 5875 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5876 S = SA->getOperand(1); 5877 } 5878 5879 // Peel off a cast operation 5880 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5881 CastOp = SCast->getSCEVType(); 5882 S = SCast->getOperand(); 5883 } 5884 5885 using namespace llvm::PatternMatch; 5886 5887 auto *SU = dyn_cast<SCEVUnknown>(S); 5888 const APInt *TrueVal, *FalseVal; 5889 if (!SU || 5890 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5891 m_APInt(FalseVal)))) { 5892 Condition = nullptr; 5893 return; 5894 } 5895 5896 TrueValue = *TrueVal; 5897 FalseValue = *FalseVal; 5898 5899 // Re-apply the cast we peeled off earlier 5900 if (CastOp.hasValue()) 5901 switch (*CastOp) { 5902 default: 5903 llvm_unreachable("Unknown SCEV cast type!"); 5904 5905 case scTruncate: 5906 TrueValue = TrueValue.trunc(BitWidth); 5907 FalseValue = FalseValue.trunc(BitWidth); 5908 break; 5909 case scZeroExtend: 5910 TrueValue = TrueValue.zext(BitWidth); 5911 FalseValue = FalseValue.zext(BitWidth); 5912 break; 5913 case scSignExtend: 5914 TrueValue = TrueValue.sext(BitWidth); 5915 FalseValue = FalseValue.sext(BitWidth); 5916 break; 5917 } 5918 5919 // Re-apply the constant offset we peeled off earlier 5920 TrueValue += Offset; 5921 FalseValue += Offset; 5922 } 5923 5924 bool isRecognized() { return Condition != nullptr; } 5925 }; 5926 5927 SelectPattern StartPattern(*this, BitWidth, Start); 5928 if (!StartPattern.isRecognized()) 5929 return ConstantRange::getFull(BitWidth); 5930 5931 SelectPattern StepPattern(*this, BitWidth, Step); 5932 if (!StepPattern.isRecognized()) 5933 return ConstantRange::getFull(BitWidth); 5934 5935 if (StartPattern.Condition != StepPattern.Condition) { 5936 // We don't handle this case today; but we could, by considering four 5937 // possibilities below instead of two. I'm not sure if there are cases where 5938 // that will help over what getRange already does, though. 5939 return ConstantRange::getFull(BitWidth); 5940 } 5941 5942 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5943 // construct arbitrary general SCEV expressions here. This function is called 5944 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5945 // say) can end up caching a suboptimal value. 5946 5947 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5948 // C2352 and C2512 (otherwise it isn't needed). 5949 5950 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5951 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5952 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5953 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5954 5955 ConstantRange TrueRange = 5956 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5957 ConstantRange FalseRange = 5958 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5959 5960 return TrueRange.unionWith(FalseRange); 5961 } 5962 5963 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5964 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5965 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5966 5967 // Return early if there are no flags to propagate to the SCEV. 5968 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5969 if (BinOp->hasNoUnsignedWrap()) 5970 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5971 if (BinOp->hasNoSignedWrap()) 5972 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5973 if (Flags == SCEV::FlagAnyWrap) 5974 return SCEV::FlagAnyWrap; 5975 5976 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5977 } 5978 5979 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5980 // Here we check that I is in the header of the innermost loop containing I, 5981 // since we only deal with instructions in the loop header. The actual loop we 5982 // need to check later will come from an add recurrence, but getting that 5983 // requires computing the SCEV of the operands, which can be expensive. This 5984 // check we can do cheaply to rule out some cases early. 5985 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5986 if (InnermostContainingLoop == nullptr || 5987 InnermostContainingLoop->getHeader() != I->getParent()) 5988 return false; 5989 5990 // Only proceed if we can prove that I does not yield poison. 5991 if (!programUndefinedIfFullPoison(I)) 5992 return false; 5993 5994 // At this point we know that if I is executed, then it does not wrap 5995 // according to at least one of NSW or NUW. If I is not executed, then we do 5996 // not know if the calculation that I represents would wrap. Multiple 5997 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5998 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5999 // derived from other instructions that map to the same SCEV. We cannot make 6000 // that guarantee for cases where I is not executed. So we need to find the 6001 // loop that I is considered in relation to and prove that I is executed for 6002 // every iteration of that loop. That implies that the value that I 6003 // calculates does not wrap anywhere in the loop, so then we can apply the 6004 // flags to the SCEV. 6005 // 6006 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6007 // from different loops, so that we know which loop to prove that I is 6008 // executed in. 6009 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6010 // I could be an extractvalue from a call to an overflow intrinsic. 6011 // TODO: We can do better here in some cases. 6012 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6013 return false; 6014 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6015 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6016 bool AllOtherOpsLoopInvariant = true; 6017 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6018 ++OtherOpIndex) { 6019 if (OtherOpIndex != OpIndex) { 6020 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6021 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6022 AllOtherOpsLoopInvariant = false; 6023 break; 6024 } 6025 } 6026 } 6027 if (AllOtherOpsLoopInvariant && 6028 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6029 return true; 6030 } 6031 } 6032 return false; 6033 } 6034 6035 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6036 // If we know that \c I can never be poison period, then that's enough. 6037 if (isSCEVExprNeverPoison(I)) 6038 return true; 6039 6040 // For an add recurrence specifically, we assume that infinite loops without 6041 // side effects are undefined behavior, and then reason as follows: 6042 // 6043 // If the add recurrence is poison in any iteration, it is poison on all 6044 // future iterations (since incrementing poison yields poison). If the result 6045 // of the add recurrence is fed into the loop latch condition and the loop 6046 // does not contain any throws or exiting blocks other than the latch, we now 6047 // have the ability to "choose" whether the backedge is taken or not (by 6048 // choosing a sufficiently evil value for the poison feeding into the branch) 6049 // for every iteration including and after the one in which \p I first became 6050 // poison. There are two possibilities (let's call the iteration in which \p 6051 // I first became poison as K): 6052 // 6053 // 1. In the set of iterations including and after K, the loop body executes 6054 // no side effects. In this case executing the backege an infinte number 6055 // of times will yield undefined behavior. 6056 // 6057 // 2. In the set of iterations including and after K, the loop body executes 6058 // at least one side effect. In this case, that specific instance of side 6059 // effect is control dependent on poison, which also yields undefined 6060 // behavior. 6061 6062 auto *ExitingBB = L->getExitingBlock(); 6063 auto *LatchBB = L->getLoopLatch(); 6064 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6065 return false; 6066 6067 SmallPtrSet<const Instruction *, 16> Pushed; 6068 SmallVector<const Instruction *, 8> PoisonStack; 6069 6070 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6071 // things that are known to be fully poison under that assumption go on the 6072 // PoisonStack. 6073 Pushed.insert(I); 6074 PoisonStack.push_back(I); 6075 6076 bool LatchControlDependentOnPoison = false; 6077 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6078 const Instruction *Poison = PoisonStack.pop_back_val(); 6079 6080 for (auto *PoisonUser : Poison->users()) { 6081 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6082 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6083 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6084 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6085 assert(BI->isConditional() && "Only possibility!"); 6086 if (BI->getParent() == LatchBB) { 6087 LatchControlDependentOnPoison = true; 6088 break; 6089 } 6090 } 6091 } 6092 } 6093 6094 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6095 } 6096 6097 ScalarEvolution::LoopProperties 6098 ScalarEvolution::getLoopProperties(const Loop *L) { 6099 using LoopProperties = ScalarEvolution::LoopProperties; 6100 6101 auto Itr = LoopPropertiesCache.find(L); 6102 if (Itr == LoopPropertiesCache.end()) { 6103 auto HasSideEffects = [](Instruction *I) { 6104 if (auto *SI = dyn_cast<StoreInst>(I)) 6105 return !SI->isSimple(); 6106 6107 return I->mayHaveSideEffects(); 6108 }; 6109 6110 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6111 /*HasNoSideEffects*/ true}; 6112 6113 for (auto *BB : L->getBlocks()) 6114 for (auto &I : *BB) { 6115 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6116 LP.HasNoAbnormalExits = false; 6117 if (HasSideEffects(&I)) 6118 LP.HasNoSideEffects = false; 6119 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6120 break; // We're already as pessimistic as we can get. 6121 } 6122 6123 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6124 assert(InsertPair.second && "We just checked!"); 6125 Itr = InsertPair.first; 6126 } 6127 6128 return Itr->second; 6129 } 6130 6131 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6132 if (!isSCEVable(V->getType())) 6133 return getUnknown(V); 6134 6135 if (Instruction *I = dyn_cast<Instruction>(V)) { 6136 // Don't attempt to analyze instructions in blocks that aren't 6137 // reachable. Such instructions don't matter, and they aren't required 6138 // to obey basic rules for definitions dominating uses which this 6139 // analysis depends on. 6140 if (!DT.isReachableFromEntry(I->getParent())) 6141 return getUnknown(UndefValue::get(V->getType())); 6142 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6143 return getConstant(CI); 6144 else if (isa<ConstantPointerNull>(V)) 6145 return getZero(V->getType()); 6146 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6147 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6148 else if (!isa<ConstantExpr>(V)) 6149 return getUnknown(V); 6150 6151 Operator *U = cast<Operator>(V); 6152 if (auto BO = MatchBinaryOp(U, DT)) { 6153 switch (BO->Opcode) { 6154 case Instruction::Add: { 6155 // The simple thing to do would be to just call getSCEV on both operands 6156 // and call getAddExpr with the result. However if we're looking at a 6157 // bunch of things all added together, this can be quite inefficient, 6158 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6159 // Instead, gather up all the operands and make a single getAddExpr call. 6160 // LLVM IR canonical form means we need only traverse the left operands. 6161 SmallVector<const SCEV *, 4> AddOps; 6162 do { 6163 if (BO->Op) { 6164 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6165 AddOps.push_back(OpSCEV); 6166 break; 6167 } 6168 6169 // If a NUW or NSW flag can be applied to the SCEV for this 6170 // addition, then compute the SCEV for this addition by itself 6171 // with a separate call to getAddExpr. We need to do that 6172 // instead of pushing the operands of the addition onto AddOps, 6173 // since the flags are only known to apply to this particular 6174 // addition - they may not apply to other additions that can be 6175 // formed with operands from AddOps. 6176 const SCEV *RHS = getSCEV(BO->RHS); 6177 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6178 if (Flags != SCEV::FlagAnyWrap) { 6179 const SCEV *LHS = getSCEV(BO->LHS); 6180 if (BO->Opcode == Instruction::Sub) 6181 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6182 else 6183 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6184 break; 6185 } 6186 } 6187 6188 if (BO->Opcode == Instruction::Sub) 6189 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6190 else 6191 AddOps.push_back(getSCEV(BO->RHS)); 6192 6193 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6194 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6195 NewBO->Opcode != Instruction::Sub)) { 6196 AddOps.push_back(getSCEV(BO->LHS)); 6197 break; 6198 } 6199 BO = NewBO; 6200 } while (true); 6201 6202 return getAddExpr(AddOps); 6203 } 6204 6205 case Instruction::Mul: { 6206 SmallVector<const SCEV *, 4> MulOps; 6207 do { 6208 if (BO->Op) { 6209 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6210 MulOps.push_back(OpSCEV); 6211 break; 6212 } 6213 6214 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6215 if (Flags != SCEV::FlagAnyWrap) { 6216 MulOps.push_back( 6217 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6218 break; 6219 } 6220 } 6221 6222 MulOps.push_back(getSCEV(BO->RHS)); 6223 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6224 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6225 MulOps.push_back(getSCEV(BO->LHS)); 6226 break; 6227 } 6228 BO = NewBO; 6229 } while (true); 6230 6231 return getMulExpr(MulOps); 6232 } 6233 case Instruction::UDiv: 6234 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6235 case Instruction::URem: 6236 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6237 case Instruction::Sub: { 6238 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6239 if (BO->Op) 6240 Flags = getNoWrapFlagsFromUB(BO->Op); 6241 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6242 } 6243 case Instruction::And: 6244 // For an expression like x&255 that merely masks off the high bits, 6245 // use zext(trunc(x)) as the SCEV expression. 6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6247 if (CI->isZero()) 6248 return getSCEV(BO->RHS); 6249 if (CI->isMinusOne()) 6250 return getSCEV(BO->LHS); 6251 const APInt &A = CI->getValue(); 6252 6253 // Instcombine's ShrinkDemandedConstant may strip bits out of 6254 // constants, obscuring what would otherwise be a low-bits mask. 6255 // Use computeKnownBits to compute what ShrinkDemandedConstant 6256 // knew about to reconstruct a low-bits mask value. 6257 unsigned LZ = A.countLeadingZeros(); 6258 unsigned TZ = A.countTrailingZeros(); 6259 unsigned BitWidth = A.getBitWidth(); 6260 KnownBits Known(BitWidth); 6261 computeKnownBits(BO->LHS, Known, getDataLayout(), 6262 0, &AC, nullptr, &DT); 6263 6264 APInt EffectiveMask = 6265 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6266 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6267 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6268 const SCEV *LHS = getSCEV(BO->LHS); 6269 const SCEV *ShiftedLHS = nullptr; 6270 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6271 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6272 // For an expression like (x * 8) & 8, simplify the multiply. 6273 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6274 unsigned GCD = std::min(MulZeros, TZ); 6275 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6276 SmallVector<const SCEV*, 4> MulOps; 6277 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6278 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6279 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6280 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6281 } 6282 } 6283 if (!ShiftedLHS) 6284 ShiftedLHS = getUDivExpr(LHS, MulCount); 6285 return getMulExpr( 6286 getZeroExtendExpr( 6287 getTruncateExpr(ShiftedLHS, 6288 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6289 BO->LHS->getType()), 6290 MulCount); 6291 } 6292 } 6293 break; 6294 6295 case Instruction::Or: 6296 // If the RHS of the Or is a constant, we may have something like: 6297 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6298 // optimizations will transparently handle this case. 6299 // 6300 // In order for this transformation to be safe, the LHS must be of the 6301 // form X*(2^n) and the Or constant must be less than 2^n. 6302 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6303 const SCEV *LHS = getSCEV(BO->LHS); 6304 const APInt &CIVal = CI->getValue(); 6305 if (GetMinTrailingZeros(LHS) >= 6306 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6307 // Build a plain add SCEV. 6308 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6309 // If the LHS of the add was an addrec and it has no-wrap flags, 6310 // transfer the no-wrap flags, since an or won't introduce a wrap. 6311 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6312 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6313 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6314 OldAR->getNoWrapFlags()); 6315 } 6316 return S; 6317 } 6318 } 6319 break; 6320 6321 case Instruction::Xor: 6322 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6323 // If the RHS of xor is -1, then this is a not operation. 6324 if (CI->isMinusOne()) 6325 return getNotSCEV(getSCEV(BO->LHS)); 6326 6327 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6328 // This is a variant of the check for xor with -1, and it handles 6329 // the case where instcombine has trimmed non-demanded bits out 6330 // of an xor with -1. 6331 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6332 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6333 if (LBO->getOpcode() == Instruction::And && 6334 LCI->getValue() == CI->getValue()) 6335 if (const SCEVZeroExtendExpr *Z = 6336 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6337 Type *UTy = BO->LHS->getType(); 6338 const SCEV *Z0 = Z->getOperand(); 6339 Type *Z0Ty = Z0->getType(); 6340 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6341 6342 // If C is a low-bits mask, the zero extend is serving to 6343 // mask off the high bits. Complement the operand and 6344 // re-apply the zext. 6345 if (CI->getValue().isMask(Z0TySize)) 6346 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6347 6348 // If C is a single bit, it may be in the sign-bit position 6349 // before the zero-extend. In this case, represent the xor 6350 // using an add, which is equivalent, and re-apply the zext. 6351 APInt Trunc = CI->getValue().trunc(Z0TySize); 6352 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6353 Trunc.isSignMask()) 6354 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6355 UTy); 6356 } 6357 } 6358 break; 6359 6360 case Instruction::Shl: 6361 // Turn shift left of a constant amount into a multiply. 6362 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6363 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6364 6365 // If the shift count is not less than the bitwidth, the result of 6366 // the shift is undefined. Don't try to analyze it, because the 6367 // resolution chosen here may differ from the resolution chosen in 6368 // other parts of the compiler. 6369 if (SA->getValue().uge(BitWidth)) 6370 break; 6371 6372 // It is currently not resolved how to interpret NSW for left 6373 // shift by BitWidth - 1, so we avoid applying flags in that 6374 // case. Remove this check (or this comment) once the situation 6375 // is resolved. See 6376 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6377 // and http://reviews.llvm.org/D8890 . 6378 auto Flags = SCEV::FlagAnyWrap; 6379 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6380 Flags = getNoWrapFlagsFromUB(BO->Op); 6381 6382 Constant *X = ConstantInt::get( 6383 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6384 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6385 } 6386 break; 6387 6388 case Instruction::AShr: { 6389 // AShr X, C, where C is a constant. 6390 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6391 if (!CI) 6392 break; 6393 6394 Type *OuterTy = BO->LHS->getType(); 6395 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6396 // If the shift count is not less than the bitwidth, the result of 6397 // the shift is undefined. Don't try to analyze it, because the 6398 // resolution chosen here may differ from the resolution chosen in 6399 // other parts of the compiler. 6400 if (CI->getValue().uge(BitWidth)) 6401 break; 6402 6403 if (CI->isZero()) 6404 return getSCEV(BO->LHS); // shift by zero --> noop 6405 6406 uint64_t AShrAmt = CI->getZExtValue(); 6407 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6408 6409 Operator *L = dyn_cast<Operator>(BO->LHS); 6410 if (L && L->getOpcode() == Instruction::Shl) { 6411 // X = Shl A, n 6412 // Y = AShr X, m 6413 // Both n and m are constant. 6414 6415 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6416 if (L->getOperand(1) == BO->RHS) 6417 // For a two-shift sext-inreg, i.e. n = m, 6418 // use sext(trunc(x)) as the SCEV expression. 6419 return getSignExtendExpr( 6420 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6421 6422 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6423 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6424 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6425 if (ShlAmt > AShrAmt) { 6426 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6427 // expression. We already checked that ShlAmt < BitWidth, so 6428 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6429 // ShlAmt - AShrAmt < Amt. 6430 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6431 ShlAmt - AShrAmt); 6432 return getSignExtendExpr( 6433 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6434 getConstant(Mul)), OuterTy); 6435 } 6436 } 6437 } 6438 break; 6439 } 6440 } 6441 } 6442 6443 switch (U->getOpcode()) { 6444 case Instruction::Trunc: 6445 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6446 6447 case Instruction::ZExt: 6448 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6449 6450 case Instruction::SExt: 6451 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6452 // The NSW flag of a subtract does not always survive the conversion to 6453 // A + (-1)*B. By pushing sign extension onto its operands we are much 6454 // more likely to preserve NSW and allow later AddRec optimisations. 6455 // 6456 // NOTE: This is effectively duplicating this logic from getSignExtend: 6457 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6458 // but by that point the NSW information has potentially been lost. 6459 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6460 Type *Ty = U->getType(); 6461 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6462 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6463 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6464 } 6465 } 6466 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6467 6468 case Instruction::BitCast: 6469 // BitCasts are no-op casts so we just eliminate the cast. 6470 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6471 return getSCEV(U->getOperand(0)); 6472 break; 6473 6474 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6475 // lead to pointer expressions which cannot safely be expanded to GEPs, 6476 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6477 // simplifying integer expressions. 6478 6479 case Instruction::GetElementPtr: 6480 return createNodeForGEP(cast<GEPOperator>(U)); 6481 6482 case Instruction::PHI: 6483 return createNodeForPHI(cast<PHINode>(U)); 6484 6485 case Instruction::Select: 6486 // U can also be a select constant expr, which let fall through. Since 6487 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6488 // constant expressions cannot have instructions as operands, we'd have 6489 // returned getUnknown for a select constant expressions anyway. 6490 if (isa<Instruction>(U)) 6491 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6492 U->getOperand(1), U->getOperand(2)); 6493 break; 6494 6495 case Instruction::Call: 6496 case Instruction::Invoke: 6497 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6498 return getSCEV(RV); 6499 break; 6500 } 6501 6502 return getUnknown(V); 6503 } 6504 6505 //===----------------------------------------------------------------------===// 6506 // Iteration Count Computation Code 6507 // 6508 6509 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6510 if (!ExitCount) 6511 return 0; 6512 6513 ConstantInt *ExitConst = ExitCount->getValue(); 6514 6515 // Guard against huge trip counts. 6516 if (ExitConst->getValue().getActiveBits() > 32) 6517 return 0; 6518 6519 // In case of integer overflow, this returns 0, which is correct. 6520 return ((unsigned)ExitConst->getZExtValue()) + 1; 6521 } 6522 6523 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6524 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6525 return getSmallConstantTripCount(L, ExitingBB); 6526 6527 // No trip count information for multiple exits. 6528 return 0; 6529 } 6530 6531 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6532 BasicBlock *ExitingBlock) { 6533 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6534 assert(L->isLoopExiting(ExitingBlock) && 6535 "Exiting block must actually branch out of the loop!"); 6536 const SCEVConstant *ExitCount = 6537 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6538 return getConstantTripCount(ExitCount); 6539 } 6540 6541 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6542 const auto *MaxExitCount = 6543 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6544 return getConstantTripCount(MaxExitCount); 6545 } 6546 6547 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6548 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6549 return getSmallConstantTripMultiple(L, ExitingBB); 6550 6551 // No trip multiple information for multiple exits. 6552 return 0; 6553 } 6554 6555 /// Returns the largest constant divisor of the trip count of this loop as a 6556 /// normal unsigned value, if possible. This means that the actual trip count is 6557 /// always a multiple of the returned value (don't forget the trip count could 6558 /// very well be zero as well!). 6559 /// 6560 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6561 /// multiple of a constant (which is also the case if the trip count is simply 6562 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6563 /// if the trip count is very large (>= 2^32). 6564 /// 6565 /// As explained in the comments for getSmallConstantTripCount, this assumes 6566 /// that control exits the loop via ExitingBlock. 6567 unsigned 6568 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6569 BasicBlock *ExitingBlock) { 6570 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6571 assert(L->isLoopExiting(ExitingBlock) && 6572 "Exiting block must actually branch out of the loop!"); 6573 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6574 if (ExitCount == getCouldNotCompute()) 6575 return 1; 6576 6577 // Get the trip count from the BE count by adding 1. 6578 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6579 6580 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6581 if (!TC) 6582 // Attempt to factor more general cases. Returns the greatest power of 6583 // two divisor. If overflow happens, the trip count expression is still 6584 // divisible by the greatest power of 2 divisor returned. 6585 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6586 6587 ConstantInt *Result = TC->getValue(); 6588 6589 // Guard against huge trip counts (this requires checking 6590 // for zero to handle the case where the trip count == -1 and the 6591 // addition wraps). 6592 if (!Result || Result->getValue().getActiveBits() > 32 || 6593 Result->getValue().getActiveBits() == 0) 6594 return 1; 6595 6596 return (unsigned)Result->getZExtValue(); 6597 } 6598 6599 /// Get the expression for the number of loop iterations for which this loop is 6600 /// guaranteed not to exit via ExitingBlock. Otherwise return 6601 /// SCEVCouldNotCompute. 6602 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6603 BasicBlock *ExitingBlock) { 6604 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6605 } 6606 6607 const SCEV * 6608 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6609 SCEVUnionPredicate &Preds) { 6610 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6611 } 6612 6613 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6614 return getBackedgeTakenInfo(L).getExact(L, this); 6615 } 6616 6617 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6618 /// known never to be less than the actual backedge taken count. 6619 const SCEV *ScalarEvolution::getConstantMaxBackedgeTakenCount(const Loop *L) { 6620 return getBackedgeTakenInfo(L).getMax(this); 6621 } 6622 6623 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6624 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6625 } 6626 6627 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6628 static void 6629 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6630 BasicBlock *Header = L->getHeader(); 6631 6632 // Push all Loop-header PHIs onto the Worklist stack. 6633 for (PHINode &PN : Header->phis()) 6634 Worklist.push_back(&PN); 6635 } 6636 6637 const ScalarEvolution::BackedgeTakenInfo & 6638 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6639 auto &BTI = getBackedgeTakenInfo(L); 6640 if (BTI.hasFullInfo()) 6641 return BTI; 6642 6643 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6644 6645 if (!Pair.second) 6646 return Pair.first->second; 6647 6648 BackedgeTakenInfo Result = 6649 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6650 6651 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6652 } 6653 6654 const ScalarEvolution::BackedgeTakenInfo & 6655 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6656 // Initially insert an invalid entry for this loop. If the insertion 6657 // succeeds, proceed to actually compute a backedge-taken count and 6658 // update the value. The temporary CouldNotCompute value tells SCEV 6659 // code elsewhere that it shouldn't attempt to request a new 6660 // backedge-taken count, which could result in infinite recursion. 6661 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6662 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6663 if (!Pair.second) 6664 return Pair.first->second; 6665 6666 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6667 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6668 // must be cleared in this scope. 6669 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6670 6671 // In product build, there are no usage of statistic. 6672 (void)NumTripCountsComputed; 6673 (void)NumTripCountsNotComputed; 6674 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6675 const SCEV *BEExact = Result.getExact(L, this); 6676 if (BEExact != getCouldNotCompute()) { 6677 assert(isLoopInvariant(BEExact, L) && 6678 isLoopInvariant(Result.getMax(this), L) && 6679 "Computed backedge-taken count isn't loop invariant for loop!"); 6680 ++NumTripCountsComputed; 6681 } 6682 else if (Result.getMax(this) == getCouldNotCompute() && 6683 isa<PHINode>(L->getHeader()->begin())) { 6684 // Only count loops that have phi nodes as not being computable. 6685 ++NumTripCountsNotComputed; 6686 } 6687 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6688 6689 // Now that we know more about the trip count for this loop, forget any 6690 // existing SCEV values for PHI nodes in this loop since they are only 6691 // conservative estimates made without the benefit of trip count 6692 // information. This is similar to the code in forgetLoop, except that 6693 // it handles SCEVUnknown PHI nodes specially. 6694 if (Result.hasAnyInfo()) { 6695 SmallVector<Instruction *, 16> Worklist; 6696 PushLoopPHIs(L, Worklist); 6697 6698 SmallPtrSet<Instruction *, 8> Discovered; 6699 while (!Worklist.empty()) { 6700 Instruction *I = Worklist.pop_back_val(); 6701 6702 ValueExprMapType::iterator It = 6703 ValueExprMap.find_as(static_cast<Value *>(I)); 6704 if (It != ValueExprMap.end()) { 6705 const SCEV *Old = It->second; 6706 6707 // SCEVUnknown for a PHI either means that it has an unrecognized 6708 // structure, or it's a PHI that's in the progress of being computed 6709 // by createNodeForPHI. In the former case, additional loop trip 6710 // count information isn't going to change anything. In the later 6711 // case, createNodeForPHI will perform the necessary updates on its 6712 // own when it gets to that point. 6713 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6714 eraseValueFromMap(It->first); 6715 forgetMemoizedResults(Old); 6716 } 6717 if (PHINode *PN = dyn_cast<PHINode>(I)) 6718 ConstantEvolutionLoopExitValue.erase(PN); 6719 } 6720 6721 // Since we don't need to invalidate anything for correctness and we're 6722 // only invalidating to make SCEV's results more precise, we get to stop 6723 // early to avoid invalidating too much. This is especially important in 6724 // cases like: 6725 // 6726 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6727 // loop0: 6728 // %pn0 = phi 6729 // ... 6730 // loop1: 6731 // %pn1 = phi 6732 // ... 6733 // 6734 // where both loop0 and loop1's backedge taken count uses the SCEV 6735 // expression for %v. If we don't have the early stop below then in cases 6736 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6737 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6738 // count for loop1, effectively nullifying SCEV's trip count cache. 6739 for (auto *U : I->users()) 6740 if (auto *I = dyn_cast<Instruction>(U)) { 6741 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6742 if (LoopForUser && L->contains(LoopForUser) && 6743 Discovered.insert(I).second) 6744 Worklist.push_back(I); 6745 } 6746 } 6747 } 6748 6749 // Re-lookup the insert position, since the call to 6750 // computeBackedgeTakenCount above could result in a 6751 // recusive call to getBackedgeTakenInfo (on a different 6752 // loop), which would invalidate the iterator computed 6753 // earlier. 6754 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6755 } 6756 6757 void ScalarEvolution::forgetAllLoops() { 6758 // This method is intended to forget all info about loops. It should 6759 // invalidate caches as if the following happened: 6760 // - The trip counts of all loops have changed arbitrarily 6761 // - Every llvm::Value has been updated in place to produce a different 6762 // result. 6763 BackedgeTakenCounts.clear(); 6764 PredicatedBackedgeTakenCounts.clear(); 6765 LoopPropertiesCache.clear(); 6766 ConstantEvolutionLoopExitValue.clear(); 6767 ValueExprMap.clear(); 6768 ValuesAtScopes.clear(); 6769 LoopDispositions.clear(); 6770 BlockDispositions.clear(); 6771 UnsignedRanges.clear(); 6772 SignedRanges.clear(); 6773 ExprValueMap.clear(); 6774 HasRecMap.clear(); 6775 MinTrailingZerosCache.clear(); 6776 PredicatedSCEVRewrites.clear(); 6777 } 6778 6779 void ScalarEvolution::forgetLoop(const Loop *L) { 6780 // Drop any stored trip count value. 6781 auto RemoveLoopFromBackedgeMap = 6782 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6783 auto BTCPos = Map.find(L); 6784 if (BTCPos != Map.end()) { 6785 BTCPos->second.clear(); 6786 Map.erase(BTCPos); 6787 } 6788 }; 6789 6790 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6791 SmallVector<Instruction *, 32> Worklist; 6792 SmallPtrSet<Instruction *, 16> Visited; 6793 6794 // Iterate over all the loops and sub-loops to drop SCEV information. 6795 while (!LoopWorklist.empty()) { 6796 auto *CurrL = LoopWorklist.pop_back_val(); 6797 6798 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6799 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6800 6801 // Drop information about predicated SCEV rewrites for this loop. 6802 for (auto I = PredicatedSCEVRewrites.begin(); 6803 I != PredicatedSCEVRewrites.end();) { 6804 std::pair<const SCEV *, const Loop *> Entry = I->first; 6805 if (Entry.second == CurrL) 6806 PredicatedSCEVRewrites.erase(I++); 6807 else 6808 ++I; 6809 } 6810 6811 auto LoopUsersItr = LoopUsers.find(CurrL); 6812 if (LoopUsersItr != LoopUsers.end()) { 6813 for (auto *S : LoopUsersItr->second) 6814 forgetMemoizedResults(S); 6815 LoopUsers.erase(LoopUsersItr); 6816 } 6817 6818 // Drop information about expressions based on loop-header PHIs. 6819 PushLoopPHIs(CurrL, Worklist); 6820 6821 while (!Worklist.empty()) { 6822 Instruction *I = Worklist.pop_back_val(); 6823 if (!Visited.insert(I).second) 6824 continue; 6825 6826 ValueExprMapType::iterator It = 6827 ValueExprMap.find_as(static_cast<Value *>(I)); 6828 if (It != ValueExprMap.end()) { 6829 eraseValueFromMap(It->first); 6830 forgetMemoizedResults(It->second); 6831 if (PHINode *PN = dyn_cast<PHINode>(I)) 6832 ConstantEvolutionLoopExitValue.erase(PN); 6833 } 6834 6835 PushDefUseChildren(I, Worklist); 6836 } 6837 6838 LoopPropertiesCache.erase(CurrL); 6839 // Forget all contained loops too, to avoid dangling entries in the 6840 // ValuesAtScopes map. 6841 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6842 } 6843 } 6844 6845 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6846 while (Loop *Parent = L->getParentLoop()) 6847 L = Parent; 6848 forgetLoop(L); 6849 } 6850 6851 void ScalarEvolution::forgetValue(Value *V) { 6852 Instruction *I = dyn_cast<Instruction>(V); 6853 if (!I) return; 6854 6855 // Drop information about expressions based on loop-header PHIs. 6856 SmallVector<Instruction *, 16> Worklist; 6857 Worklist.push_back(I); 6858 6859 SmallPtrSet<Instruction *, 8> Visited; 6860 while (!Worklist.empty()) { 6861 I = Worklist.pop_back_val(); 6862 if (!Visited.insert(I).second) 6863 continue; 6864 6865 ValueExprMapType::iterator It = 6866 ValueExprMap.find_as(static_cast<Value *>(I)); 6867 if (It != ValueExprMap.end()) { 6868 eraseValueFromMap(It->first); 6869 forgetMemoizedResults(It->second); 6870 if (PHINode *PN = dyn_cast<PHINode>(I)) 6871 ConstantEvolutionLoopExitValue.erase(PN); 6872 } 6873 6874 PushDefUseChildren(I, Worklist); 6875 } 6876 } 6877 6878 /// Get the exact loop backedge taken count considering all loop exits. A 6879 /// computable result can only be returned for loops with all exiting blocks 6880 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6881 /// is never skipped. This is a valid assumption as long as the loop exits via 6882 /// that test. For precise results, it is the caller's responsibility to specify 6883 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6884 const SCEV * 6885 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6886 SCEVUnionPredicate *Preds) const { 6887 // If any exits were not computable, the loop is not computable. 6888 if (!isComplete() || ExitNotTaken.empty()) 6889 return SE->getCouldNotCompute(); 6890 6891 const BasicBlock *Latch = L->getLoopLatch(); 6892 // All exiting blocks we have collected must dominate the only backedge. 6893 if (!Latch) 6894 return SE->getCouldNotCompute(); 6895 6896 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6897 // count is simply a minimum out of all these calculated exit counts. 6898 SmallVector<const SCEV *, 2> Ops; 6899 for (auto &ENT : ExitNotTaken) { 6900 const SCEV *BECount = ENT.ExactNotTaken; 6901 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6902 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6903 "We should only have known counts for exiting blocks that dominate " 6904 "latch!"); 6905 6906 Ops.push_back(BECount); 6907 6908 if (Preds && !ENT.hasAlwaysTruePredicate()) 6909 Preds->add(ENT.Predicate.get()); 6910 6911 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6912 "Predicate should be always true!"); 6913 } 6914 6915 return SE->getUMinFromMismatchedTypes(Ops); 6916 } 6917 6918 /// Get the exact not taken count for this loop exit. 6919 const SCEV * 6920 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6921 ScalarEvolution *SE) const { 6922 for (auto &ENT : ExitNotTaken) 6923 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6924 return ENT.ExactNotTaken; 6925 6926 return SE->getCouldNotCompute(); 6927 } 6928 6929 /// getMax - Get the max backedge taken count for the loop. 6930 const SCEV * 6931 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6932 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6933 return !ENT.hasAlwaysTruePredicate(); 6934 }; 6935 6936 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6937 return SE->getCouldNotCompute(); 6938 6939 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6940 "No point in having a non-constant max backedge taken count!"); 6941 return getMax(); 6942 } 6943 6944 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6945 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6946 return !ENT.hasAlwaysTruePredicate(); 6947 }; 6948 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6949 } 6950 6951 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6952 ScalarEvolution *SE) const { 6953 if (getMax() && getMax() != SE->getCouldNotCompute() && 6954 SE->hasOperand(getMax(), S)) 6955 return true; 6956 6957 for (auto &ENT : ExitNotTaken) 6958 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6959 SE->hasOperand(ENT.ExactNotTaken, S)) 6960 return true; 6961 6962 return false; 6963 } 6964 6965 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6966 : ExactNotTaken(E), MaxNotTaken(E) { 6967 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6968 isa<SCEVConstant>(MaxNotTaken)) && 6969 "No point in having a non-constant max backedge taken count!"); 6970 } 6971 6972 ScalarEvolution::ExitLimit::ExitLimit( 6973 const SCEV *E, const SCEV *M, bool MaxOrZero, 6974 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6975 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6976 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6977 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6978 "Exact is not allowed to be less precise than Max"); 6979 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6980 isa<SCEVConstant>(MaxNotTaken)) && 6981 "No point in having a non-constant max backedge taken count!"); 6982 for (auto *PredSet : PredSetList) 6983 for (auto *P : *PredSet) 6984 addPredicate(P); 6985 } 6986 6987 ScalarEvolution::ExitLimit::ExitLimit( 6988 const SCEV *E, const SCEV *M, bool MaxOrZero, 6989 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6990 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6991 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6992 isa<SCEVConstant>(MaxNotTaken)) && 6993 "No point in having a non-constant max backedge taken count!"); 6994 } 6995 6996 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6997 bool MaxOrZero) 6998 : ExitLimit(E, M, MaxOrZero, None) { 6999 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7000 isa<SCEVConstant>(MaxNotTaken)) && 7001 "No point in having a non-constant max backedge taken count!"); 7002 } 7003 7004 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7005 /// computable exit into a persistent ExitNotTakenInfo array. 7006 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7007 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7008 ExitCounts, 7009 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7010 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7011 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7012 7013 ExitNotTaken.reserve(ExitCounts.size()); 7014 std::transform( 7015 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7016 [&](const EdgeExitInfo &EEI) { 7017 BasicBlock *ExitBB = EEI.first; 7018 const ExitLimit &EL = EEI.second; 7019 if (EL.Predicates.empty()) 7020 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7021 7022 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7023 for (auto *Pred : EL.Predicates) 7024 Predicate->add(Pred); 7025 7026 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7027 }); 7028 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7029 "No point in having a non-constant max backedge taken count!"); 7030 } 7031 7032 /// Invalidate this result and free the ExitNotTakenInfo array. 7033 void ScalarEvolution::BackedgeTakenInfo::clear() { 7034 ExitNotTaken.clear(); 7035 } 7036 7037 /// Compute the number of times the backedge of the specified loop will execute. 7038 ScalarEvolution::BackedgeTakenInfo 7039 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7040 bool AllowPredicates) { 7041 SmallVector<BasicBlock *, 8> ExitingBlocks; 7042 L->getExitingBlocks(ExitingBlocks); 7043 7044 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7045 7046 SmallVector<EdgeExitInfo, 4> ExitCounts; 7047 bool CouldComputeBECount = true; 7048 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7049 const SCEV *MustExitMaxBECount = nullptr; 7050 const SCEV *MayExitMaxBECount = nullptr; 7051 bool MustExitMaxOrZero = false; 7052 7053 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7054 // and compute maxBECount. 7055 // Do a union of all the predicates here. 7056 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7057 BasicBlock *ExitBB = ExitingBlocks[i]; 7058 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7059 7060 assert((AllowPredicates || EL.Predicates.empty()) && 7061 "Predicated exit limit when predicates are not allowed!"); 7062 7063 // 1. For each exit that can be computed, add an entry to ExitCounts. 7064 // CouldComputeBECount is true only if all exits can be computed. 7065 if (EL.ExactNotTaken == getCouldNotCompute()) 7066 // We couldn't compute an exact value for this exit, so 7067 // we won't be able to compute an exact value for the loop. 7068 CouldComputeBECount = false; 7069 else 7070 ExitCounts.emplace_back(ExitBB, EL); 7071 7072 // 2. Derive the loop's MaxBECount from each exit's max number of 7073 // non-exiting iterations. Partition the loop exits into two kinds: 7074 // LoopMustExits and LoopMayExits. 7075 // 7076 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7077 // is a LoopMayExit. If any computable LoopMustExit is found, then 7078 // MaxBECount is the minimum EL.MaxNotTaken of computable 7079 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7080 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7081 // computable EL.MaxNotTaken. 7082 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7083 DT.dominates(ExitBB, Latch)) { 7084 if (!MustExitMaxBECount) { 7085 MustExitMaxBECount = EL.MaxNotTaken; 7086 MustExitMaxOrZero = EL.MaxOrZero; 7087 } else { 7088 MustExitMaxBECount = 7089 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7090 } 7091 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7092 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7093 MayExitMaxBECount = EL.MaxNotTaken; 7094 else { 7095 MayExitMaxBECount = 7096 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7097 } 7098 } 7099 } 7100 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7101 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7102 // The loop backedge will be taken the maximum or zero times if there's 7103 // a single exit that must be taken the maximum or zero times. 7104 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7105 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7106 MaxBECount, MaxOrZero); 7107 } 7108 7109 ScalarEvolution::ExitLimit 7110 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7111 bool AllowPredicates) { 7112 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7113 // If our exiting block does not dominate the latch, then its connection with 7114 // loop's exit limit may be far from trivial. 7115 const BasicBlock *Latch = L->getLoopLatch(); 7116 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7117 return getCouldNotCompute(); 7118 7119 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7120 Instruction *Term = ExitingBlock->getTerminator(); 7121 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7122 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7123 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7124 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7125 "It should have one successor in loop and one exit block!"); 7126 // Proceed to the next level to examine the exit condition expression. 7127 return computeExitLimitFromCond( 7128 L, BI->getCondition(), ExitIfTrue, 7129 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7130 } 7131 7132 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7133 // For switch, make sure that there is a single exit from the loop. 7134 BasicBlock *Exit = nullptr; 7135 for (auto *SBB : successors(ExitingBlock)) 7136 if (!L->contains(SBB)) { 7137 if (Exit) // Multiple exit successors. 7138 return getCouldNotCompute(); 7139 Exit = SBB; 7140 } 7141 assert(Exit && "Exiting block must have at least one exit"); 7142 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7143 /*ControlsExit=*/IsOnlyExit); 7144 } 7145 7146 return getCouldNotCompute(); 7147 } 7148 7149 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7150 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7151 bool ControlsExit, bool AllowPredicates) { 7152 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7153 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7154 ControlsExit, AllowPredicates); 7155 } 7156 7157 Optional<ScalarEvolution::ExitLimit> 7158 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7159 bool ExitIfTrue, bool ControlsExit, 7160 bool AllowPredicates) { 7161 (void)this->L; 7162 (void)this->ExitIfTrue; 7163 (void)this->AllowPredicates; 7164 7165 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7166 this->AllowPredicates == AllowPredicates && 7167 "Variance in assumed invariant key components!"); 7168 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7169 if (Itr == TripCountMap.end()) 7170 return None; 7171 return Itr->second; 7172 } 7173 7174 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7175 bool ExitIfTrue, 7176 bool ControlsExit, 7177 bool AllowPredicates, 7178 const ExitLimit &EL) { 7179 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7180 this->AllowPredicates == AllowPredicates && 7181 "Variance in assumed invariant key components!"); 7182 7183 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7184 assert(InsertResult.second && "Expected successful insertion!"); 7185 (void)InsertResult; 7186 (void)ExitIfTrue; 7187 } 7188 7189 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7190 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7191 bool ControlsExit, bool AllowPredicates) { 7192 7193 if (auto MaybeEL = 7194 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7195 return *MaybeEL; 7196 7197 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7198 ControlsExit, AllowPredicates); 7199 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7200 return EL; 7201 } 7202 7203 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7204 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7205 bool ControlsExit, bool AllowPredicates) { 7206 // Check if the controlling expression for this loop is an And or Or. 7207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7208 if (BO->getOpcode() == Instruction::And) { 7209 // Recurse on the operands of the and. 7210 bool EitherMayExit = !ExitIfTrue; 7211 ExitLimit EL0 = computeExitLimitFromCondCached( 7212 Cache, L, BO->getOperand(0), ExitIfTrue, 7213 ControlsExit && !EitherMayExit, AllowPredicates); 7214 ExitLimit EL1 = computeExitLimitFromCondCached( 7215 Cache, L, BO->getOperand(1), ExitIfTrue, 7216 ControlsExit && !EitherMayExit, AllowPredicates); 7217 const SCEV *BECount = getCouldNotCompute(); 7218 const SCEV *MaxBECount = getCouldNotCompute(); 7219 if (EitherMayExit) { 7220 // Both conditions must be true for the loop to continue executing. 7221 // Choose the less conservative count. 7222 if (EL0.ExactNotTaken == getCouldNotCompute() || 7223 EL1.ExactNotTaken == getCouldNotCompute()) 7224 BECount = getCouldNotCompute(); 7225 else 7226 BECount = 7227 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7228 if (EL0.MaxNotTaken == getCouldNotCompute()) 7229 MaxBECount = EL1.MaxNotTaken; 7230 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7231 MaxBECount = EL0.MaxNotTaken; 7232 else 7233 MaxBECount = 7234 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7235 } else { 7236 // Both conditions must be true at the same time for the loop to exit. 7237 // For now, be conservative. 7238 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7239 MaxBECount = EL0.MaxNotTaken; 7240 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7241 BECount = EL0.ExactNotTaken; 7242 } 7243 7244 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7245 // to be more aggressive when computing BECount than when computing 7246 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7247 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7248 // to not. 7249 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7250 !isa<SCEVCouldNotCompute>(BECount)) 7251 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7252 7253 return ExitLimit(BECount, MaxBECount, false, 7254 {&EL0.Predicates, &EL1.Predicates}); 7255 } 7256 if (BO->getOpcode() == Instruction::Or) { 7257 // Recurse on the operands of the or. 7258 bool EitherMayExit = ExitIfTrue; 7259 ExitLimit EL0 = computeExitLimitFromCondCached( 7260 Cache, L, BO->getOperand(0), ExitIfTrue, 7261 ControlsExit && !EitherMayExit, AllowPredicates); 7262 ExitLimit EL1 = computeExitLimitFromCondCached( 7263 Cache, L, BO->getOperand(1), ExitIfTrue, 7264 ControlsExit && !EitherMayExit, AllowPredicates); 7265 const SCEV *BECount = getCouldNotCompute(); 7266 const SCEV *MaxBECount = getCouldNotCompute(); 7267 if (EitherMayExit) { 7268 // Both conditions must be false for the loop to continue executing. 7269 // Choose the less conservative count. 7270 if (EL0.ExactNotTaken == getCouldNotCompute() || 7271 EL1.ExactNotTaken == getCouldNotCompute()) 7272 BECount = getCouldNotCompute(); 7273 else 7274 BECount = 7275 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7276 if (EL0.MaxNotTaken == getCouldNotCompute()) 7277 MaxBECount = EL1.MaxNotTaken; 7278 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7279 MaxBECount = EL0.MaxNotTaken; 7280 else 7281 MaxBECount = 7282 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7283 } else { 7284 // Both conditions must be false at the same time for the loop to exit. 7285 // For now, be conservative. 7286 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7287 MaxBECount = EL0.MaxNotTaken; 7288 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7289 BECount = EL0.ExactNotTaken; 7290 } 7291 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7292 // to be more aggressive when computing BECount than when computing 7293 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7294 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7295 // to not. 7296 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7297 !isa<SCEVCouldNotCompute>(BECount)) 7298 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7299 7300 return ExitLimit(BECount, MaxBECount, false, 7301 {&EL0.Predicates, &EL1.Predicates}); 7302 } 7303 } 7304 7305 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7306 // Proceed to the next level to examine the icmp. 7307 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7308 ExitLimit EL = 7309 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7310 if (EL.hasFullInfo() || !AllowPredicates) 7311 return EL; 7312 7313 // Try again, but use SCEV predicates this time. 7314 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7315 /*AllowPredicates=*/true); 7316 } 7317 7318 // Check for a constant condition. These are normally stripped out by 7319 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7320 // preserve the CFG and is temporarily leaving constant conditions 7321 // in place. 7322 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7323 if (ExitIfTrue == !CI->getZExtValue()) 7324 // The backedge is always taken. 7325 return getCouldNotCompute(); 7326 else 7327 // The backedge is never taken. 7328 return getZero(CI->getType()); 7329 } 7330 7331 // If it's not an integer or pointer comparison then compute it the hard way. 7332 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7333 } 7334 7335 ScalarEvolution::ExitLimit 7336 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7337 ICmpInst *ExitCond, 7338 bool ExitIfTrue, 7339 bool ControlsExit, 7340 bool AllowPredicates) { 7341 // If the condition was exit on true, convert the condition to exit on false 7342 ICmpInst::Predicate Pred; 7343 if (!ExitIfTrue) 7344 Pred = ExitCond->getPredicate(); 7345 else 7346 Pred = ExitCond->getInversePredicate(); 7347 const ICmpInst::Predicate OriginalPred = Pred; 7348 7349 // Handle common loops like: for (X = "string"; *X; ++X) 7350 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7351 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7352 ExitLimit ItCnt = 7353 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7354 if (ItCnt.hasAnyInfo()) 7355 return ItCnt; 7356 } 7357 7358 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7359 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7360 7361 // Try to evaluate any dependencies out of the loop. 7362 LHS = getSCEVAtScope(LHS, L); 7363 RHS = getSCEVAtScope(RHS, L); 7364 7365 // At this point, we would like to compute how many iterations of the 7366 // loop the predicate will return true for these inputs. 7367 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7368 // If there is a loop-invariant, force it into the RHS. 7369 std::swap(LHS, RHS); 7370 Pred = ICmpInst::getSwappedPredicate(Pred); 7371 } 7372 7373 // Simplify the operands before analyzing them. 7374 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7375 7376 // If we have a comparison of a chrec against a constant, try to use value 7377 // ranges to answer this query. 7378 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7379 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7380 if (AddRec->getLoop() == L) { 7381 // Form the constant range. 7382 ConstantRange CompRange = 7383 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7384 7385 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7386 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7387 } 7388 7389 switch (Pred) { 7390 case ICmpInst::ICMP_NE: { // while (X != Y) 7391 // Convert to: while (X-Y != 0) 7392 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7393 AllowPredicates); 7394 if (EL.hasAnyInfo()) return EL; 7395 break; 7396 } 7397 case ICmpInst::ICMP_EQ: { // while (X == Y) 7398 // Convert to: while (X-Y == 0) 7399 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7400 if (EL.hasAnyInfo()) return EL; 7401 break; 7402 } 7403 case ICmpInst::ICMP_SLT: 7404 case ICmpInst::ICMP_ULT: { // while (X < Y) 7405 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7406 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7407 AllowPredicates); 7408 if (EL.hasAnyInfo()) return EL; 7409 break; 7410 } 7411 case ICmpInst::ICMP_SGT: 7412 case ICmpInst::ICMP_UGT: { // while (X > Y) 7413 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7414 ExitLimit EL = 7415 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7416 AllowPredicates); 7417 if (EL.hasAnyInfo()) return EL; 7418 break; 7419 } 7420 default: 7421 break; 7422 } 7423 7424 auto *ExhaustiveCount = 7425 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7426 7427 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7428 return ExhaustiveCount; 7429 7430 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7431 ExitCond->getOperand(1), L, OriginalPred); 7432 } 7433 7434 ScalarEvolution::ExitLimit 7435 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7436 SwitchInst *Switch, 7437 BasicBlock *ExitingBlock, 7438 bool ControlsExit) { 7439 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7440 7441 // Give up if the exit is the default dest of a switch. 7442 if (Switch->getDefaultDest() == ExitingBlock) 7443 return getCouldNotCompute(); 7444 7445 assert(L->contains(Switch->getDefaultDest()) && 7446 "Default case must not exit the loop!"); 7447 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7448 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7449 7450 // while (X != Y) --> while (X-Y != 0) 7451 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7452 if (EL.hasAnyInfo()) 7453 return EL; 7454 7455 return getCouldNotCompute(); 7456 } 7457 7458 static ConstantInt * 7459 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7460 ScalarEvolution &SE) { 7461 const SCEV *InVal = SE.getConstant(C); 7462 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7463 assert(isa<SCEVConstant>(Val) && 7464 "Evaluation of SCEV at constant didn't fold correctly?"); 7465 return cast<SCEVConstant>(Val)->getValue(); 7466 } 7467 7468 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7469 /// compute the backedge execution count. 7470 ScalarEvolution::ExitLimit 7471 ScalarEvolution::computeLoadConstantCompareExitLimit( 7472 LoadInst *LI, 7473 Constant *RHS, 7474 const Loop *L, 7475 ICmpInst::Predicate predicate) { 7476 if (LI->isVolatile()) return getCouldNotCompute(); 7477 7478 // Check to see if the loaded pointer is a getelementptr of a global. 7479 // TODO: Use SCEV instead of manually grubbing with GEPs. 7480 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7481 if (!GEP) return getCouldNotCompute(); 7482 7483 // Make sure that it is really a constant global we are gepping, with an 7484 // initializer, and make sure the first IDX is really 0. 7485 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7486 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7487 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7488 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7489 return getCouldNotCompute(); 7490 7491 // Okay, we allow one non-constant index into the GEP instruction. 7492 Value *VarIdx = nullptr; 7493 std::vector<Constant*> Indexes; 7494 unsigned VarIdxNum = 0; 7495 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7496 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7497 Indexes.push_back(CI); 7498 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7499 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7500 VarIdx = GEP->getOperand(i); 7501 VarIdxNum = i-2; 7502 Indexes.push_back(nullptr); 7503 } 7504 7505 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7506 if (!VarIdx) 7507 return getCouldNotCompute(); 7508 7509 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7510 // Check to see if X is a loop variant variable value now. 7511 const SCEV *Idx = getSCEV(VarIdx); 7512 Idx = getSCEVAtScope(Idx, L); 7513 7514 // We can only recognize very limited forms of loop index expressions, in 7515 // particular, only affine AddRec's like {C1,+,C2}. 7516 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7517 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7518 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7519 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7520 return getCouldNotCompute(); 7521 7522 unsigned MaxSteps = MaxBruteForceIterations; 7523 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7524 ConstantInt *ItCst = ConstantInt::get( 7525 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7526 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7527 7528 // Form the GEP offset. 7529 Indexes[VarIdxNum] = Val; 7530 7531 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7532 Indexes); 7533 if (!Result) break; // Cannot compute! 7534 7535 // Evaluate the condition for this iteration. 7536 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7537 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7538 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7539 ++NumArrayLenItCounts; 7540 return getConstant(ItCst); // Found terminating iteration! 7541 } 7542 } 7543 return getCouldNotCompute(); 7544 } 7545 7546 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7547 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7548 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7549 if (!RHS) 7550 return getCouldNotCompute(); 7551 7552 const BasicBlock *Latch = L->getLoopLatch(); 7553 if (!Latch) 7554 return getCouldNotCompute(); 7555 7556 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7557 if (!Predecessor) 7558 return getCouldNotCompute(); 7559 7560 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7561 // Return LHS in OutLHS and shift_opt in OutOpCode. 7562 auto MatchPositiveShift = 7563 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7564 7565 using namespace PatternMatch; 7566 7567 ConstantInt *ShiftAmt; 7568 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7569 OutOpCode = Instruction::LShr; 7570 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7571 OutOpCode = Instruction::AShr; 7572 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7573 OutOpCode = Instruction::Shl; 7574 else 7575 return false; 7576 7577 return ShiftAmt->getValue().isStrictlyPositive(); 7578 }; 7579 7580 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7581 // 7582 // loop: 7583 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7584 // %iv.shifted = lshr i32 %iv, <positive constant> 7585 // 7586 // Return true on a successful match. Return the corresponding PHI node (%iv 7587 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7588 auto MatchShiftRecurrence = 7589 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7590 Optional<Instruction::BinaryOps> PostShiftOpCode; 7591 7592 { 7593 Instruction::BinaryOps OpC; 7594 Value *V; 7595 7596 // If we encounter a shift instruction, "peel off" the shift operation, 7597 // and remember that we did so. Later when we inspect %iv's backedge 7598 // value, we will make sure that the backedge value uses the same 7599 // operation. 7600 // 7601 // Note: the peeled shift operation does not have to be the same 7602 // instruction as the one feeding into the PHI's backedge value. We only 7603 // really care about it being the same *kind* of shift instruction -- 7604 // that's all that is required for our later inferences to hold. 7605 if (MatchPositiveShift(LHS, V, OpC)) { 7606 PostShiftOpCode = OpC; 7607 LHS = V; 7608 } 7609 } 7610 7611 PNOut = dyn_cast<PHINode>(LHS); 7612 if (!PNOut || PNOut->getParent() != L->getHeader()) 7613 return false; 7614 7615 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7616 Value *OpLHS; 7617 7618 return 7619 // The backedge value for the PHI node must be a shift by a positive 7620 // amount 7621 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7622 7623 // of the PHI node itself 7624 OpLHS == PNOut && 7625 7626 // and the kind of shift should be match the kind of shift we peeled 7627 // off, if any. 7628 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7629 }; 7630 7631 PHINode *PN; 7632 Instruction::BinaryOps OpCode; 7633 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7634 return getCouldNotCompute(); 7635 7636 const DataLayout &DL = getDataLayout(); 7637 7638 // The key rationale for this optimization is that for some kinds of shift 7639 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7640 // within a finite number of iterations. If the condition guarding the 7641 // backedge (in the sense that the backedge is taken if the condition is true) 7642 // is false for the value the shift recurrence stabilizes to, then we know 7643 // that the backedge is taken only a finite number of times. 7644 7645 ConstantInt *StableValue = nullptr; 7646 switch (OpCode) { 7647 default: 7648 llvm_unreachable("Impossible case!"); 7649 7650 case Instruction::AShr: { 7651 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7652 // bitwidth(K) iterations. 7653 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7654 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7655 Predecessor->getTerminator(), &DT); 7656 auto *Ty = cast<IntegerType>(RHS->getType()); 7657 if (Known.isNonNegative()) 7658 StableValue = ConstantInt::get(Ty, 0); 7659 else if (Known.isNegative()) 7660 StableValue = ConstantInt::get(Ty, -1, true); 7661 else 7662 return getCouldNotCompute(); 7663 7664 break; 7665 } 7666 case Instruction::LShr: 7667 case Instruction::Shl: 7668 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7669 // stabilize to 0 in at most bitwidth(K) iterations. 7670 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7671 break; 7672 } 7673 7674 auto *Result = 7675 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7676 assert(Result->getType()->isIntegerTy(1) && 7677 "Otherwise cannot be an operand to a branch instruction"); 7678 7679 if (Result->isZeroValue()) { 7680 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7681 const SCEV *UpperBound = 7682 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7683 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7684 } 7685 7686 return getCouldNotCompute(); 7687 } 7688 7689 /// Return true if we can constant fold an instruction of the specified type, 7690 /// assuming that all operands were constants. 7691 static bool CanConstantFold(const Instruction *I) { 7692 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7693 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7694 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7695 return true; 7696 7697 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7698 if (const Function *F = CI->getCalledFunction()) 7699 return canConstantFoldCallTo(CI, F); 7700 return false; 7701 } 7702 7703 /// Determine whether this instruction can constant evolve within this loop 7704 /// assuming its operands can all constant evolve. 7705 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7706 // An instruction outside of the loop can't be derived from a loop PHI. 7707 if (!L->contains(I)) return false; 7708 7709 if (isa<PHINode>(I)) { 7710 // We don't currently keep track of the control flow needed to evaluate 7711 // PHIs, so we cannot handle PHIs inside of loops. 7712 return L->getHeader() == I->getParent(); 7713 } 7714 7715 // If we won't be able to constant fold this expression even if the operands 7716 // are constants, bail early. 7717 return CanConstantFold(I); 7718 } 7719 7720 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7721 /// recursing through each instruction operand until reaching a loop header phi. 7722 static PHINode * 7723 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7724 DenseMap<Instruction *, PHINode *> &PHIMap, 7725 unsigned Depth) { 7726 if (Depth > MaxConstantEvolvingDepth) 7727 return nullptr; 7728 7729 // Otherwise, we can evaluate this instruction if all of its operands are 7730 // constant or derived from a PHI node themselves. 7731 PHINode *PHI = nullptr; 7732 for (Value *Op : UseInst->operands()) { 7733 if (isa<Constant>(Op)) continue; 7734 7735 Instruction *OpInst = dyn_cast<Instruction>(Op); 7736 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7737 7738 PHINode *P = dyn_cast<PHINode>(OpInst); 7739 if (!P) 7740 // If this operand is already visited, reuse the prior result. 7741 // We may have P != PHI if this is the deepest point at which the 7742 // inconsistent paths meet. 7743 P = PHIMap.lookup(OpInst); 7744 if (!P) { 7745 // Recurse and memoize the results, whether a phi is found or not. 7746 // This recursive call invalidates pointers into PHIMap. 7747 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7748 PHIMap[OpInst] = P; 7749 } 7750 if (!P) 7751 return nullptr; // Not evolving from PHI 7752 if (PHI && PHI != P) 7753 return nullptr; // Evolving from multiple different PHIs. 7754 PHI = P; 7755 } 7756 // This is a expression evolving from a constant PHI! 7757 return PHI; 7758 } 7759 7760 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7761 /// in the loop that V is derived from. We allow arbitrary operations along the 7762 /// way, but the operands of an operation must either be constants or a value 7763 /// derived from a constant PHI. If this expression does not fit with these 7764 /// constraints, return null. 7765 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7766 Instruction *I = dyn_cast<Instruction>(V); 7767 if (!I || !canConstantEvolve(I, L)) return nullptr; 7768 7769 if (PHINode *PN = dyn_cast<PHINode>(I)) 7770 return PN; 7771 7772 // Record non-constant instructions contained by the loop. 7773 DenseMap<Instruction *, PHINode *> PHIMap; 7774 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7775 } 7776 7777 /// EvaluateExpression - Given an expression that passes the 7778 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7779 /// in the loop has the value PHIVal. If we can't fold this expression for some 7780 /// reason, return null. 7781 static Constant *EvaluateExpression(Value *V, const Loop *L, 7782 DenseMap<Instruction *, Constant *> &Vals, 7783 const DataLayout &DL, 7784 const TargetLibraryInfo *TLI) { 7785 // Convenient constant check, but redundant for recursive calls. 7786 if (Constant *C = dyn_cast<Constant>(V)) return C; 7787 Instruction *I = dyn_cast<Instruction>(V); 7788 if (!I) return nullptr; 7789 7790 if (Constant *C = Vals.lookup(I)) return C; 7791 7792 // An instruction inside the loop depends on a value outside the loop that we 7793 // weren't given a mapping for, or a value such as a call inside the loop. 7794 if (!canConstantEvolve(I, L)) return nullptr; 7795 7796 // An unmapped PHI can be due to a branch or another loop inside this loop, 7797 // or due to this not being the initial iteration through a loop where we 7798 // couldn't compute the evolution of this particular PHI last time. 7799 if (isa<PHINode>(I)) return nullptr; 7800 7801 std::vector<Constant*> Operands(I->getNumOperands()); 7802 7803 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7804 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7805 if (!Operand) { 7806 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7807 if (!Operands[i]) return nullptr; 7808 continue; 7809 } 7810 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7811 Vals[Operand] = C; 7812 if (!C) return nullptr; 7813 Operands[i] = C; 7814 } 7815 7816 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7817 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7818 Operands[1], DL, TLI); 7819 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7820 if (!LI->isVolatile()) 7821 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7822 } 7823 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7824 } 7825 7826 7827 // If every incoming value to PN except the one for BB is a specific Constant, 7828 // return that, else return nullptr. 7829 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7830 Constant *IncomingVal = nullptr; 7831 7832 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7833 if (PN->getIncomingBlock(i) == BB) 7834 continue; 7835 7836 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7837 if (!CurrentVal) 7838 return nullptr; 7839 7840 if (IncomingVal != CurrentVal) { 7841 if (IncomingVal) 7842 return nullptr; 7843 IncomingVal = CurrentVal; 7844 } 7845 } 7846 7847 return IncomingVal; 7848 } 7849 7850 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7851 /// in the header of its containing loop, we know the loop executes a 7852 /// constant number of times, and the PHI node is just a recurrence 7853 /// involving constants, fold it. 7854 Constant * 7855 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7856 const APInt &BEs, 7857 const Loop *L) { 7858 auto I = ConstantEvolutionLoopExitValue.find(PN); 7859 if (I != ConstantEvolutionLoopExitValue.end()) 7860 return I->second; 7861 7862 if (BEs.ugt(MaxBruteForceIterations)) 7863 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7864 7865 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7866 7867 DenseMap<Instruction *, Constant *> CurrentIterVals; 7868 BasicBlock *Header = L->getHeader(); 7869 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7870 7871 BasicBlock *Latch = L->getLoopLatch(); 7872 if (!Latch) 7873 return nullptr; 7874 7875 for (PHINode &PHI : Header->phis()) { 7876 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7877 CurrentIterVals[&PHI] = StartCST; 7878 } 7879 if (!CurrentIterVals.count(PN)) 7880 return RetVal = nullptr; 7881 7882 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7883 7884 // Execute the loop symbolically to determine the exit value. 7885 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7886 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7887 7888 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7889 unsigned IterationNum = 0; 7890 const DataLayout &DL = getDataLayout(); 7891 for (; ; ++IterationNum) { 7892 if (IterationNum == NumIterations) 7893 return RetVal = CurrentIterVals[PN]; // Got exit value! 7894 7895 // Compute the value of the PHIs for the next iteration. 7896 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7897 DenseMap<Instruction *, Constant *> NextIterVals; 7898 Constant *NextPHI = 7899 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7900 if (!NextPHI) 7901 return nullptr; // Couldn't evaluate! 7902 NextIterVals[PN] = NextPHI; 7903 7904 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7905 7906 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7907 // cease to be able to evaluate one of them or if they stop evolving, 7908 // because that doesn't necessarily prevent us from computing PN. 7909 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7910 for (const auto &I : CurrentIterVals) { 7911 PHINode *PHI = dyn_cast<PHINode>(I.first); 7912 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7913 PHIsToCompute.emplace_back(PHI, I.second); 7914 } 7915 // We use two distinct loops because EvaluateExpression may invalidate any 7916 // iterators into CurrentIterVals. 7917 for (const auto &I : PHIsToCompute) { 7918 PHINode *PHI = I.first; 7919 Constant *&NextPHI = NextIterVals[PHI]; 7920 if (!NextPHI) { // Not already computed. 7921 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7922 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7923 } 7924 if (NextPHI != I.second) 7925 StoppedEvolving = false; 7926 } 7927 7928 // If all entries in CurrentIterVals == NextIterVals then we can stop 7929 // iterating, the loop can't continue to change. 7930 if (StoppedEvolving) 7931 return RetVal = CurrentIterVals[PN]; 7932 7933 CurrentIterVals.swap(NextIterVals); 7934 } 7935 } 7936 7937 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7938 Value *Cond, 7939 bool ExitWhen) { 7940 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7941 if (!PN) return getCouldNotCompute(); 7942 7943 // If the loop is canonicalized, the PHI will have exactly two entries. 7944 // That's the only form we support here. 7945 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7946 7947 DenseMap<Instruction *, Constant *> CurrentIterVals; 7948 BasicBlock *Header = L->getHeader(); 7949 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7950 7951 BasicBlock *Latch = L->getLoopLatch(); 7952 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7953 7954 for (PHINode &PHI : Header->phis()) { 7955 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7956 CurrentIterVals[&PHI] = StartCST; 7957 } 7958 if (!CurrentIterVals.count(PN)) 7959 return getCouldNotCompute(); 7960 7961 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7962 // the loop symbolically to determine when the condition gets a value of 7963 // "ExitWhen". 7964 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7965 const DataLayout &DL = getDataLayout(); 7966 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7967 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7968 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7969 7970 // Couldn't symbolically evaluate. 7971 if (!CondVal) return getCouldNotCompute(); 7972 7973 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7974 ++NumBruteForceTripCountsComputed; 7975 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7976 } 7977 7978 // Update all the PHI nodes for the next iteration. 7979 DenseMap<Instruction *, Constant *> NextIterVals; 7980 7981 // Create a list of which PHIs we need to compute. We want to do this before 7982 // calling EvaluateExpression on them because that may invalidate iterators 7983 // into CurrentIterVals. 7984 SmallVector<PHINode *, 8> PHIsToCompute; 7985 for (const auto &I : CurrentIterVals) { 7986 PHINode *PHI = dyn_cast<PHINode>(I.first); 7987 if (!PHI || PHI->getParent() != Header) continue; 7988 PHIsToCompute.push_back(PHI); 7989 } 7990 for (PHINode *PHI : PHIsToCompute) { 7991 Constant *&NextPHI = NextIterVals[PHI]; 7992 if (NextPHI) continue; // Already computed! 7993 7994 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7995 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7996 } 7997 CurrentIterVals.swap(NextIterVals); 7998 } 7999 8000 // Too many iterations were needed to evaluate. 8001 return getCouldNotCompute(); 8002 } 8003 8004 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8005 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8006 ValuesAtScopes[V]; 8007 // Check to see if we've folded this expression at this loop before. 8008 for (auto &LS : Values) 8009 if (LS.first == L) 8010 return LS.second ? LS.second : V; 8011 8012 Values.emplace_back(L, nullptr); 8013 8014 // Otherwise compute it. 8015 const SCEV *C = computeSCEVAtScope(V, L); 8016 for (auto &LS : reverse(ValuesAtScopes[V])) 8017 if (LS.first == L) { 8018 LS.second = C; 8019 break; 8020 } 8021 return C; 8022 } 8023 8024 /// This builds up a Constant using the ConstantExpr interface. That way, we 8025 /// will return Constants for objects which aren't represented by a 8026 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8027 /// Returns NULL if the SCEV isn't representable as a Constant. 8028 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8029 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8030 case scCouldNotCompute: 8031 case scAddRecExpr: 8032 break; 8033 case scConstant: 8034 return cast<SCEVConstant>(V)->getValue(); 8035 case scUnknown: 8036 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8037 case scSignExtend: { 8038 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8039 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8040 return ConstantExpr::getSExt(CastOp, SS->getType()); 8041 break; 8042 } 8043 case scZeroExtend: { 8044 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8045 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8046 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8047 break; 8048 } 8049 case scTruncate: { 8050 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8051 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8052 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8053 break; 8054 } 8055 case scAddExpr: { 8056 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8057 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8058 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8059 unsigned AS = PTy->getAddressSpace(); 8060 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8061 C = ConstantExpr::getBitCast(C, DestPtrTy); 8062 } 8063 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8064 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8065 if (!C2) return nullptr; 8066 8067 // First pointer! 8068 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8069 unsigned AS = C2->getType()->getPointerAddressSpace(); 8070 std::swap(C, C2); 8071 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8072 // The offsets have been converted to bytes. We can add bytes to an 8073 // i8* by GEP with the byte count in the first index. 8074 C = ConstantExpr::getBitCast(C, DestPtrTy); 8075 } 8076 8077 // Don't bother trying to sum two pointers. We probably can't 8078 // statically compute a load that results from it anyway. 8079 if (C2->getType()->isPointerTy()) 8080 return nullptr; 8081 8082 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8083 if (PTy->getElementType()->isStructTy()) 8084 C2 = ConstantExpr::getIntegerCast( 8085 C2, Type::getInt32Ty(C->getContext()), true); 8086 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8087 } else 8088 C = ConstantExpr::getAdd(C, C2); 8089 } 8090 return C; 8091 } 8092 break; 8093 } 8094 case scMulExpr: { 8095 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8096 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8097 // Don't bother with pointers at all. 8098 if (C->getType()->isPointerTy()) return nullptr; 8099 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8100 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8101 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8102 C = ConstantExpr::getMul(C, C2); 8103 } 8104 return C; 8105 } 8106 break; 8107 } 8108 case scUDivExpr: { 8109 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8110 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8111 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8112 if (LHS->getType() == RHS->getType()) 8113 return ConstantExpr::getUDiv(LHS, RHS); 8114 break; 8115 } 8116 case scSMaxExpr: 8117 case scUMaxExpr: 8118 case scSMinExpr: 8119 case scUMinExpr: 8120 break; // TODO: smax, umax, smin, umax. 8121 } 8122 return nullptr; 8123 } 8124 8125 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8126 if (isa<SCEVConstant>(V)) return V; 8127 8128 // If this instruction is evolved from a constant-evolving PHI, compute the 8129 // exit value from the loop without using SCEVs. 8130 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8131 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8132 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8133 const Loop *LI = this->LI[I->getParent()]; 8134 // Looking for loop exit value. 8135 if (LI && LI->getParentLoop() == L && 8136 PN->getParent() == LI->getHeader()) { 8137 // Okay, there is no closed form solution for the PHI node. Check 8138 // to see if the loop that contains it has a known backedge-taken 8139 // count. If so, we may be able to force computation of the exit 8140 // value. 8141 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8142 // This trivial case can show up in some degenerate cases where 8143 // the incoming IR has not yet been fully simplified. 8144 if (BackedgeTakenCount->isZero()) { 8145 Value *InitValue = nullptr; 8146 bool MultipleInitValues = false; 8147 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8148 if (!LI->contains(PN->getIncomingBlock(i))) { 8149 if (!InitValue) 8150 InitValue = PN->getIncomingValue(i); 8151 else if (InitValue != PN->getIncomingValue(i)) { 8152 MultipleInitValues = true; 8153 break; 8154 } 8155 } 8156 } 8157 if (!MultipleInitValues && InitValue) 8158 return getSCEV(InitValue); 8159 } 8160 // Do we have a loop invariant value flowing around the backedge 8161 // for a loop which must execute the backedge? 8162 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8163 isKnownPositive(BackedgeTakenCount) && 8164 PN->getNumIncomingValues() == 2) { 8165 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8166 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8167 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8168 return OnBackedge; 8169 } 8170 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8171 // Okay, we know how many times the containing loop executes. If 8172 // this is a constant evolving PHI node, get the final value at 8173 // the specified iteration number. 8174 Constant *RV = 8175 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8176 if (RV) return getSCEV(RV); 8177 } 8178 } 8179 8180 // If there is a single-input Phi, evaluate it at our scope. If we can 8181 // prove that this replacement does not break LCSSA form, use new value. 8182 if (PN->getNumOperands() == 1) { 8183 const SCEV *Input = getSCEV(PN->getOperand(0)); 8184 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8185 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8186 // for the simplest case just support constants. 8187 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8188 } 8189 } 8190 8191 // Okay, this is an expression that we cannot symbolically evaluate 8192 // into a SCEV. Check to see if it's possible to symbolically evaluate 8193 // the arguments into constants, and if so, try to constant propagate the 8194 // result. This is particularly useful for computing loop exit values. 8195 if (CanConstantFold(I)) { 8196 SmallVector<Constant *, 4> Operands; 8197 bool MadeImprovement = false; 8198 for (Value *Op : I->operands()) { 8199 if (Constant *C = dyn_cast<Constant>(Op)) { 8200 Operands.push_back(C); 8201 continue; 8202 } 8203 8204 // If any of the operands is non-constant and if they are 8205 // non-integer and non-pointer, don't even try to analyze them 8206 // with scev techniques. 8207 if (!isSCEVable(Op->getType())) 8208 return V; 8209 8210 const SCEV *OrigV = getSCEV(Op); 8211 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8212 MadeImprovement |= OrigV != OpV; 8213 8214 Constant *C = BuildConstantFromSCEV(OpV); 8215 if (!C) return V; 8216 if (C->getType() != Op->getType()) 8217 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8218 Op->getType(), 8219 false), 8220 C, Op->getType()); 8221 Operands.push_back(C); 8222 } 8223 8224 // Check to see if getSCEVAtScope actually made an improvement. 8225 if (MadeImprovement) { 8226 Constant *C = nullptr; 8227 const DataLayout &DL = getDataLayout(); 8228 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8229 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8230 Operands[1], DL, &TLI); 8231 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8232 if (!LI->isVolatile()) 8233 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8234 } else 8235 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8236 if (!C) return V; 8237 return getSCEV(C); 8238 } 8239 } 8240 } 8241 8242 // This is some other type of SCEVUnknown, just return it. 8243 return V; 8244 } 8245 8246 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8247 // Avoid performing the look-up in the common case where the specified 8248 // expression has no loop-variant portions. 8249 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8250 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8251 if (OpAtScope != Comm->getOperand(i)) { 8252 // Okay, at least one of these operands is loop variant but might be 8253 // foldable. Build a new instance of the folded commutative expression. 8254 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8255 Comm->op_begin()+i); 8256 NewOps.push_back(OpAtScope); 8257 8258 for (++i; i != e; ++i) { 8259 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8260 NewOps.push_back(OpAtScope); 8261 } 8262 if (isa<SCEVAddExpr>(Comm)) 8263 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8264 if (isa<SCEVMulExpr>(Comm)) 8265 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8266 if (isa<SCEVMinMaxExpr>(Comm)) 8267 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8268 llvm_unreachable("Unknown commutative SCEV type!"); 8269 } 8270 } 8271 // If we got here, all operands are loop invariant. 8272 return Comm; 8273 } 8274 8275 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8276 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8277 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8278 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8279 return Div; // must be loop invariant 8280 return getUDivExpr(LHS, RHS); 8281 } 8282 8283 // If this is a loop recurrence for a loop that does not contain L, then we 8284 // are dealing with the final value computed by the loop. 8285 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8286 // First, attempt to evaluate each operand. 8287 // Avoid performing the look-up in the common case where the specified 8288 // expression has no loop-variant portions. 8289 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8290 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8291 if (OpAtScope == AddRec->getOperand(i)) 8292 continue; 8293 8294 // Okay, at least one of these operands is loop variant but might be 8295 // foldable. Build a new instance of the folded commutative expression. 8296 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8297 AddRec->op_begin()+i); 8298 NewOps.push_back(OpAtScope); 8299 for (++i; i != e; ++i) 8300 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8301 8302 const SCEV *FoldedRec = 8303 getAddRecExpr(NewOps, AddRec->getLoop(), 8304 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8305 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8306 // The addrec may be folded to a nonrecurrence, for example, if the 8307 // induction variable is multiplied by zero after constant folding. Go 8308 // ahead and return the folded value. 8309 if (!AddRec) 8310 return FoldedRec; 8311 break; 8312 } 8313 8314 // If the scope is outside the addrec's loop, evaluate it by using the 8315 // loop exit value of the addrec. 8316 if (!AddRec->getLoop()->contains(L)) { 8317 // To evaluate this recurrence, we need to know how many times the AddRec 8318 // loop iterates. Compute this now. 8319 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8320 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8321 8322 // Then, evaluate the AddRec. 8323 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8324 } 8325 8326 return AddRec; 8327 } 8328 8329 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8330 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8331 if (Op == Cast->getOperand()) 8332 return Cast; // must be loop invariant 8333 return getZeroExtendExpr(Op, Cast->getType()); 8334 } 8335 8336 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8337 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8338 if (Op == Cast->getOperand()) 8339 return Cast; // must be loop invariant 8340 return getSignExtendExpr(Op, Cast->getType()); 8341 } 8342 8343 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8344 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8345 if (Op == Cast->getOperand()) 8346 return Cast; // must be loop invariant 8347 return getTruncateExpr(Op, Cast->getType()); 8348 } 8349 8350 llvm_unreachable("Unknown SCEV type!"); 8351 } 8352 8353 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8354 return getSCEVAtScope(getSCEV(V), L); 8355 } 8356 8357 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8358 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8359 return stripInjectiveFunctions(ZExt->getOperand()); 8360 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8361 return stripInjectiveFunctions(SExt->getOperand()); 8362 return S; 8363 } 8364 8365 /// Finds the minimum unsigned root of the following equation: 8366 /// 8367 /// A * X = B (mod N) 8368 /// 8369 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8370 /// A and B isn't important. 8371 /// 8372 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8373 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8374 ScalarEvolution &SE) { 8375 uint32_t BW = A.getBitWidth(); 8376 assert(BW == SE.getTypeSizeInBits(B->getType())); 8377 assert(A != 0 && "A must be non-zero."); 8378 8379 // 1. D = gcd(A, N) 8380 // 8381 // The gcd of A and N may have only one prime factor: 2. The number of 8382 // trailing zeros in A is its multiplicity 8383 uint32_t Mult2 = A.countTrailingZeros(); 8384 // D = 2^Mult2 8385 8386 // 2. Check if B is divisible by D. 8387 // 8388 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8389 // is not less than multiplicity of this prime factor for D. 8390 if (SE.GetMinTrailingZeros(B) < Mult2) 8391 return SE.getCouldNotCompute(); 8392 8393 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8394 // modulo (N / D). 8395 // 8396 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8397 // (N / D) in general. The inverse itself always fits into BW bits, though, 8398 // so we immediately truncate it. 8399 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8400 APInt Mod(BW + 1, 0); 8401 Mod.setBit(BW - Mult2); // Mod = N / D 8402 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8403 8404 // 4. Compute the minimum unsigned root of the equation: 8405 // I * (B / D) mod (N / D) 8406 // To simplify the computation, we factor out the divide by D: 8407 // (I * B mod N) / D 8408 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8409 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8410 } 8411 8412 /// For a given quadratic addrec, generate coefficients of the corresponding 8413 /// quadratic equation, multiplied by a common value to ensure that they are 8414 /// integers. 8415 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8416 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8417 /// were multiplied by, and BitWidth is the bit width of the original addrec 8418 /// coefficients. 8419 /// This function returns None if the addrec coefficients are not compile- 8420 /// time constants. 8421 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8422 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8423 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8424 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8425 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8426 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8427 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8428 << *AddRec << '\n'); 8429 8430 // We currently can only solve this if the coefficients are constants. 8431 if (!LC || !MC || !NC) { 8432 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8433 return None; 8434 } 8435 8436 APInt L = LC->getAPInt(); 8437 APInt M = MC->getAPInt(); 8438 APInt N = NC->getAPInt(); 8439 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8440 8441 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8442 unsigned NewWidth = BitWidth + 1; 8443 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8444 << BitWidth << '\n'); 8445 // The sign-extension (as opposed to a zero-extension) here matches the 8446 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8447 N = N.sext(NewWidth); 8448 M = M.sext(NewWidth); 8449 L = L.sext(NewWidth); 8450 8451 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8452 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8453 // L+M, L+2M+N, L+3M+3N, ... 8454 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8455 // 8456 // The equation Acc = 0 is then 8457 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8458 // In a quadratic form it becomes: 8459 // N n^2 + (2M-N) n + 2L = 0. 8460 8461 APInt A = N; 8462 APInt B = 2 * M - A; 8463 APInt C = 2 * L; 8464 APInt T = APInt(NewWidth, 2); 8465 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8466 << "x + " << C << ", coeff bw: " << NewWidth 8467 << ", multiplied by " << T << '\n'); 8468 return std::make_tuple(A, B, C, T, BitWidth); 8469 } 8470 8471 /// Helper function to compare optional APInts: 8472 /// (a) if X and Y both exist, return min(X, Y), 8473 /// (b) if neither X nor Y exist, return None, 8474 /// (c) if exactly one of X and Y exists, return that value. 8475 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8476 if (X.hasValue() && Y.hasValue()) { 8477 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8478 APInt XW = X->sextOrSelf(W); 8479 APInt YW = Y->sextOrSelf(W); 8480 return XW.slt(YW) ? *X : *Y; 8481 } 8482 if (!X.hasValue() && !Y.hasValue()) 8483 return None; 8484 return X.hasValue() ? *X : *Y; 8485 } 8486 8487 /// Helper function to truncate an optional APInt to a given BitWidth. 8488 /// When solving addrec-related equations, it is preferable to return a value 8489 /// that has the same bit width as the original addrec's coefficients. If the 8490 /// solution fits in the original bit width, truncate it (except for i1). 8491 /// Returning a value of a different bit width may inhibit some optimizations. 8492 /// 8493 /// In general, a solution to a quadratic equation generated from an addrec 8494 /// may require BW+1 bits, where BW is the bit width of the addrec's 8495 /// coefficients. The reason is that the coefficients of the quadratic 8496 /// equation are BW+1 bits wide (to avoid truncation when converting from 8497 /// the addrec to the equation). 8498 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8499 if (!X.hasValue()) 8500 return None; 8501 unsigned W = X->getBitWidth(); 8502 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8503 return X->trunc(BitWidth); 8504 return X; 8505 } 8506 8507 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8508 /// iterations. The values L, M, N are assumed to be signed, and they 8509 /// should all have the same bit widths. 8510 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8511 /// where BW is the bit width of the addrec's coefficients. 8512 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8513 /// returned as such, otherwise the bit width of the returned value may 8514 /// be greater than BW. 8515 /// 8516 /// This function returns None if 8517 /// (a) the addrec coefficients are not constant, or 8518 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8519 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8520 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8521 static Optional<APInt> 8522 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8523 APInt A, B, C, M; 8524 unsigned BitWidth; 8525 auto T = GetQuadraticEquation(AddRec); 8526 if (!T.hasValue()) 8527 return None; 8528 8529 std::tie(A, B, C, M, BitWidth) = *T; 8530 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8531 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8532 if (!X.hasValue()) 8533 return None; 8534 8535 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8536 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8537 if (!V->isZero()) 8538 return None; 8539 8540 return TruncIfPossible(X, BitWidth); 8541 } 8542 8543 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8544 /// iterations. The values M, N are assumed to be signed, and they 8545 /// should all have the same bit widths. 8546 /// Find the least n such that c(n) does not belong to the given range, 8547 /// while c(n-1) does. 8548 /// 8549 /// This function returns None if 8550 /// (a) the addrec coefficients are not constant, or 8551 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8552 /// bounds of the range. 8553 static Optional<APInt> 8554 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8555 const ConstantRange &Range, ScalarEvolution &SE) { 8556 assert(AddRec->getOperand(0)->isZero() && 8557 "Starting value of addrec should be 0"); 8558 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8559 << Range << ", addrec " << *AddRec << '\n'); 8560 // This case is handled in getNumIterationsInRange. Here we can assume that 8561 // we start in the range. 8562 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8563 "Addrec's initial value should be in range"); 8564 8565 APInt A, B, C, M; 8566 unsigned BitWidth; 8567 auto T = GetQuadraticEquation(AddRec); 8568 if (!T.hasValue()) 8569 return None; 8570 8571 // Be careful about the return value: there can be two reasons for not 8572 // returning an actual number. First, if no solutions to the equations 8573 // were found, and second, if the solutions don't leave the given range. 8574 // The first case means that the actual solution is "unknown", the second 8575 // means that it's known, but not valid. If the solution is unknown, we 8576 // cannot make any conclusions. 8577 // Return a pair: the optional solution and a flag indicating if the 8578 // solution was found. 8579 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8580 // Solve for signed overflow and unsigned overflow, pick the lower 8581 // solution. 8582 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8583 << Bound << " (before multiplying by " << M << ")\n"); 8584 Bound *= M; // The quadratic equation multiplier. 8585 8586 Optional<APInt> SO = None; 8587 if (BitWidth > 1) { 8588 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8589 "signed overflow\n"); 8590 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8591 } 8592 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8593 "unsigned overflow\n"); 8594 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8595 BitWidth+1); 8596 8597 auto LeavesRange = [&] (const APInt &X) { 8598 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8599 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8600 if (Range.contains(V0->getValue())) 8601 return false; 8602 // X should be at least 1, so X-1 is non-negative. 8603 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8604 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8605 if (Range.contains(V1->getValue())) 8606 return true; 8607 return false; 8608 }; 8609 8610 // If SolveQuadraticEquationWrap returns None, it means that there can 8611 // be a solution, but the function failed to find it. We cannot treat it 8612 // as "no solution". 8613 if (!SO.hasValue() || !UO.hasValue()) 8614 return { None, false }; 8615 8616 // Check the smaller value first to see if it leaves the range. 8617 // At this point, both SO and UO must have values. 8618 Optional<APInt> Min = MinOptional(SO, UO); 8619 if (LeavesRange(*Min)) 8620 return { Min, true }; 8621 Optional<APInt> Max = Min == SO ? UO : SO; 8622 if (LeavesRange(*Max)) 8623 return { Max, true }; 8624 8625 // Solutions were found, but were eliminated, hence the "true". 8626 return { None, true }; 8627 }; 8628 8629 std::tie(A, B, C, M, BitWidth) = *T; 8630 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8631 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8632 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8633 auto SL = SolveForBoundary(Lower); 8634 auto SU = SolveForBoundary(Upper); 8635 // If any of the solutions was unknown, no meaninigful conclusions can 8636 // be made. 8637 if (!SL.second || !SU.second) 8638 return None; 8639 8640 // Claim: The correct solution is not some value between Min and Max. 8641 // 8642 // Justification: Assuming that Min and Max are different values, one of 8643 // them is when the first signed overflow happens, the other is when the 8644 // first unsigned overflow happens. Crossing the range boundary is only 8645 // possible via an overflow (treating 0 as a special case of it, modeling 8646 // an overflow as crossing k*2^W for some k). 8647 // 8648 // The interesting case here is when Min was eliminated as an invalid 8649 // solution, but Max was not. The argument is that if there was another 8650 // overflow between Min and Max, it would also have been eliminated if 8651 // it was considered. 8652 // 8653 // For a given boundary, it is possible to have two overflows of the same 8654 // type (signed/unsigned) without having the other type in between: this 8655 // can happen when the vertex of the parabola is between the iterations 8656 // corresponding to the overflows. This is only possible when the two 8657 // overflows cross k*2^W for the same k. In such case, if the second one 8658 // left the range (and was the first one to do so), the first overflow 8659 // would have to enter the range, which would mean that either we had left 8660 // the range before or that we started outside of it. Both of these cases 8661 // are contradictions. 8662 // 8663 // Claim: In the case where SolveForBoundary returns None, the correct 8664 // solution is not some value between the Max for this boundary and the 8665 // Min of the other boundary. 8666 // 8667 // Justification: Assume that we had such Max_A and Min_B corresponding 8668 // to range boundaries A and B and such that Max_A < Min_B. If there was 8669 // a solution between Max_A and Min_B, it would have to be caused by an 8670 // overflow corresponding to either A or B. It cannot correspond to B, 8671 // since Min_B is the first occurrence of such an overflow. If it 8672 // corresponded to A, it would have to be either a signed or an unsigned 8673 // overflow that is larger than both eliminated overflows for A. But 8674 // between the eliminated overflows and this overflow, the values would 8675 // cover the entire value space, thus crossing the other boundary, which 8676 // is a contradiction. 8677 8678 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8679 } 8680 8681 ScalarEvolution::ExitLimit 8682 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8683 bool AllowPredicates) { 8684 8685 // This is only used for loops with a "x != y" exit test. The exit condition 8686 // is now expressed as a single expression, V = x-y. So the exit test is 8687 // effectively V != 0. We know and take advantage of the fact that this 8688 // expression only being used in a comparison by zero context. 8689 8690 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8691 // If the value is a constant 8692 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8693 // If the value is already zero, the branch will execute zero times. 8694 if (C->getValue()->isZero()) return C; 8695 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8696 } 8697 8698 const SCEVAddRecExpr *AddRec = 8699 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8700 8701 if (!AddRec && AllowPredicates) 8702 // Try to make this an AddRec using runtime tests, in the first X 8703 // iterations of this loop, where X is the SCEV expression found by the 8704 // algorithm below. 8705 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8706 8707 if (!AddRec || AddRec->getLoop() != L) 8708 return getCouldNotCompute(); 8709 8710 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8711 // the quadratic equation to solve it. 8712 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8713 // We can only use this value if the chrec ends up with an exact zero 8714 // value at this index. When solving for "X*X != 5", for example, we 8715 // should not accept a root of 2. 8716 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8717 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8718 return ExitLimit(R, R, false, Predicates); 8719 } 8720 return getCouldNotCompute(); 8721 } 8722 8723 // Otherwise we can only handle this if it is affine. 8724 if (!AddRec->isAffine()) 8725 return getCouldNotCompute(); 8726 8727 // If this is an affine expression, the execution count of this branch is 8728 // the minimum unsigned root of the following equation: 8729 // 8730 // Start + Step*N = 0 (mod 2^BW) 8731 // 8732 // equivalent to: 8733 // 8734 // Step*N = -Start (mod 2^BW) 8735 // 8736 // where BW is the common bit width of Start and Step. 8737 8738 // Get the initial value for the loop. 8739 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8740 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8741 8742 // For now we handle only constant steps. 8743 // 8744 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8745 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8746 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8747 // We have not yet seen any such cases. 8748 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8749 if (!StepC || StepC->getValue()->isZero()) 8750 return getCouldNotCompute(); 8751 8752 // For positive steps (counting up until unsigned overflow): 8753 // N = -Start/Step (as unsigned) 8754 // For negative steps (counting down to zero): 8755 // N = Start/-Step 8756 // First compute the unsigned distance from zero in the direction of Step. 8757 bool CountDown = StepC->getAPInt().isNegative(); 8758 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8759 8760 // Handle unitary steps, which cannot wraparound. 8761 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8762 // N = Distance (as unsigned) 8763 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8764 APInt MaxBECount = getUnsignedRangeMax(Distance); 8765 8766 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8767 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8768 // case, and see if we can improve the bound. 8769 // 8770 // Explicitly handling this here is necessary because getUnsignedRange 8771 // isn't context-sensitive; it doesn't know that we only care about the 8772 // range inside the loop. 8773 const SCEV *Zero = getZero(Distance->getType()); 8774 const SCEV *One = getOne(Distance->getType()); 8775 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8776 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8777 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8778 // as "unsigned_max(Distance + 1) - 1". 8779 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8780 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8781 } 8782 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8783 } 8784 8785 // If the condition controls loop exit (the loop exits only if the expression 8786 // is true) and the addition is no-wrap we can use unsigned divide to 8787 // compute the backedge count. In this case, the step may not divide the 8788 // distance, but we don't care because if the condition is "missed" the loop 8789 // will have undefined behavior due to wrapping. 8790 if (ControlsExit && AddRec->hasNoSelfWrap() && 8791 loopHasNoAbnormalExits(AddRec->getLoop())) { 8792 const SCEV *Exact = 8793 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8794 const SCEV *Max = 8795 Exact == getCouldNotCompute() 8796 ? Exact 8797 : getConstant(getUnsignedRangeMax(Exact)); 8798 return ExitLimit(Exact, Max, false, Predicates); 8799 } 8800 8801 // Solve the general equation. 8802 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8803 getNegativeSCEV(Start), *this); 8804 const SCEV *M = E == getCouldNotCompute() 8805 ? E 8806 : getConstant(getUnsignedRangeMax(E)); 8807 return ExitLimit(E, M, false, Predicates); 8808 } 8809 8810 ScalarEvolution::ExitLimit 8811 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8812 // Loops that look like: while (X == 0) are very strange indeed. We don't 8813 // handle them yet except for the trivial case. This could be expanded in the 8814 // future as needed. 8815 8816 // If the value is a constant, check to see if it is known to be non-zero 8817 // already. If so, the backedge will execute zero times. 8818 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8819 if (!C->getValue()->isZero()) 8820 return getZero(C->getType()); 8821 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8822 } 8823 8824 // We could implement others, but I really doubt anyone writes loops like 8825 // this, and if they did, they would already be constant folded. 8826 return getCouldNotCompute(); 8827 } 8828 8829 std::pair<BasicBlock *, BasicBlock *> 8830 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8831 // If the block has a unique predecessor, then there is no path from the 8832 // predecessor to the block that does not go through the direct edge 8833 // from the predecessor to the block. 8834 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8835 return {Pred, BB}; 8836 8837 // A loop's header is defined to be a block that dominates the loop. 8838 // If the header has a unique predecessor outside the loop, it must be 8839 // a block that has exactly one successor that can reach the loop. 8840 if (Loop *L = LI.getLoopFor(BB)) 8841 return {L->getLoopPredecessor(), L->getHeader()}; 8842 8843 return {nullptr, nullptr}; 8844 } 8845 8846 /// SCEV structural equivalence is usually sufficient for testing whether two 8847 /// expressions are equal, however for the purposes of looking for a condition 8848 /// guarding a loop, it can be useful to be a little more general, since a 8849 /// front-end may have replicated the controlling expression. 8850 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8851 // Quick check to see if they are the same SCEV. 8852 if (A == B) return true; 8853 8854 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8855 // Not all instructions that are "identical" compute the same value. For 8856 // instance, two distinct alloca instructions allocating the same type are 8857 // identical and do not read memory; but compute distinct values. 8858 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8859 }; 8860 8861 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8862 // two different instructions with the same value. Check for this case. 8863 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8864 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8865 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8866 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8867 if (ComputesEqualValues(AI, BI)) 8868 return true; 8869 8870 // Otherwise assume they may have a different value. 8871 return false; 8872 } 8873 8874 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8875 const SCEV *&LHS, const SCEV *&RHS, 8876 unsigned Depth) { 8877 bool Changed = false; 8878 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8879 // '0 != 0'. 8880 auto TrivialCase = [&](bool TriviallyTrue) { 8881 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8882 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8883 return true; 8884 }; 8885 // If we hit the max recursion limit bail out. 8886 if (Depth >= 3) 8887 return false; 8888 8889 // Canonicalize a constant to the right side. 8890 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8891 // Check for both operands constant. 8892 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8893 if (ConstantExpr::getICmp(Pred, 8894 LHSC->getValue(), 8895 RHSC->getValue())->isNullValue()) 8896 return TrivialCase(false); 8897 else 8898 return TrivialCase(true); 8899 } 8900 // Otherwise swap the operands to put the constant on the right. 8901 std::swap(LHS, RHS); 8902 Pred = ICmpInst::getSwappedPredicate(Pred); 8903 Changed = true; 8904 } 8905 8906 // If we're comparing an addrec with a value which is loop-invariant in the 8907 // addrec's loop, put the addrec on the left. Also make a dominance check, 8908 // as both operands could be addrecs loop-invariant in each other's loop. 8909 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8910 const Loop *L = AR->getLoop(); 8911 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8912 std::swap(LHS, RHS); 8913 Pred = ICmpInst::getSwappedPredicate(Pred); 8914 Changed = true; 8915 } 8916 } 8917 8918 // If there's a constant operand, canonicalize comparisons with boundary 8919 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8920 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8921 const APInt &RA = RC->getAPInt(); 8922 8923 bool SimplifiedByConstantRange = false; 8924 8925 if (!ICmpInst::isEquality(Pred)) { 8926 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8927 if (ExactCR.isFullSet()) 8928 return TrivialCase(true); 8929 else if (ExactCR.isEmptySet()) 8930 return TrivialCase(false); 8931 8932 APInt NewRHS; 8933 CmpInst::Predicate NewPred; 8934 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8935 ICmpInst::isEquality(NewPred)) { 8936 // We were able to convert an inequality to an equality. 8937 Pred = NewPred; 8938 RHS = getConstant(NewRHS); 8939 Changed = SimplifiedByConstantRange = true; 8940 } 8941 } 8942 8943 if (!SimplifiedByConstantRange) { 8944 switch (Pred) { 8945 default: 8946 break; 8947 case ICmpInst::ICMP_EQ: 8948 case ICmpInst::ICMP_NE: 8949 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8950 if (!RA) 8951 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8952 if (const SCEVMulExpr *ME = 8953 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8954 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8955 ME->getOperand(0)->isAllOnesValue()) { 8956 RHS = AE->getOperand(1); 8957 LHS = ME->getOperand(1); 8958 Changed = true; 8959 } 8960 break; 8961 8962 8963 // The "Should have been caught earlier!" messages refer to the fact 8964 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8965 // should have fired on the corresponding cases, and canonicalized the 8966 // check to trivial case. 8967 8968 case ICmpInst::ICMP_UGE: 8969 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8970 Pred = ICmpInst::ICMP_UGT; 8971 RHS = getConstant(RA - 1); 8972 Changed = true; 8973 break; 8974 case ICmpInst::ICMP_ULE: 8975 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8976 Pred = ICmpInst::ICMP_ULT; 8977 RHS = getConstant(RA + 1); 8978 Changed = true; 8979 break; 8980 case ICmpInst::ICMP_SGE: 8981 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8982 Pred = ICmpInst::ICMP_SGT; 8983 RHS = getConstant(RA - 1); 8984 Changed = true; 8985 break; 8986 case ICmpInst::ICMP_SLE: 8987 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8988 Pred = ICmpInst::ICMP_SLT; 8989 RHS = getConstant(RA + 1); 8990 Changed = true; 8991 break; 8992 } 8993 } 8994 } 8995 8996 // Check for obvious equality. 8997 if (HasSameValue(LHS, RHS)) { 8998 if (ICmpInst::isTrueWhenEqual(Pred)) 8999 return TrivialCase(true); 9000 if (ICmpInst::isFalseWhenEqual(Pred)) 9001 return TrivialCase(false); 9002 } 9003 9004 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9005 // adding or subtracting 1 from one of the operands. 9006 switch (Pred) { 9007 case ICmpInst::ICMP_SLE: 9008 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9009 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9010 SCEV::FlagNSW); 9011 Pred = ICmpInst::ICMP_SLT; 9012 Changed = true; 9013 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9014 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9015 SCEV::FlagNSW); 9016 Pred = ICmpInst::ICMP_SLT; 9017 Changed = true; 9018 } 9019 break; 9020 case ICmpInst::ICMP_SGE: 9021 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9022 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9023 SCEV::FlagNSW); 9024 Pred = ICmpInst::ICMP_SGT; 9025 Changed = true; 9026 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9027 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9028 SCEV::FlagNSW); 9029 Pred = ICmpInst::ICMP_SGT; 9030 Changed = true; 9031 } 9032 break; 9033 case ICmpInst::ICMP_ULE: 9034 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9035 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9036 SCEV::FlagNUW); 9037 Pred = ICmpInst::ICMP_ULT; 9038 Changed = true; 9039 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9040 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9041 Pred = ICmpInst::ICMP_ULT; 9042 Changed = true; 9043 } 9044 break; 9045 case ICmpInst::ICMP_UGE: 9046 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9047 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9048 Pred = ICmpInst::ICMP_UGT; 9049 Changed = true; 9050 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9051 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9052 SCEV::FlagNUW); 9053 Pred = ICmpInst::ICMP_UGT; 9054 Changed = true; 9055 } 9056 break; 9057 default: 9058 break; 9059 } 9060 9061 // TODO: More simplifications are possible here. 9062 9063 // Recursively simplify until we either hit a recursion limit or nothing 9064 // changes. 9065 if (Changed) 9066 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9067 9068 return Changed; 9069 } 9070 9071 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9072 return getSignedRangeMax(S).isNegative(); 9073 } 9074 9075 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9076 return getSignedRangeMin(S).isStrictlyPositive(); 9077 } 9078 9079 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9080 return !getSignedRangeMin(S).isNegative(); 9081 } 9082 9083 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9084 return !getSignedRangeMax(S).isStrictlyPositive(); 9085 } 9086 9087 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9088 return isKnownNegative(S) || isKnownPositive(S); 9089 } 9090 9091 std::pair<const SCEV *, const SCEV *> 9092 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9093 // Compute SCEV on entry of loop L. 9094 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9095 if (Start == getCouldNotCompute()) 9096 return { Start, Start }; 9097 // Compute post increment SCEV for loop L. 9098 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9099 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9100 return { Start, PostInc }; 9101 } 9102 9103 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9104 const SCEV *LHS, const SCEV *RHS) { 9105 // First collect all loops. 9106 SmallPtrSet<const Loop *, 8> LoopsUsed; 9107 getUsedLoops(LHS, LoopsUsed); 9108 getUsedLoops(RHS, LoopsUsed); 9109 9110 if (LoopsUsed.empty()) 9111 return false; 9112 9113 // Domination relationship must be a linear order on collected loops. 9114 #ifndef NDEBUG 9115 for (auto *L1 : LoopsUsed) 9116 for (auto *L2 : LoopsUsed) 9117 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9118 DT.dominates(L2->getHeader(), L1->getHeader())) && 9119 "Domination relationship is not a linear order"); 9120 #endif 9121 9122 const Loop *MDL = 9123 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9124 [&](const Loop *L1, const Loop *L2) { 9125 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9126 }); 9127 9128 // Get init and post increment value for LHS. 9129 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9130 // if LHS contains unknown non-invariant SCEV then bail out. 9131 if (SplitLHS.first == getCouldNotCompute()) 9132 return false; 9133 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9134 // Get init and post increment value for RHS. 9135 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9136 // if RHS contains unknown non-invariant SCEV then bail out. 9137 if (SplitRHS.first == getCouldNotCompute()) 9138 return false; 9139 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9140 // It is possible that init SCEV contains an invariant load but it does 9141 // not dominate MDL and is not available at MDL loop entry, so we should 9142 // check it here. 9143 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9144 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9145 return false; 9146 9147 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9148 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9149 SplitRHS.second); 9150 } 9151 9152 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9153 const SCEV *LHS, const SCEV *RHS) { 9154 // Canonicalize the inputs first. 9155 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9156 9157 if (isKnownViaInduction(Pred, LHS, RHS)) 9158 return true; 9159 9160 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9161 return true; 9162 9163 // Otherwise see what can be done with some simple reasoning. 9164 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9165 } 9166 9167 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9168 const SCEVAddRecExpr *LHS, 9169 const SCEV *RHS) { 9170 const Loop *L = LHS->getLoop(); 9171 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9172 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9173 } 9174 9175 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9176 ICmpInst::Predicate Pred, 9177 bool &Increasing) { 9178 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9179 9180 #ifndef NDEBUG 9181 // Verify an invariant: inverting the predicate should turn a monotonically 9182 // increasing change to a monotonically decreasing one, and vice versa. 9183 bool IncreasingSwapped; 9184 bool ResultSwapped = isMonotonicPredicateImpl( 9185 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9186 9187 assert(Result == ResultSwapped && "should be able to analyze both!"); 9188 if (ResultSwapped) 9189 assert(Increasing == !IncreasingSwapped && 9190 "monotonicity should flip as we flip the predicate"); 9191 #endif 9192 9193 return Result; 9194 } 9195 9196 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9197 ICmpInst::Predicate Pred, 9198 bool &Increasing) { 9199 9200 // A zero step value for LHS means the induction variable is essentially a 9201 // loop invariant value. We don't really depend on the predicate actually 9202 // flipping from false to true (for increasing predicates, and the other way 9203 // around for decreasing predicates), all we care about is that *if* the 9204 // predicate changes then it only changes from false to true. 9205 // 9206 // A zero step value in itself is not very useful, but there may be places 9207 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9208 // as general as possible. 9209 9210 switch (Pred) { 9211 default: 9212 return false; // Conservative answer 9213 9214 case ICmpInst::ICMP_UGT: 9215 case ICmpInst::ICMP_UGE: 9216 case ICmpInst::ICMP_ULT: 9217 case ICmpInst::ICMP_ULE: 9218 if (!LHS->hasNoUnsignedWrap()) 9219 return false; 9220 9221 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9222 return true; 9223 9224 case ICmpInst::ICMP_SGT: 9225 case ICmpInst::ICMP_SGE: 9226 case ICmpInst::ICMP_SLT: 9227 case ICmpInst::ICMP_SLE: { 9228 if (!LHS->hasNoSignedWrap()) 9229 return false; 9230 9231 const SCEV *Step = LHS->getStepRecurrence(*this); 9232 9233 if (isKnownNonNegative(Step)) { 9234 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9235 return true; 9236 } 9237 9238 if (isKnownNonPositive(Step)) { 9239 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9240 return true; 9241 } 9242 9243 return false; 9244 } 9245 9246 } 9247 9248 llvm_unreachable("switch has default clause!"); 9249 } 9250 9251 bool ScalarEvolution::isLoopInvariantPredicate( 9252 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9253 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9254 const SCEV *&InvariantRHS) { 9255 9256 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9257 if (!isLoopInvariant(RHS, L)) { 9258 if (!isLoopInvariant(LHS, L)) 9259 return false; 9260 9261 std::swap(LHS, RHS); 9262 Pred = ICmpInst::getSwappedPredicate(Pred); 9263 } 9264 9265 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9266 if (!ArLHS || ArLHS->getLoop() != L) 9267 return false; 9268 9269 bool Increasing; 9270 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9271 return false; 9272 9273 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9274 // true as the loop iterates, and the backedge is control dependent on 9275 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9276 // 9277 // * if the predicate was false in the first iteration then the predicate 9278 // is never evaluated again, since the loop exits without taking the 9279 // backedge. 9280 // * if the predicate was true in the first iteration then it will 9281 // continue to be true for all future iterations since it is 9282 // monotonically increasing. 9283 // 9284 // For both the above possibilities, we can replace the loop varying 9285 // predicate with its value on the first iteration of the loop (which is 9286 // loop invariant). 9287 // 9288 // A similar reasoning applies for a monotonically decreasing predicate, by 9289 // replacing true with false and false with true in the above two bullets. 9290 9291 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9292 9293 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9294 return false; 9295 9296 InvariantPred = Pred; 9297 InvariantLHS = ArLHS->getStart(); 9298 InvariantRHS = RHS; 9299 return true; 9300 } 9301 9302 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9303 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9304 if (HasSameValue(LHS, RHS)) 9305 return ICmpInst::isTrueWhenEqual(Pred); 9306 9307 // This code is split out from isKnownPredicate because it is called from 9308 // within isLoopEntryGuardedByCond. 9309 9310 auto CheckRanges = 9311 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9312 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9313 .contains(RangeLHS); 9314 }; 9315 9316 // The check at the top of the function catches the case where the values are 9317 // known to be equal. 9318 if (Pred == CmpInst::ICMP_EQ) 9319 return false; 9320 9321 if (Pred == CmpInst::ICMP_NE) 9322 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9323 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9324 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9325 9326 if (CmpInst::isSigned(Pred)) 9327 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9328 9329 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9330 } 9331 9332 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9333 const SCEV *LHS, 9334 const SCEV *RHS) { 9335 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9336 // Return Y via OutY. 9337 auto MatchBinaryAddToConst = 9338 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9339 SCEV::NoWrapFlags ExpectedFlags) { 9340 const SCEV *NonConstOp, *ConstOp; 9341 SCEV::NoWrapFlags FlagsPresent; 9342 9343 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9344 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9345 return false; 9346 9347 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9348 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9349 }; 9350 9351 APInt C; 9352 9353 switch (Pred) { 9354 default: 9355 break; 9356 9357 case ICmpInst::ICMP_SGE: 9358 std::swap(LHS, RHS); 9359 LLVM_FALLTHROUGH; 9360 case ICmpInst::ICMP_SLE: 9361 // X s<= (X + C)<nsw> if C >= 0 9362 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9363 return true; 9364 9365 // (X + C)<nsw> s<= X if C <= 0 9366 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9367 !C.isStrictlyPositive()) 9368 return true; 9369 break; 9370 9371 case ICmpInst::ICMP_SGT: 9372 std::swap(LHS, RHS); 9373 LLVM_FALLTHROUGH; 9374 case ICmpInst::ICMP_SLT: 9375 // X s< (X + C)<nsw> if C > 0 9376 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9377 C.isStrictlyPositive()) 9378 return true; 9379 9380 // (X + C)<nsw> s< X if C < 0 9381 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9382 return true; 9383 break; 9384 } 9385 9386 return false; 9387 } 9388 9389 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9390 const SCEV *LHS, 9391 const SCEV *RHS) { 9392 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9393 return false; 9394 9395 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9396 // the stack can result in exponential time complexity. 9397 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9398 9399 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9400 // 9401 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9402 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9403 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9404 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9405 // use isKnownPredicate later if needed. 9406 return isKnownNonNegative(RHS) && 9407 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9408 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9409 } 9410 9411 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9412 ICmpInst::Predicate Pred, 9413 const SCEV *LHS, const SCEV *RHS) { 9414 // No need to even try if we know the module has no guards. 9415 if (!HasGuards) 9416 return false; 9417 9418 return any_of(*BB, [&](Instruction &I) { 9419 using namespace llvm::PatternMatch; 9420 9421 Value *Condition; 9422 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9423 m_Value(Condition))) && 9424 isImpliedCond(Pred, LHS, RHS, Condition, false); 9425 }); 9426 } 9427 9428 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9429 /// protected by a conditional between LHS and RHS. This is used to 9430 /// to eliminate casts. 9431 bool 9432 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9433 ICmpInst::Predicate Pred, 9434 const SCEV *LHS, const SCEV *RHS) { 9435 // Interpret a null as meaning no loop, where there is obviously no guard 9436 // (interprocedural conditions notwithstanding). 9437 if (!L) return true; 9438 9439 if (VerifyIR) 9440 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9441 "This cannot be done on broken IR!"); 9442 9443 9444 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9445 return true; 9446 9447 BasicBlock *Latch = L->getLoopLatch(); 9448 if (!Latch) 9449 return false; 9450 9451 BranchInst *LoopContinuePredicate = 9452 dyn_cast<BranchInst>(Latch->getTerminator()); 9453 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9454 isImpliedCond(Pred, LHS, RHS, 9455 LoopContinuePredicate->getCondition(), 9456 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9457 return true; 9458 9459 // We don't want more than one activation of the following loops on the stack 9460 // -- that can lead to O(n!) time complexity. 9461 if (WalkingBEDominatingConds) 9462 return false; 9463 9464 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9465 9466 // See if we can exploit a trip count to prove the predicate. 9467 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9468 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9469 if (LatchBECount != getCouldNotCompute()) { 9470 // We know that Latch branches back to the loop header exactly 9471 // LatchBECount times. This means the backdege condition at Latch is 9472 // equivalent to "{0,+,1} u< LatchBECount". 9473 Type *Ty = LatchBECount->getType(); 9474 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9475 const SCEV *LoopCounter = 9476 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9477 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9478 LatchBECount)) 9479 return true; 9480 } 9481 9482 // Check conditions due to any @llvm.assume intrinsics. 9483 for (auto &AssumeVH : AC.assumptions()) { 9484 if (!AssumeVH) 9485 continue; 9486 auto *CI = cast<CallInst>(AssumeVH); 9487 if (!DT.dominates(CI, Latch->getTerminator())) 9488 continue; 9489 9490 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9491 return true; 9492 } 9493 9494 // If the loop is not reachable from the entry block, we risk running into an 9495 // infinite loop as we walk up into the dom tree. These loops do not matter 9496 // anyway, so we just return a conservative answer when we see them. 9497 if (!DT.isReachableFromEntry(L->getHeader())) 9498 return false; 9499 9500 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9501 return true; 9502 9503 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9504 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9505 assert(DTN && "should reach the loop header before reaching the root!"); 9506 9507 BasicBlock *BB = DTN->getBlock(); 9508 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9509 return true; 9510 9511 BasicBlock *PBB = BB->getSinglePredecessor(); 9512 if (!PBB) 9513 continue; 9514 9515 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9516 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9517 continue; 9518 9519 Value *Condition = ContinuePredicate->getCondition(); 9520 9521 // If we have an edge `E` within the loop body that dominates the only 9522 // latch, the condition guarding `E` also guards the backedge. This 9523 // reasoning works only for loops with a single latch. 9524 9525 BasicBlockEdge DominatingEdge(PBB, BB); 9526 if (DominatingEdge.isSingleEdge()) { 9527 // We're constructively (and conservatively) enumerating edges within the 9528 // loop body that dominate the latch. The dominator tree better agree 9529 // with us on this: 9530 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9531 9532 if (isImpliedCond(Pred, LHS, RHS, Condition, 9533 BB != ContinuePredicate->getSuccessor(0))) 9534 return true; 9535 } 9536 } 9537 9538 return false; 9539 } 9540 9541 bool 9542 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9543 ICmpInst::Predicate Pred, 9544 const SCEV *LHS, const SCEV *RHS) { 9545 // Interpret a null as meaning no loop, where there is obviously no guard 9546 // (interprocedural conditions notwithstanding). 9547 if (!L) return false; 9548 9549 if (VerifyIR) 9550 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9551 "This cannot be done on broken IR!"); 9552 9553 // Both LHS and RHS must be available at loop entry. 9554 assert(isAvailableAtLoopEntry(LHS, L) && 9555 "LHS is not available at Loop Entry"); 9556 assert(isAvailableAtLoopEntry(RHS, L) && 9557 "RHS is not available at Loop Entry"); 9558 9559 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9560 return true; 9561 9562 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9563 // the facts (a >= b && a != b) separately. A typical situation is when the 9564 // non-strict comparison is known from ranges and non-equality is known from 9565 // dominating predicates. If we are proving strict comparison, we always try 9566 // to prove non-equality and non-strict comparison separately. 9567 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9568 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9569 bool ProvedNonStrictComparison = false; 9570 bool ProvedNonEquality = false; 9571 9572 if (ProvingStrictComparison) { 9573 ProvedNonStrictComparison = 9574 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9575 ProvedNonEquality = 9576 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9577 if (ProvedNonStrictComparison && ProvedNonEquality) 9578 return true; 9579 } 9580 9581 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9582 auto ProveViaGuard = [&](BasicBlock *Block) { 9583 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9584 return true; 9585 if (ProvingStrictComparison) { 9586 if (!ProvedNonStrictComparison) 9587 ProvedNonStrictComparison = 9588 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9589 if (!ProvedNonEquality) 9590 ProvedNonEquality = 9591 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9592 if (ProvedNonStrictComparison && ProvedNonEquality) 9593 return true; 9594 } 9595 return false; 9596 }; 9597 9598 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9599 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9600 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9601 return true; 9602 if (ProvingStrictComparison) { 9603 if (!ProvedNonStrictComparison) 9604 ProvedNonStrictComparison = 9605 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9606 if (!ProvedNonEquality) 9607 ProvedNonEquality = 9608 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9609 if (ProvedNonStrictComparison && ProvedNonEquality) 9610 return true; 9611 } 9612 return false; 9613 }; 9614 9615 // Starting at the loop predecessor, climb up the predecessor chain, as long 9616 // as there are predecessors that can be found that have unique successors 9617 // leading to the original header. 9618 for (std::pair<BasicBlock *, BasicBlock *> 9619 Pair(L->getLoopPredecessor(), L->getHeader()); 9620 Pair.first; 9621 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9622 9623 if (ProveViaGuard(Pair.first)) 9624 return true; 9625 9626 BranchInst *LoopEntryPredicate = 9627 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9628 if (!LoopEntryPredicate || 9629 LoopEntryPredicate->isUnconditional()) 9630 continue; 9631 9632 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9633 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9634 return true; 9635 } 9636 9637 // Check conditions due to any @llvm.assume intrinsics. 9638 for (auto &AssumeVH : AC.assumptions()) { 9639 if (!AssumeVH) 9640 continue; 9641 auto *CI = cast<CallInst>(AssumeVH); 9642 if (!DT.dominates(CI, L->getHeader())) 9643 continue; 9644 9645 if (ProveViaCond(CI->getArgOperand(0), false)) 9646 return true; 9647 } 9648 9649 return false; 9650 } 9651 9652 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9653 const SCEV *LHS, const SCEV *RHS, 9654 Value *FoundCondValue, 9655 bool Inverse) { 9656 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9657 return false; 9658 9659 auto ClearOnExit = 9660 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9661 9662 // Recursively handle And and Or conditions. 9663 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9664 if (BO->getOpcode() == Instruction::And) { 9665 if (!Inverse) 9666 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9667 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9668 } else if (BO->getOpcode() == Instruction::Or) { 9669 if (Inverse) 9670 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9671 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9672 } 9673 } 9674 9675 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9676 if (!ICI) return false; 9677 9678 // Now that we found a conditional branch that dominates the loop or controls 9679 // the loop latch. Check to see if it is the comparison we are looking for. 9680 ICmpInst::Predicate FoundPred; 9681 if (Inverse) 9682 FoundPred = ICI->getInversePredicate(); 9683 else 9684 FoundPred = ICI->getPredicate(); 9685 9686 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9687 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9688 9689 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9690 } 9691 9692 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9693 const SCEV *RHS, 9694 ICmpInst::Predicate FoundPred, 9695 const SCEV *FoundLHS, 9696 const SCEV *FoundRHS) { 9697 // Balance the types. 9698 if (getTypeSizeInBits(LHS->getType()) < 9699 getTypeSizeInBits(FoundLHS->getType())) { 9700 if (CmpInst::isSigned(Pred)) { 9701 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9702 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9703 } else { 9704 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9705 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9706 } 9707 } else if (getTypeSizeInBits(LHS->getType()) > 9708 getTypeSizeInBits(FoundLHS->getType())) { 9709 if (CmpInst::isSigned(FoundPred)) { 9710 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9711 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9712 } else { 9713 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9714 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9715 } 9716 } 9717 9718 // Canonicalize the query to match the way instcombine will have 9719 // canonicalized the comparison. 9720 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9721 if (LHS == RHS) 9722 return CmpInst::isTrueWhenEqual(Pred); 9723 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9724 if (FoundLHS == FoundRHS) 9725 return CmpInst::isFalseWhenEqual(FoundPred); 9726 9727 // Check to see if we can make the LHS or RHS match. 9728 if (LHS == FoundRHS || RHS == FoundLHS) { 9729 if (isa<SCEVConstant>(RHS)) { 9730 std::swap(FoundLHS, FoundRHS); 9731 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9732 } else { 9733 std::swap(LHS, RHS); 9734 Pred = ICmpInst::getSwappedPredicate(Pred); 9735 } 9736 } 9737 9738 // Check whether the found predicate is the same as the desired predicate. 9739 if (FoundPred == Pred) 9740 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9741 9742 // Check whether swapping the found predicate makes it the same as the 9743 // desired predicate. 9744 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9745 if (isa<SCEVConstant>(RHS)) 9746 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9747 else 9748 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9749 RHS, LHS, FoundLHS, FoundRHS); 9750 } 9751 9752 // Unsigned comparison is the same as signed comparison when both the operands 9753 // are non-negative. 9754 if (CmpInst::isUnsigned(FoundPred) && 9755 CmpInst::getSignedPredicate(FoundPred) == Pred && 9756 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9757 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9758 9759 // Check if we can make progress by sharpening ranges. 9760 if (FoundPred == ICmpInst::ICMP_NE && 9761 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9762 9763 const SCEVConstant *C = nullptr; 9764 const SCEV *V = nullptr; 9765 9766 if (isa<SCEVConstant>(FoundLHS)) { 9767 C = cast<SCEVConstant>(FoundLHS); 9768 V = FoundRHS; 9769 } else { 9770 C = cast<SCEVConstant>(FoundRHS); 9771 V = FoundLHS; 9772 } 9773 9774 // The guarding predicate tells us that C != V. If the known range 9775 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9776 // range we consider has to correspond to same signedness as the 9777 // predicate we're interested in folding. 9778 9779 APInt Min = ICmpInst::isSigned(Pred) ? 9780 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9781 9782 if (Min == C->getAPInt()) { 9783 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9784 // This is true even if (Min + 1) wraps around -- in case of 9785 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9786 9787 APInt SharperMin = Min + 1; 9788 9789 switch (Pred) { 9790 case ICmpInst::ICMP_SGE: 9791 case ICmpInst::ICMP_UGE: 9792 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9793 // RHS, we're done. 9794 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9795 getConstant(SharperMin))) 9796 return true; 9797 LLVM_FALLTHROUGH; 9798 9799 case ICmpInst::ICMP_SGT: 9800 case ICmpInst::ICMP_UGT: 9801 // We know from the range information that (V `Pred` Min || 9802 // V == Min). We know from the guarding condition that !(V 9803 // == Min). This gives us 9804 // 9805 // V `Pred` Min || V == Min && !(V == Min) 9806 // => V `Pred` Min 9807 // 9808 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9809 9810 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9811 return true; 9812 LLVM_FALLTHROUGH; 9813 9814 default: 9815 // No change 9816 break; 9817 } 9818 } 9819 } 9820 9821 // Check whether the actual condition is beyond sufficient. 9822 if (FoundPred == ICmpInst::ICMP_EQ) 9823 if (ICmpInst::isTrueWhenEqual(Pred)) 9824 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9825 return true; 9826 if (Pred == ICmpInst::ICMP_NE) 9827 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9828 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9829 return true; 9830 9831 // Otherwise assume the worst. 9832 return false; 9833 } 9834 9835 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9836 const SCEV *&L, const SCEV *&R, 9837 SCEV::NoWrapFlags &Flags) { 9838 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9839 if (!AE || AE->getNumOperands() != 2) 9840 return false; 9841 9842 L = AE->getOperand(0); 9843 R = AE->getOperand(1); 9844 Flags = AE->getNoWrapFlags(); 9845 return true; 9846 } 9847 9848 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9849 const SCEV *Less) { 9850 // We avoid subtracting expressions here because this function is usually 9851 // fairly deep in the call stack (i.e. is called many times). 9852 9853 // X - X = 0. 9854 if (More == Less) 9855 return APInt(getTypeSizeInBits(More->getType()), 0); 9856 9857 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9858 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9859 const auto *MAR = cast<SCEVAddRecExpr>(More); 9860 9861 if (LAR->getLoop() != MAR->getLoop()) 9862 return None; 9863 9864 // We look at affine expressions only; not for correctness but to keep 9865 // getStepRecurrence cheap. 9866 if (!LAR->isAffine() || !MAR->isAffine()) 9867 return None; 9868 9869 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9870 return None; 9871 9872 Less = LAR->getStart(); 9873 More = MAR->getStart(); 9874 9875 // fall through 9876 } 9877 9878 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9879 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9880 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9881 return M - L; 9882 } 9883 9884 SCEV::NoWrapFlags Flags; 9885 const SCEV *LLess = nullptr, *RLess = nullptr; 9886 const SCEV *LMore = nullptr, *RMore = nullptr; 9887 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9888 // Compare (X + C1) vs X. 9889 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9890 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9891 if (RLess == More) 9892 return -(C1->getAPInt()); 9893 9894 // Compare X vs (X + C2). 9895 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9896 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9897 if (RMore == Less) 9898 return C2->getAPInt(); 9899 9900 // Compare (X + C1) vs (X + C2). 9901 if (C1 && C2 && RLess == RMore) 9902 return C2->getAPInt() - C1->getAPInt(); 9903 9904 return None; 9905 } 9906 9907 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9908 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9909 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9910 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9911 return false; 9912 9913 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9914 if (!AddRecLHS) 9915 return false; 9916 9917 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9918 if (!AddRecFoundLHS) 9919 return false; 9920 9921 // We'd like to let SCEV reason about control dependencies, so we constrain 9922 // both the inequalities to be about add recurrences on the same loop. This 9923 // way we can use isLoopEntryGuardedByCond later. 9924 9925 const Loop *L = AddRecFoundLHS->getLoop(); 9926 if (L != AddRecLHS->getLoop()) 9927 return false; 9928 9929 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9930 // 9931 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9932 // ... (2) 9933 // 9934 // Informal proof for (2), assuming (1) [*]: 9935 // 9936 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9937 // 9938 // Then 9939 // 9940 // FoundLHS s< FoundRHS s< INT_MIN - C 9941 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9942 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9943 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9944 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9945 // <=> FoundLHS + C s< FoundRHS + C 9946 // 9947 // [*]: (1) can be proved by ruling out overflow. 9948 // 9949 // [**]: This can be proved by analyzing all the four possibilities: 9950 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9951 // (A s>= 0, B s>= 0). 9952 // 9953 // Note: 9954 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9955 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9956 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9957 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9958 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9959 // C)". 9960 9961 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9962 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9963 if (!LDiff || !RDiff || *LDiff != *RDiff) 9964 return false; 9965 9966 if (LDiff->isMinValue()) 9967 return true; 9968 9969 APInt FoundRHSLimit; 9970 9971 if (Pred == CmpInst::ICMP_ULT) { 9972 FoundRHSLimit = -(*RDiff); 9973 } else { 9974 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9975 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9976 } 9977 9978 // Try to prove (1) or (2), as needed. 9979 return isAvailableAtLoopEntry(FoundRHS, L) && 9980 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9981 getConstant(FoundRHSLimit)); 9982 } 9983 9984 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9985 const SCEV *LHS, const SCEV *RHS, 9986 const SCEV *FoundLHS, 9987 const SCEV *FoundRHS, unsigned Depth) { 9988 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9989 9990 auto ClearOnExit = make_scope_exit([&]() { 9991 if (LPhi) { 9992 bool Erased = PendingMerges.erase(LPhi); 9993 assert(Erased && "Failed to erase LPhi!"); 9994 (void)Erased; 9995 } 9996 if (RPhi) { 9997 bool Erased = PendingMerges.erase(RPhi); 9998 assert(Erased && "Failed to erase RPhi!"); 9999 (void)Erased; 10000 } 10001 }); 10002 10003 // Find respective Phis and check that they are not being pending. 10004 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10005 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10006 if (!PendingMerges.insert(Phi).second) 10007 return false; 10008 LPhi = Phi; 10009 } 10010 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10011 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10012 // If we detect a loop of Phi nodes being processed by this method, for 10013 // example: 10014 // 10015 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10016 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10017 // 10018 // we don't want to deal with a case that complex, so return conservative 10019 // answer false. 10020 if (!PendingMerges.insert(Phi).second) 10021 return false; 10022 RPhi = Phi; 10023 } 10024 10025 // If none of LHS, RHS is a Phi, nothing to do here. 10026 if (!LPhi && !RPhi) 10027 return false; 10028 10029 // If there is a SCEVUnknown Phi we are interested in, make it left. 10030 if (!LPhi) { 10031 std::swap(LHS, RHS); 10032 std::swap(FoundLHS, FoundRHS); 10033 std::swap(LPhi, RPhi); 10034 Pred = ICmpInst::getSwappedPredicate(Pred); 10035 } 10036 10037 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10038 const BasicBlock *LBB = LPhi->getParent(); 10039 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10040 10041 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10042 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10043 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10044 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10045 }; 10046 10047 if (RPhi && RPhi->getParent() == LBB) { 10048 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10049 // If we compare two Phis from the same block, and for each entry block 10050 // the predicate is true for incoming values from this block, then the 10051 // predicate is also true for the Phis. 10052 for (const BasicBlock *IncBB : predecessors(LBB)) { 10053 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10054 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10055 if (!ProvedEasily(L, R)) 10056 return false; 10057 } 10058 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10059 // Case two: RHS is also a Phi from the same basic block, and it is an 10060 // AddRec. It means that there is a loop which has both AddRec and Unknown 10061 // PHIs, for it we can compare incoming values of AddRec from above the loop 10062 // and latch with their respective incoming values of LPhi. 10063 // TODO: Generalize to handle loops with many inputs in a header. 10064 if (LPhi->getNumIncomingValues() != 2) return false; 10065 10066 auto *RLoop = RAR->getLoop(); 10067 auto *Predecessor = RLoop->getLoopPredecessor(); 10068 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10069 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10070 if (!ProvedEasily(L1, RAR->getStart())) 10071 return false; 10072 auto *Latch = RLoop->getLoopLatch(); 10073 assert(Latch && "Loop with AddRec with no latch?"); 10074 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10075 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10076 return false; 10077 } else { 10078 // In all other cases go over inputs of LHS and compare each of them to RHS, 10079 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10080 // At this point RHS is either a non-Phi, or it is a Phi from some block 10081 // different from LBB. 10082 for (const BasicBlock *IncBB : predecessors(LBB)) { 10083 // Check that RHS is available in this block. 10084 if (!dominates(RHS, IncBB)) 10085 return false; 10086 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10087 if (!ProvedEasily(L, RHS)) 10088 return false; 10089 } 10090 } 10091 return true; 10092 } 10093 10094 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10095 const SCEV *LHS, const SCEV *RHS, 10096 const SCEV *FoundLHS, 10097 const SCEV *FoundRHS) { 10098 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10099 return true; 10100 10101 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10102 return true; 10103 10104 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10105 FoundLHS, FoundRHS) || 10106 // ~x < ~y --> x > y 10107 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10108 getNotSCEV(FoundRHS), 10109 getNotSCEV(FoundLHS)); 10110 } 10111 10112 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10113 template <typename MinMaxExprType> 10114 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10115 const SCEV *Candidate) { 10116 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10117 if (!MinMaxExpr) 10118 return false; 10119 10120 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10121 } 10122 10123 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10124 ICmpInst::Predicate Pred, 10125 const SCEV *LHS, const SCEV *RHS) { 10126 // If both sides are affine addrecs for the same loop, with equal 10127 // steps, and we know the recurrences don't wrap, then we only 10128 // need to check the predicate on the starting values. 10129 10130 if (!ICmpInst::isRelational(Pred)) 10131 return false; 10132 10133 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10134 if (!LAR) 10135 return false; 10136 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10137 if (!RAR) 10138 return false; 10139 if (LAR->getLoop() != RAR->getLoop()) 10140 return false; 10141 if (!LAR->isAffine() || !RAR->isAffine()) 10142 return false; 10143 10144 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10145 return false; 10146 10147 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10148 SCEV::FlagNSW : SCEV::FlagNUW; 10149 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10150 return false; 10151 10152 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10153 } 10154 10155 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10156 /// expression? 10157 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10158 ICmpInst::Predicate Pred, 10159 const SCEV *LHS, const SCEV *RHS) { 10160 switch (Pred) { 10161 default: 10162 return false; 10163 10164 case ICmpInst::ICMP_SGE: 10165 std::swap(LHS, RHS); 10166 LLVM_FALLTHROUGH; 10167 case ICmpInst::ICMP_SLE: 10168 return 10169 // min(A, ...) <= A 10170 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10171 // A <= max(A, ...) 10172 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10173 10174 case ICmpInst::ICMP_UGE: 10175 std::swap(LHS, RHS); 10176 LLVM_FALLTHROUGH; 10177 case ICmpInst::ICMP_ULE: 10178 return 10179 // min(A, ...) <= A 10180 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10181 // A <= max(A, ...) 10182 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10183 } 10184 10185 llvm_unreachable("covered switch fell through?!"); 10186 } 10187 10188 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10189 const SCEV *LHS, const SCEV *RHS, 10190 const SCEV *FoundLHS, 10191 const SCEV *FoundRHS, 10192 unsigned Depth) { 10193 assert(getTypeSizeInBits(LHS->getType()) == 10194 getTypeSizeInBits(RHS->getType()) && 10195 "LHS and RHS have different sizes?"); 10196 assert(getTypeSizeInBits(FoundLHS->getType()) == 10197 getTypeSizeInBits(FoundRHS->getType()) && 10198 "FoundLHS and FoundRHS have different sizes?"); 10199 // We want to avoid hurting the compile time with analysis of too big trees. 10200 if (Depth > MaxSCEVOperationsImplicationDepth) 10201 return false; 10202 // We only want to work with ICMP_SGT comparison so far. 10203 // TODO: Extend to ICMP_UGT? 10204 if (Pred == ICmpInst::ICMP_SLT) { 10205 Pred = ICmpInst::ICMP_SGT; 10206 std::swap(LHS, RHS); 10207 std::swap(FoundLHS, FoundRHS); 10208 } 10209 if (Pred != ICmpInst::ICMP_SGT) 10210 return false; 10211 10212 auto GetOpFromSExt = [&](const SCEV *S) { 10213 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10214 return Ext->getOperand(); 10215 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10216 // the constant in some cases. 10217 return S; 10218 }; 10219 10220 // Acquire values from extensions. 10221 auto *OrigLHS = LHS; 10222 auto *OrigFoundLHS = FoundLHS; 10223 LHS = GetOpFromSExt(LHS); 10224 FoundLHS = GetOpFromSExt(FoundLHS); 10225 10226 // Is the SGT predicate can be proved trivially or using the found context. 10227 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10228 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10229 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10230 FoundRHS, Depth + 1); 10231 }; 10232 10233 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10234 // We want to avoid creation of any new non-constant SCEV. Since we are 10235 // going to compare the operands to RHS, we should be certain that we don't 10236 // need any size extensions for this. So let's decline all cases when the 10237 // sizes of types of LHS and RHS do not match. 10238 // TODO: Maybe try to get RHS from sext to catch more cases? 10239 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10240 return false; 10241 10242 // Should not overflow. 10243 if (!LHSAddExpr->hasNoSignedWrap()) 10244 return false; 10245 10246 auto *LL = LHSAddExpr->getOperand(0); 10247 auto *LR = LHSAddExpr->getOperand(1); 10248 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10249 10250 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10251 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10252 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10253 }; 10254 // Try to prove the following rule: 10255 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10256 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10257 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10258 return true; 10259 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10260 Value *LL, *LR; 10261 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10262 10263 using namespace llvm::PatternMatch; 10264 10265 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10266 // Rules for division. 10267 // We are going to perform some comparisons with Denominator and its 10268 // derivative expressions. In general case, creating a SCEV for it may 10269 // lead to a complex analysis of the entire graph, and in particular it 10270 // can request trip count recalculation for the same loop. This would 10271 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10272 // this, we only want to create SCEVs that are constants in this section. 10273 // So we bail if Denominator is not a constant. 10274 if (!isa<ConstantInt>(LR)) 10275 return false; 10276 10277 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10278 10279 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10280 // then a SCEV for the numerator already exists and matches with FoundLHS. 10281 auto *Numerator = getExistingSCEV(LL); 10282 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10283 return false; 10284 10285 // Make sure that the numerator matches with FoundLHS and the denominator 10286 // is positive. 10287 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10288 return false; 10289 10290 auto *DTy = Denominator->getType(); 10291 auto *FRHSTy = FoundRHS->getType(); 10292 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10293 // One of types is a pointer and another one is not. We cannot extend 10294 // them properly to a wider type, so let us just reject this case. 10295 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10296 // to avoid this check. 10297 return false; 10298 10299 // Given that: 10300 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10301 auto *WTy = getWiderType(DTy, FRHSTy); 10302 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10303 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10304 10305 // Try to prove the following rule: 10306 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10307 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10308 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10309 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10310 if (isKnownNonPositive(RHS) && 10311 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10312 return true; 10313 10314 // Try to prove the following rule: 10315 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10316 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10317 // If we divide it by Denominator > 2, then: 10318 // 1. If FoundLHS is negative, then the result is 0. 10319 // 2. If FoundLHS is non-negative, then the result is non-negative. 10320 // Anyways, the result is non-negative. 10321 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10322 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10323 if (isKnownNegative(RHS) && 10324 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10325 return true; 10326 } 10327 } 10328 10329 // If our expression contained SCEVUnknown Phis, and we split it down and now 10330 // need to prove something for them, try to prove the predicate for every 10331 // possible incoming values of those Phis. 10332 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10333 return true; 10334 10335 return false; 10336 } 10337 10338 bool 10339 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10340 const SCEV *LHS, const SCEV *RHS) { 10341 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10342 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10343 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10344 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10345 } 10346 10347 bool 10348 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10349 const SCEV *LHS, const SCEV *RHS, 10350 const SCEV *FoundLHS, 10351 const SCEV *FoundRHS) { 10352 switch (Pred) { 10353 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10354 case ICmpInst::ICMP_EQ: 10355 case ICmpInst::ICMP_NE: 10356 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10357 return true; 10358 break; 10359 case ICmpInst::ICMP_SLT: 10360 case ICmpInst::ICMP_SLE: 10361 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10362 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10363 return true; 10364 break; 10365 case ICmpInst::ICMP_SGT: 10366 case ICmpInst::ICMP_SGE: 10367 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10368 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10369 return true; 10370 break; 10371 case ICmpInst::ICMP_ULT: 10372 case ICmpInst::ICMP_ULE: 10373 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10374 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10375 return true; 10376 break; 10377 case ICmpInst::ICMP_UGT: 10378 case ICmpInst::ICMP_UGE: 10379 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10380 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10381 return true; 10382 break; 10383 } 10384 10385 // Maybe it can be proved via operations? 10386 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10387 return true; 10388 10389 return false; 10390 } 10391 10392 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10393 const SCEV *LHS, 10394 const SCEV *RHS, 10395 const SCEV *FoundLHS, 10396 const SCEV *FoundRHS) { 10397 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10398 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10399 // reduce the compile time impact of this optimization. 10400 return false; 10401 10402 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10403 if (!Addend) 10404 return false; 10405 10406 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10407 10408 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10409 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10410 ConstantRange FoundLHSRange = 10411 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10412 10413 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10414 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10415 10416 // We can also compute the range of values for `LHS` that satisfy the 10417 // consequent, "`LHS` `Pred` `RHS`": 10418 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10419 ConstantRange SatisfyingLHSRange = 10420 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10421 10422 // The antecedent implies the consequent if every value of `LHS` that 10423 // satisfies the antecedent also satisfies the consequent. 10424 return SatisfyingLHSRange.contains(LHSRange); 10425 } 10426 10427 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10428 bool IsSigned, bool NoWrap) { 10429 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10430 10431 if (NoWrap) return false; 10432 10433 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10434 const SCEV *One = getOne(Stride->getType()); 10435 10436 if (IsSigned) { 10437 APInt MaxRHS = getSignedRangeMax(RHS); 10438 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10439 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10440 10441 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10442 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10443 } 10444 10445 APInt MaxRHS = getUnsignedRangeMax(RHS); 10446 APInt MaxValue = APInt::getMaxValue(BitWidth); 10447 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10448 10449 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10450 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10451 } 10452 10453 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10454 bool IsSigned, bool NoWrap) { 10455 if (NoWrap) return false; 10456 10457 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10458 const SCEV *One = getOne(Stride->getType()); 10459 10460 if (IsSigned) { 10461 APInt MinRHS = getSignedRangeMin(RHS); 10462 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10463 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10464 10465 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10466 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10467 } 10468 10469 APInt MinRHS = getUnsignedRangeMin(RHS); 10470 APInt MinValue = APInt::getMinValue(BitWidth); 10471 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10472 10473 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10474 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10475 } 10476 10477 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10478 bool Equality) { 10479 const SCEV *One = getOne(Step->getType()); 10480 Delta = Equality ? getAddExpr(Delta, Step) 10481 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10482 return getUDivExpr(Delta, Step); 10483 } 10484 10485 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10486 const SCEV *Stride, 10487 const SCEV *End, 10488 unsigned BitWidth, 10489 bool IsSigned) { 10490 10491 assert(!isKnownNonPositive(Stride) && 10492 "Stride is expected strictly positive!"); 10493 // Calculate the maximum backedge count based on the range of values 10494 // permitted by Start, End, and Stride. 10495 const SCEV *MaxBECount; 10496 APInt MinStart = 10497 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10498 10499 APInt StrideForMaxBECount = 10500 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10501 10502 // We already know that the stride is positive, so we paper over conservatism 10503 // in our range computation by forcing StrideForMaxBECount to be at least one. 10504 // In theory this is unnecessary, but we expect MaxBECount to be a 10505 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10506 // is nothing to constant fold it to). 10507 APInt One(BitWidth, 1, IsSigned); 10508 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10509 10510 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10511 : APInt::getMaxValue(BitWidth); 10512 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10513 10514 // Although End can be a MAX expression we estimate MaxEnd considering only 10515 // the case End = RHS of the loop termination condition. This is safe because 10516 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10517 // taken count. 10518 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10519 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10520 10521 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10522 getConstant(StrideForMaxBECount) /* Step */, 10523 false /* Equality */); 10524 10525 return MaxBECount; 10526 } 10527 10528 ScalarEvolution::ExitLimit 10529 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10530 const Loop *L, bool IsSigned, 10531 bool ControlsExit, bool AllowPredicates) { 10532 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10533 10534 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10535 bool PredicatedIV = false; 10536 10537 if (!IV && AllowPredicates) { 10538 // Try to make this an AddRec using runtime tests, in the first X 10539 // iterations of this loop, where X is the SCEV expression found by the 10540 // algorithm below. 10541 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10542 PredicatedIV = true; 10543 } 10544 10545 // Avoid weird loops 10546 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10547 return getCouldNotCompute(); 10548 10549 bool NoWrap = ControlsExit && 10550 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10551 10552 const SCEV *Stride = IV->getStepRecurrence(*this); 10553 10554 bool PositiveStride = isKnownPositive(Stride); 10555 10556 // Avoid negative or zero stride values. 10557 if (!PositiveStride) { 10558 // We can compute the correct backedge taken count for loops with unknown 10559 // strides if we can prove that the loop is not an infinite loop with side 10560 // effects. Here's the loop structure we are trying to handle - 10561 // 10562 // i = start 10563 // do { 10564 // A[i] = i; 10565 // i += s; 10566 // } while (i < end); 10567 // 10568 // The backedge taken count for such loops is evaluated as - 10569 // (max(end, start + stride) - start - 1) /u stride 10570 // 10571 // The additional preconditions that we need to check to prove correctness 10572 // of the above formula is as follows - 10573 // 10574 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10575 // NoWrap flag). 10576 // b) loop is single exit with no side effects. 10577 // 10578 // 10579 // Precondition a) implies that if the stride is negative, this is a single 10580 // trip loop. The backedge taken count formula reduces to zero in this case. 10581 // 10582 // Precondition b) implies that the unknown stride cannot be zero otherwise 10583 // we have UB. 10584 // 10585 // The positive stride case is the same as isKnownPositive(Stride) returning 10586 // true (original behavior of the function). 10587 // 10588 // We want to make sure that the stride is truly unknown as there are edge 10589 // cases where ScalarEvolution propagates no wrap flags to the 10590 // post-increment/decrement IV even though the increment/decrement operation 10591 // itself is wrapping. The computed backedge taken count may be wrong in 10592 // such cases. This is prevented by checking that the stride is not known to 10593 // be either positive or non-positive. For example, no wrap flags are 10594 // propagated to the post-increment IV of this loop with a trip count of 2 - 10595 // 10596 // unsigned char i; 10597 // for(i=127; i<128; i+=129) 10598 // A[i] = i; 10599 // 10600 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10601 !loopHasNoSideEffects(L)) 10602 return getCouldNotCompute(); 10603 } else if (!Stride->isOne() && 10604 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10605 // Avoid proven overflow cases: this will ensure that the backedge taken 10606 // count will not generate any unsigned overflow. Relaxed no-overflow 10607 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10608 // undefined behaviors like the case of C language. 10609 return getCouldNotCompute(); 10610 10611 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10612 : ICmpInst::ICMP_ULT; 10613 const SCEV *Start = IV->getStart(); 10614 const SCEV *End = RHS; 10615 // When the RHS is not invariant, we do not know the end bound of the loop and 10616 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10617 // calculate the MaxBECount, given the start, stride and max value for the end 10618 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10619 // checked above). 10620 if (!isLoopInvariant(RHS, L)) { 10621 const SCEV *MaxBECount = computeMaxBECountForLT( 10622 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10623 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10624 false /*MaxOrZero*/, Predicates); 10625 } 10626 // If the backedge is taken at least once, then it will be taken 10627 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10628 // is the LHS value of the less-than comparison the first time it is evaluated 10629 // and End is the RHS. 10630 const SCEV *BECountIfBackedgeTaken = 10631 computeBECount(getMinusSCEV(End, Start), Stride, false); 10632 // If the loop entry is guarded by the result of the backedge test of the 10633 // first loop iteration, then we know the backedge will be taken at least 10634 // once and so the backedge taken count is as above. If not then we use the 10635 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10636 // as if the backedge is taken at least once max(End,Start) is End and so the 10637 // result is as above, and if not max(End,Start) is Start so we get a backedge 10638 // count of zero. 10639 const SCEV *BECount; 10640 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10641 BECount = BECountIfBackedgeTaken; 10642 else { 10643 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10644 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10645 } 10646 10647 const SCEV *MaxBECount; 10648 bool MaxOrZero = false; 10649 if (isa<SCEVConstant>(BECount)) 10650 MaxBECount = BECount; 10651 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10652 // If we know exactly how many times the backedge will be taken if it's 10653 // taken at least once, then the backedge count will either be that or 10654 // zero. 10655 MaxBECount = BECountIfBackedgeTaken; 10656 MaxOrZero = true; 10657 } else { 10658 MaxBECount = computeMaxBECountForLT( 10659 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10660 } 10661 10662 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10663 !isa<SCEVCouldNotCompute>(BECount)) 10664 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10665 10666 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10667 } 10668 10669 ScalarEvolution::ExitLimit 10670 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10671 const Loop *L, bool IsSigned, 10672 bool ControlsExit, bool AllowPredicates) { 10673 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10674 // We handle only IV > Invariant 10675 if (!isLoopInvariant(RHS, L)) 10676 return getCouldNotCompute(); 10677 10678 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10679 if (!IV && AllowPredicates) 10680 // Try to make this an AddRec using runtime tests, in the first X 10681 // iterations of this loop, where X is the SCEV expression found by the 10682 // algorithm below. 10683 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10684 10685 // Avoid weird loops 10686 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10687 return getCouldNotCompute(); 10688 10689 bool NoWrap = ControlsExit && 10690 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10691 10692 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10693 10694 // Avoid negative or zero stride values 10695 if (!isKnownPositive(Stride)) 10696 return getCouldNotCompute(); 10697 10698 // Avoid proven overflow cases: this will ensure that the backedge taken count 10699 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10700 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10701 // behaviors like the case of C language. 10702 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10703 return getCouldNotCompute(); 10704 10705 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10706 : ICmpInst::ICMP_UGT; 10707 10708 const SCEV *Start = IV->getStart(); 10709 const SCEV *End = RHS; 10710 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10711 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10712 10713 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10714 10715 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10716 : getUnsignedRangeMax(Start); 10717 10718 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10719 : getUnsignedRangeMin(Stride); 10720 10721 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10722 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10723 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10724 10725 // Although End can be a MIN expression we estimate MinEnd considering only 10726 // the case End = RHS. This is safe because in the other case (Start - End) 10727 // is zero, leading to a zero maximum backedge taken count. 10728 APInt MinEnd = 10729 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10730 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10731 10732 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10733 ? BECount 10734 : computeBECount(getConstant(MaxStart - MinEnd), 10735 getConstant(MinStride), false); 10736 10737 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10738 MaxBECount = BECount; 10739 10740 return ExitLimit(BECount, MaxBECount, false, Predicates); 10741 } 10742 10743 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10744 ScalarEvolution &SE) const { 10745 if (Range.isFullSet()) // Infinite loop. 10746 return SE.getCouldNotCompute(); 10747 10748 // If the start is a non-zero constant, shift the range to simplify things. 10749 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10750 if (!SC->getValue()->isZero()) { 10751 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10752 Operands[0] = SE.getZero(SC->getType()); 10753 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10754 getNoWrapFlags(FlagNW)); 10755 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10756 return ShiftedAddRec->getNumIterationsInRange( 10757 Range.subtract(SC->getAPInt()), SE); 10758 // This is strange and shouldn't happen. 10759 return SE.getCouldNotCompute(); 10760 } 10761 10762 // The only time we can solve this is when we have all constant indices. 10763 // Otherwise, we cannot determine the overflow conditions. 10764 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10765 return SE.getCouldNotCompute(); 10766 10767 // Okay at this point we know that all elements of the chrec are constants and 10768 // that the start element is zero. 10769 10770 // First check to see if the range contains zero. If not, the first 10771 // iteration exits. 10772 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10773 if (!Range.contains(APInt(BitWidth, 0))) 10774 return SE.getZero(getType()); 10775 10776 if (isAffine()) { 10777 // If this is an affine expression then we have this situation: 10778 // Solve {0,+,A} in Range === Ax in Range 10779 10780 // We know that zero is in the range. If A is positive then we know that 10781 // the upper value of the range must be the first possible exit value. 10782 // If A is negative then the lower of the range is the last possible loop 10783 // value. Also note that we already checked for a full range. 10784 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10785 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10786 10787 // The exit value should be (End+A)/A. 10788 APInt ExitVal = (End + A).udiv(A); 10789 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10790 10791 // Evaluate at the exit value. If we really did fall out of the valid 10792 // range, then we computed our trip count, otherwise wrap around or other 10793 // things must have happened. 10794 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10795 if (Range.contains(Val->getValue())) 10796 return SE.getCouldNotCompute(); // Something strange happened 10797 10798 // Ensure that the previous value is in the range. This is a sanity check. 10799 assert(Range.contains( 10800 EvaluateConstantChrecAtConstant(this, 10801 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10802 "Linear scev computation is off in a bad way!"); 10803 return SE.getConstant(ExitValue); 10804 } 10805 10806 if (isQuadratic()) { 10807 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10808 return SE.getConstant(S.getValue()); 10809 } 10810 10811 return SE.getCouldNotCompute(); 10812 } 10813 10814 const SCEVAddRecExpr * 10815 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10816 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10817 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10818 // but in this case we cannot guarantee that the value returned will be an 10819 // AddRec because SCEV does not have a fixed point where it stops 10820 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10821 // may happen if we reach arithmetic depth limit while simplifying. So we 10822 // construct the returned value explicitly. 10823 SmallVector<const SCEV *, 3> Ops; 10824 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10825 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10826 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10827 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10828 // We know that the last operand is not a constant zero (otherwise it would 10829 // have been popped out earlier). This guarantees us that if the result has 10830 // the same last operand, then it will also not be popped out, meaning that 10831 // the returned value will be an AddRec. 10832 const SCEV *Last = getOperand(getNumOperands() - 1); 10833 assert(!Last->isZero() && "Recurrency with zero step?"); 10834 Ops.push_back(Last); 10835 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10836 SCEV::FlagAnyWrap)); 10837 } 10838 10839 // Return true when S contains at least an undef value. 10840 static inline bool containsUndefs(const SCEV *S) { 10841 return SCEVExprContains(S, [](const SCEV *S) { 10842 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10843 return isa<UndefValue>(SU->getValue()); 10844 return false; 10845 }); 10846 } 10847 10848 namespace { 10849 10850 // Collect all steps of SCEV expressions. 10851 struct SCEVCollectStrides { 10852 ScalarEvolution &SE; 10853 SmallVectorImpl<const SCEV *> &Strides; 10854 10855 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10856 : SE(SE), Strides(S) {} 10857 10858 bool follow(const SCEV *S) { 10859 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10860 Strides.push_back(AR->getStepRecurrence(SE)); 10861 return true; 10862 } 10863 10864 bool isDone() const { return false; } 10865 }; 10866 10867 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10868 struct SCEVCollectTerms { 10869 SmallVectorImpl<const SCEV *> &Terms; 10870 10871 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10872 10873 bool follow(const SCEV *S) { 10874 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10875 isa<SCEVSignExtendExpr>(S)) { 10876 if (!containsUndefs(S)) 10877 Terms.push_back(S); 10878 10879 // Stop recursion: once we collected a term, do not walk its operands. 10880 return false; 10881 } 10882 10883 // Keep looking. 10884 return true; 10885 } 10886 10887 bool isDone() const { return false; } 10888 }; 10889 10890 // Check if a SCEV contains an AddRecExpr. 10891 struct SCEVHasAddRec { 10892 bool &ContainsAddRec; 10893 10894 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10895 ContainsAddRec = false; 10896 } 10897 10898 bool follow(const SCEV *S) { 10899 if (isa<SCEVAddRecExpr>(S)) { 10900 ContainsAddRec = true; 10901 10902 // Stop recursion: once we collected a term, do not walk its operands. 10903 return false; 10904 } 10905 10906 // Keep looking. 10907 return true; 10908 } 10909 10910 bool isDone() const { return false; } 10911 }; 10912 10913 // Find factors that are multiplied with an expression that (possibly as a 10914 // subexpression) contains an AddRecExpr. In the expression: 10915 // 10916 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10917 // 10918 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10919 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10920 // parameters as they form a product with an induction variable. 10921 // 10922 // This collector expects all array size parameters to be in the same MulExpr. 10923 // It might be necessary to later add support for collecting parameters that are 10924 // spread over different nested MulExpr. 10925 struct SCEVCollectAddRecMultiplies { 10926 SmallVectorImpl<const SCEV *> &Terms; 10927 ScalarEvolution &SE; 10928 10929 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10930 : Terms(T), SE(SE) {} 10931 10932 bool follow(const SCEV *S) { 10933 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10934 bool HasAddRec = false; 10935 SmallVector<const SCEV *, 0> Operands; 10936 for (auto Op : Mul->operands()) { 10937 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10938 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10939 Operands.push_back(Op); 10940 } else if (Unknown) { 10941 HasAddRec = true; 10942 } else { 10943 bool ContainsAddRec; 10944 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10945 visitAll(Op, ContiansAddRec); 10946 HasAddRec |= ContainsAddRec; 10947 } 10948 } 10949 if (Operands.size() == 0) 10950 return true; 10951 10952 if (!HasAddRec) 10953 return false; 10954 10955 Terms.push_back(SE.getMulExpr(Operands)); 10956 // Stop recursion: once we collected a term, do not walk its operands. 10957 return false; 10958 } 10959 10960 // Keep looking. 10961 return true; 10962 } 10963 10964 bool isDone() const { return false; } 10965 }; 10966 10967 } // end anonymous namespace 10968 10969 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10970 /// two places: 10971 /// 1) The strides of AddRec expressions. 10972 /// 2) Unknowns that are multiplied with AddRec expressions. 10973 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10974 SmallVectorImpl<const SCEV *> &Terms) { 10975 SmallVector<const SCEV *, 4> Strides; 10976 SCEVCollectStrides StrideCollector(*this, Strides); 10977 visitAll(Expr, StrideCollector); 10978 10979 LLVM_DEBUG({ 10980 dbgs() << "Strides:\n"; 10981 for (const SCEV *S : Strides) 10982 dbgs() << *S << "\n"; 10983 }); 10984 10985 for (const SCEV *S : Strides) { 10986 SCEVCollectTerms TermCollector(Terms); 10987 visitAll(S, TermCollector); 10988 } 10989 10990 LLVM_DEBUG({ 10991 dbgs() << "Terms:\n"; 10992 for (const SCEV *T : Terms) 10993 dbgs() << *T << "\n"; 10994 }); 10995 10996 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10997 visitAll(Expr, MulCollector); 10998 } 10999 11000 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11001 SmallVectorImpl<const SCEV *> &Terms, 11002 SmallVectorImpl<const SCEV *> &Sizes) { 11003 int Last = Terms.size() - 1; 11004 const SCEV *Step = Terms[Last]; 11005 11006 // End of recursion. 11007 if (Last == 0) { 11008 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11009 SmallVector<const SCEV *, 2> Qs; 11010 for (const SCEV *Op : M->operands()) 11011 if (!isa<SCEVConstant>(Op)) 11012 Qs.push_back(Op); 11013 11014 Step = SE.getMulExpr(Qs); 11015 } 11016 11017 Sizes.push_back(Step); 11018 return true; 11019 } 11020 11021 for (const SCEV *&Term : Terms) { 11022 // Normalize the terms before the next call to findArrayDimensionsRec. 11023 const SCEV *Q, *R; 11024 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11025 11026 // Bail out when GCD does not evenly divide one of the terms. 11027 if (!R->isZero()) 11028 return false; 11029 11030 Term = Q; 11031 } 11032 11033 // Remove all SCEVConstants. 11034 Terms.erase( 11035 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11036 Terms.end()); 11037 11038 if (Terms.size() > 0) 11039 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11040 return false; 11041 11042 Sizes.push_back(Step); 11043 return true; 11044 } 11045 11046 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11047 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11048 for (const SCEV *T : Terms) 11049 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11050 return true; 11051 return false; 11052 } 11053 11054 // Return the number of product terms in S. 11055 static inline int numberOfTerms(const SCEV *S) { 11056 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11057 return Expr->getNumOperands(); 11058 return 1; 11059 } 11060 11061 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11062 if (isa<SCEVConstant>(T)) 11063 return nullptr; 11064 11065 if (isa<SCEVUnknown>(T)) 11066 return T; 11067 11068 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11069 SmallVector<const SCEV *, 2> Factors; 11070 for (const SCEV *Op : M->operands()) 11071 if (!isa<SCEVConstant>(Op)) 11072 Factors.push_back(Op); 11073 11074 return SE.getMulExpr(Factors); 11075 } 11076 11077 return T; 11078 } 11079 11080 /// Return the size of an element read or written by Inst. 11081 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11082 Type *Ty; 11083 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11084 Ty = Store->getValueOperand()->getType(); 11085 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11086 Ty = Load->getType(); 11087 else 11088 return nullptr; 11089 11090 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11091 return getSizeOfExpr(ETy, Ty); 11092 } 11093 11094 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11095 SmallVectorImpl<const SCEV *> &Sizes, 11096 const SCEV *ElementSize) { 11097 if (Terms.size() < 1 || !ElementSize) 11098 return; 11099 11100 // Early return when Terms do not contain parameters: we do not delinearize 11101 // non parametric SCEVs. 11102 if (!containsParameters(Terms)) 11103 return; 11104 11105 LLVM_DEBUG({ 11106 dbgs() << "Terms:\n"; 11107 for (const SCEV *T : Terms) 11108 dbgs() << *T << "\n"; 11109 }); 11110 11111 // Remove duplicates. 11112 array_pod_sort(Terms.begin(), Terms.end()); 11113 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11114 11115 // Put larger terms first. 11116 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11117 return numberOfTerms(LHS) > numberOfTerms(RHS); 11118 }); 11119 11120 // Try to divide all terms by the element size. If term is not divisible by 11121 // element size, proceed with the original term. 11122 for (const SCEV *&Term : Terms) { 11123 const SCEV *Q, *R; 11124 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11125 if (!Q->isZero()) 11126 Term = Q; 11127 } 11128 11129 SmallVector<const SCEV *, 4> NewTerms; 11130 11131 // Remove constant factors. 11132 for (const SCEV *T : Terms) 11133 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11134 NewTerms.push_back(NewT); 11135 11136 LLVM_DEBUG({ 11137 dbgs() << "Terms after sorting:\n"; 11138 for (const SCEV *T : NewTerms) 11139 dbgs() << *T << "\n"; 11140 }); 11141 11142 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11143 Sizes.clear(); 11144 return; 11145 } 11146 11147 // The last element to be pushed into Sizes is the size of an element. 11148 Sizes.push_back(ElementSize); 11149 11150 LLVM_DEBUG({ 11151 dbgs() << "Sizes:\n"; 11152 for (const SCEV *S : Sizes) 11153 dbgs() << *S << "\n"; 11154 }); 11155 } 11156 11157 void ScalarEvolution::computeAccessFunctions( 11158 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11159 SmallVectorImpl<const SCEV *> &Sizes) { 11160 // Early exit in case this SCEV is not an affine multivariate function. 11161 if (Sizes.empty()) 11162 return; 11163 11164 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11165 if (!AR->isAffine()) 11166 return; 11167 11168 const SCEV *Res = Expr; 11169 int Last = Sizes.size() - 1; 11170 for (int i = Last; i >= 0; i--) { 11171 const SCEV *Q, *R; 11172 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11173 11174 LLVM_DEBUG({ 11175 dbgs() << "Res: " << *Res << "\n"; 11176 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11177 dbgs() << "Res divided by Sizes[i]:\n"; 11178 dbgs() << "Quotient: " << *Q << "\n"; 11179 dbgs() << "Remainder: " << *R << "\n"; 11180 }); 11181 11182 Res = Q; 11183 11184 // Do not record the last subscript corresponding to the size of elements in 11185 // the array. 11186 if (i == Last) { 11187 11188 // Bail out if the remainder is too complex. 11189 if (isa<SCEVAddRecExpr>(R)) { 11190 Subscripts.clear(); 11191 Sizes.clear(); 11192 return; 11193 } 11194 11195 continue; 11196 } 11197 11198 // Record the access function for the current subscript. 11199 Subscripts.push_back(R); 11200 } 11201 11202 // Also push in last position the remainder of the last division: it will be 11203 // the access function of the innermost dimension. 11204 Subscripts.push_back(Res); 11205 11206 std::reverse(Subscripts.begin(), Subscripts.end()); 11207 11208 LLVM_DEBUG({ 11209 dbgs() << "Subscripts:\n"; 11210 for (const SCEV *S : Subscripts) 11211 dbgs() << *S << "\n"; 11212 }); 11213 } 11214 11215 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11216 /// sizes of an array access. Returns the remainder of the delinearization that 11217 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11218 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11219 /// expressions in the stride and base of a SCEV corresponding to the 11220 /// computation of a GCD (greatest common divisor) of base and stride. When 11221 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11222 /// 11223 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11224 /// 11225 /// void foo(long n, long m, long o, double A[n][m][o]) { 11226 /// 11227 /// for (long i = 0; i < n; i++) 11228 /// for (long j = 0; j < m; j++) 11229 /// for (long k = 0; k < o; k++) 11230 /// A[i][j][k] = 1.0; 11231 /// } 11232 /// 11233 /// the delinearization input is the following AddRec SCEV: 11234 /// 11235 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11236 /// 11237 /// From this SCEV, we are able to say that the base offset of the access is %A 11238 /// because it appears as an offset that does not divide any of the strides in 11239 /// the loops: 11240 /// 11241 /// CHECK: Base offset: %A 11242 /// 11243 /// and then SCEV->delinearize determines the size of some of the dimensions of 11244 /// the array as these are the multiples by which the strides are happening: 11245 /// 11246 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11247 /// 11248 /// Note that the outermost dimension remains of UnknownSize because there are 11249 /// no strides that would help identifying the size of the last dimension: when 11250 /// the array has been statically allocated, one could compute the size of that 11251 /// dimension by dividing the overall size of the array by the size of the known 11252 /// dimensions: %m * %o * 8. 11253 /// 11254 /// Finally delinearize provides the access functions for the array reference 11255 /// that does correspond to A[i][j][k] of the above C testcase: 11256 /// 11257 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11258 /// 11259 /// The testcases are checking the output of a function pass: 11260 /// DelinearizationPass that walks through all loads and stores of a function 11261 /// asking for the SCEV of the memory access with respect to all enclosing 11262 /// loops, calling SCEV->delinearize on that and printing the results. 11263 void ScalarEvolution::delinearize(const SCEV *Expr, 11264 SmallVectorImpl<const SCEV *> &Subscripts, 11265 SmallVectorImpl<const SCEV *> &Sizes, 11266 const SCEV *ElementSize) { 11267 // First step: collect parametric terms. 11268 SmallVector<const SCEV *, 4> Terms; 11269 collectParametricTerms(Expr, Terms); 11270 11271 if (Terms.empty()) 11272 return; 11273 11274 // Second step: find subscript sizes. 11275 findArrayDimensions(Terms, Sizes, ElementSize); 11276 11277 if (Sizes.empty()) 11278 return; 11279 11280 // Third step: compute the access functions for each subscript. 11281 computeAccessFunctions(Expr, Subscripts, Sizes); 11282 11283 if (Subscripts.empty()) 11284 return; 11285 11286 LLVM_DEBUG({ 11287 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11288 dbgs() << "ArrayDecl[UnknownSize]"; 11289 for (const SCEV *S : Sizes) 11290 dbgs() << "[" << *S << "]"; 11291 11292 dbgs() << "\nArrayRef"; 11293 for (const SCEV *S : Subscripts) 11294 dbgs() << "[" << *S << "]"; 11295 dbgs() << "\n"; 11296 }); 11297 } 11298 11299 //===----------------------------------------------------------------------===// 11300 // SCEVCallbackVH Class Implementation 11301 //===----------------------------------------------------------------------===// 11302 11303 void ScalarEvolution::SCEVCallbackVH::deleted() { 11304 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11305 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11306 SE->ConstantEvolutionLoopExitValue.erase(PN); 11307 SE->eraseValueFromMap(getValPtr()); 11308 // this now dangles! 11309 } 11310 11311 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11312 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11313 11314 // Forget all the expressions associated with users of the old value, 11315 // so that future queries will recompute the expressions using the new 11316 // value. 11317 Value *Old = getValPtr(); 11318 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11319 SmallPtrSet<User *, 8> Visited; 11320 while (!Worklist.empty()) { 11321 User *U = Worklist.pop_back_val(); 11322 // Deleting the Old value will cause this to dangle. Postpone 11323 // that until everything else is done. 11324 if (U == Old) 11325 continue; 11326 if (!Visited.insert(U).second) 11327 continue; 11328 if (PHINode *PN = dyn_cast<PHINode>(U)) 11329 SE->ConstantEvolutionLoopExitValue.erase(PN); 11330 SE->eraseValueFromMap(U); 11331 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11332 } 11333 // Delete the Old value. 11334 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11335 SE->ConstantEvolutionLoopExitValue.erase(PN); 11336 SE->eraseValueFromMap(Old); 11337 // this now dangles! 11338 } 11339 11340 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11341 : CallbackVH(V), SE(se) {} 11342 11343 //===----------------------------------------------------------------------===// 11344 // ScalarEvolution Class Implementation 11345 //===----------------------------------------------------------------------===// 11346 11347 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11348 AssumptionCache &AC, DominatorTree &DT, 11349 LoopInfo &LI) 11350 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11351 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11352 LoopDispositions(64), BlockDispositions(64) { 11353 // To use guards for proving predicates, we need to scan every instruction in 11354 // relevant basic blocks, and not just terminators. Doing this is a waste of 11355 // time if the IR does not actually contain any calls to 11356 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11357 // 11358 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11359 // to _add_ guards to the module when there weren't any before, and wants 11360 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11361 // efficient in lieu of being smart in that rather obscure case. 11362 11363 auto *GuardDecl = F.getParent()->getFunction( 11364 Intrinsic::getName(Intrinsic::experimental_guard)); 11365 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11366 } 11367 11368 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11369 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11370 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11371 ValueExprMap(std::move(Arg.ValueExprMap)), 11372 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11373 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11374 PendingMerges(std::move(Arg.PendingMerges)), 11375 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11376 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11377 PredicatedBackedgeTakenCounts( 11378 std::move(Arg.PredicatedBackedgeTakenCounts)), 11379 ConstantEvolutionLoopExitValue( 11380 std::move(Arg.ConstantEvolutionLoopExitValue)), 11381 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11382 LoopDispositions(std::move(Arg.LoopDispositions)), 11383 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11384 BlockDispositions(std::move(Arg.BlockDispositions)), 11385 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11386 SignedRanges(std::move(Arg.SignedRanges)), 11387 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11388 UniquePreds(std::move(Arg.UniquePreds)), 11389 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11390 LoopUsers(std::move(Arg.LoopUsers)), 11391 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11392 FirstUnknown(Arg.FirstUnknown) { 11393 Arg.FirstUnknown = nullptr; 11394 } 11395 11396 ScalarEvolution::~ScalarEvolution() { 11397 // Iterate through all the SCEVUnknown instances and call their 11398 // destructors, so that they release their references to their values. 11399 for (SCEVUnknown *U = FirstUnknown; U;) { 11400 SCEVUnknown *Tmp = U; 11401 U = U->Next; 11402 Tmp->~SCEVUnknown(); 11403 } 11404 FirstUnknown = nullptr; 11405 11406 ExprValueMap.clear(); 11407 ValueExprMap.clear(); 11408 HasRecMap.clear(); 11409 11410 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11411 // that a loop had multiple computable exits. 11412 for (auto &BTCI : BackedgeTakenCounts) 11413 BTCI.second.clear(); 11414 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11415 BTCI.second.clear(); 11416 11417 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11418 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11419 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11420 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11421 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11422 } 11423 11424 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11425 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11426 } 11427 11428 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11429 const Loop *L) { 11430 // Print all inner loops first 11431 for (Loop *I : *L) 11432 PrintLoopInfo(OS, SE, I); 11433 11434 OS << "Loop "; 11435 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11436 OS << ": "; 11437 11438 SmallVector<BasicBlock *, 8> ExitingBlocks; 11439 L->getExitingBlocks(ExitingBlocks); 11440 if (ExitingBlocks.size() != 1) 11441 OS << "<multiple exits> "; 11442 11443 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11444 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11445 else 11446 OS << "Unpredictable backedge-taken count.\n"; 11447 11448 if (ExitingBlocks.size() > 1) 11449 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11450 OS << " exit count for " << ExitingBlock->getName() << ": " 11451 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11452 } 11453 11454 OS << "Loop "; 11455 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11456 OS << ": "; 11457 11458 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11459 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11460 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11461 OS << ", actual taken count either this or zero."; 11462 } else { 11463 OS << "Unpredictable max backedge-taken count. "; 11464 } 11465 11466 OS << "\n" 11467 "Loop "; 11468 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11469 OS << ": "; 11470 11471 SCEVUnionPredicate Pred; 11472 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11473 if (!isa<SCEVCouldNotCompute>(PBT)) { 11474 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11475 OS << " Predicates:\n"; 11476 Pred.print(OS, 4); 11477 } else { 11478 OS << "Unpredictable predicated backedge-taken count. "; 11479 } 11480 OS << "\n"; 11481 11482 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11483 OS << "Loop "; 11484 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11485 OS << ": "; 11486 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11487 } 11488 } 11489 11490 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11491 switch (LD) { 11492 case ScalarEvolution::LoopVariant: 11493 return "Variant"; 11494 case ScalarEvolution::LoopInvariant: 11495 return "Invariant"; 11496 case ScalarEvolution::LoopComputable: 11497 return "Computable"; 11498 } 11499 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11500 } 11501 11502 void ScalarEvolution::print(raw_ostream &OS) const { 11503 // ScalarEvolution's implementation of the print method is to print 11504 // out SCEV values of all instructions that are interesting. Doing 11505 // this potentially causes it to create new SCEV objects though, 11506 // which technically conflicts with the const qualifier. This isn't 11507 // observable from outside the class though, so casting away the 11508 // const isn't dangerous. 11509 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11510 11511 OS << "Classifying expressions for: "; 11512 F.printAsOperand(OS, /*PrintType=*/false); 11513 OS << "\n"; 11514 for (Instruction &I : instructions(F)) 11515 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11516 OS << I << '\n'; 11517 OS << " --> "; 11518 const SCEV *SV = SE.getSCEV(&I); 11519 SV->print(OS); 11520 if (!isa<SCEVCouldNotCompute>(SV)) { 11521 OS << " U: "; 11522 SE.getUnsignedRange(SV).print(OS); 11523 OS << " S: "; 11524 SE.getSignedRange(SV).print(OS); 11525 } 11526 11527 const Loop *L = LI.getLoopFor(I.getParent()); 11528 11529 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11530 if (AtUse != SV) { 11531 OS << " --> "; 11532 AtUse->print(OS); 11533 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11534 OS << " U: "; 11535 SE.getUnsignedRange(AtUse).print(OS); 11536 OS << " S: "; 11537 SE.getSignedRange(AtUse).print(OS); 11538 } 11539 } 11540 11541 if (L) { 11542 OS << "\t\t" "Exits: "; 11543 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11544 if (!SE.isLoopInvariant(ExitValue, L)) { 11545 OS << "<<Unknown>>"; 11546 } else { 11547 OS << *ExitValue; 11548 } 11549 11550 bool First = true; 11551 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11552 if (First) { 11553 OS << "\t\t" "LoopDispositions: { "; 11554 First = false; 11555 } else { 11556 OS << ", "; 11557 } 11558 11559 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11560 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11561 } 11562 11563 for (auto *InnerL : depth_first(L)) { 11564 if (InnerL == L) 11565 continue; 11566 if (First) { 11567 OS << "\t\t" "LoopDispositions: { "; 11568 First = false; 11569 } else { 11570 OS << ", "; 11571 } 11572 11573 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11574 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11575 } 11576 11577 OS << " }"; 11578 } 11579 11580 OS << "\n"; 11581 } 11582 11583 OS << "Determining loop execution counts for: "; 11584 F.printAsOperand(OS, /*PrintType=*/false); 11585 OS << "\n"; 11586 for (Loop *I : LI) 11587 PrintLoopInfo(OS, &SE, I); 11588 } 11589 11590 ScalarEvolution::LoopDisposition 11591 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11592 auto &Values = LoopDispositions[S]; 11593 for (auto &V : Values) { 11594 if (V.getPointer() == L) 11595 return V.getInt(); 11596 } 11597 Values.emplace_back(L, LoopVariant); 11598 LoopDisposition D = computeLoopDisposition(S, L); 11599 auto &Values2 = LoopDispositions[S]; 11600 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11601 if (V.getPointer() == L) { 11602 V.setInt(D); 11603 break; 11604 } 11605 } 11606 return D; 11607 } 11608 11609 ScalarEvolution::LoopDisposition 11610 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11611 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11612 case scConstant: 11613 return LoopInvariant; 11614 case scTruncate: 11615 case scZeroExtend: 11616 case scSignExtend: 11617 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11618 case scAddRecExpr: { 11619 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11620 11621 // If L is the addrec's loop, it's computable. 11622 if (AR->getLoop() == L) 11623 return LoopComputable; 11624 11625 // Add recurrences are never invariant in the function-body (null loop). 11626 if (!L) 11627 return LoopVariant; 11628 11629 // Everything that is not defined at loop entry is variant. 11630 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11631 return LoopVariant; 11632 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11633 " dominate the contained loop's header?"); 11634 11635 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11636 if (AR->getLoop()->contains(L)) 11637 return LoopInvariant; 11638 11639 // This recurrence is variant w.r.t. L if any of its operands 11640 // are variant. 11641 for (auto *Op : AR->operands()) 11642 if (!isLoopInvariant(Op, L)) 11643 return LoopVariant; 11644 11645 // Otherwise it's loop-invariant. 11646 return LoopInvariant; 11647 } 11648 case scAddExpr: 11649 case scMulExpr: 11650 case scUMaxExpr: 11651 case scSMaxExpr: 11652 case scUMinExpr: 11653 case scSMinExpr: { 11654 bool HasVarying = false; 11655 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11656 LoopDisposition D = getLoopDisposition(Op, L); 11657 if (D == LoopVariant) 11658 return LoopVariant; 11659 if (D == LoopComputable) 11660 HasVarying = true; 11661 } 11662 return HasVarying ? LoopComputable : LoopInvariant; 11663 } 11664 case scUDivExpr: { 11665 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11666 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11667 if (LD == LoopVariant) 11668 return LoopVariant; 11669 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11670 if (RD == LoopVariant) 11671 return LoopVariant; 11672 return (LD == LoopInvariant && RD == LoopInvariant) ? 11673 LoopInvariant : LoopComputable; 11674 } 11675 case scUnknown: 11676 // All non-instruction values are loop invariant. All instructions are loop 11677 // invariant if they are not contained in the specified loop. 11678 // Instructions are never considered invariant in the function body 11679 // (null loop) because they are defined within the "loop". 11680 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11681 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11682 return LoopInvariant; 11683 case scCouldNotCompute: 11684 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11685 } 11686 llvm_unreachable("Unknown SCEV kind!"); 11687 } 11688 11689 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11690 return getLoopDisposition(S, L) == LoopInvariant; 11691 } 11692 11693 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11694 return getLoopDisposition(S, L) == LoopComputable; 11695 } 11696 11697 ScalarEvolution::BlockDisposition 11698 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11699 auto &Values = BlockDispositions[S]; 11700 for (auto &V : Values) { 11701 if (V.getPointer() == BB) 11702 return V.getInt(); 11703 } 11704 Values.emplace_back(BB, DoesNotDominateBlock); 11705 BlockDisposition D = computeBlockDisposition(S, BB); 11706 auto &Values2 = BlockDispositions[S]; 11707 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11708 if (V.getPointer() == BB) { 11709 V.setInt(D); 11710 break; 11711 } 11712 } 11713 return D; 11714 } 11715 11716 ScalarEvolution::BlockDisposition 11717 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11718 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11719 case scConstant: 11720 return ProperlyDominatesBlock; 11721 case scTruncate: 11722 case scZeroExtend: 11723 case scSignExtend: 11724 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11725 case scAddRecExpr: { 11726 // This uses a "dominates" query instead of "properly dominates" query 11727 // to test for proper dominance too, because the instruction which 11728 // produces the addrec's value is a PHI, and a PHI effectively properly 11729 // dominates its entire containing block. 11730 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11731 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11732 return DoesNotDominateBlock; 11733 11734 // Fall through into SCEVNAryExpr handling. 11735 LLVM_FALLTHROUGH; 11736 } 11737 case scAddExpr: 11738 case scMulExpr: 11739 case scUMaxExpr: 11740 case scSMaxExpr: 11741 case scUMinExpr: 11742 case scSMinExpr: { 11743 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11744 bool Proper = true; 11745 for (const SCEV *NAryOp : NAry->operands()) { 11746 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11747 if (D == DoesNotDominateBlock) 11748 return DoesNotDominateBlock; 11749 if (D == DominatesBlock) 11750 Proper = false; 11751 } 11752 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11753 } 11754 case scUDivExpr: { 11755 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11756 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11757 BlockDisposition LD = getBlockDisposition(LHS, BB); 11758 if (LD == DoesNotDominateBlock) 11759 return DoesNotDominateBlock; 11760 BlockDisposition RD = getBlockDisposition(RHS, BB); 11761 if (RD == DoesNotDominateBlock) 11762 return DoesNotDominateBlock; 11763 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11764 ProperlyDominatesBlock : DominatesBlock; 11765 } 11766 case scUnknown: 11767 if (Instruction *I = 11768 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11769 if (I->getParent() == BB) 11770 return DominatesBlock; 11771 if (DT.properlyDominates(I->getParent(), BB)) 11772 return ProperlyDominatesBlock; 11773 return DoesNotDominateBlock; 11774 } 11775 return ProperlyDominatesBlock; 11776 case scCouldNotCompute: 11777 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11778 } 11779 llvm_unreachable("Unknown SCEV kind!"); 11780 } 11781 11782 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11783 return getBlockDisposition(S, BB) >= DominatesBlock; 11784 } 11785 11786 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11787 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11788 } 11789 11790 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11791 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11792 } 11793 11794 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11795 auto IsS = [&](const SCEV *X) { return S == X; }; 11796 auto ContainsS = [&](const SCEV *X) { 11797 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11798 }; 11799 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11800 } 11801 11802 void 11803 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11804 ValuesAtScopes.erase(S); 11805 LoopDispositions.erase(S); 11806 BlockDispositions.erase(S); 11807 UnsignedRanges.erase(S); 11808 SignedRanges.erase(S); 11809 ExprValueMap.erase(S); 11810 HasRecMap.erase(S); 11811 MinTrailingZerosCache.erase(S); 11812 11813 for (auto I = PredicatedSCEVRewrites.begin(); 11814 I != PredicatedSCEVRewrites.end();) { 11815 std::pair<const SCEV *, const Loop *> Entry = I->first; 11816 if (Entry.first == S) 11817 PredicatedSCEVRewrites.erase(I++); 11818 else 11819 ++I; 11820 } 11821 11822 auto RemoveSCEVFromBackedgeMap = 11823 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11824 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11825 BackedgeTakenInfo &BEInfo = I->second; 11826 if (BEInfo.hasOperand(S, this)) { 11827 BEInfo.clear(); 11828 Map.erase(I++); 11829 } else 11830 ++I; 11831 } 11832 }; 11833 11834 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11835 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11836 } 11837 11838 void 11839 ScalarEvolution::getUsedLoops(const SCEV *S, 11840 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11841 struct FindUsedLoops { 11842 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11843 : LoopsUsed(LoopsUsed) {} 11844 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11845 bool follow(const SCEV *S) { 11846 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11847 LoopsUsed.insert(AR->getLoop()); 11848 return true; 11849 } 11850 11851 bool isDone() const { return false; } 11852 }; 11853 11854 FindUsedLoops F(LoopsUsed); 11855 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11856 } 11857 11858 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11859 SmallPtrSet<const Loop *, 8> LoopsUsed; 11860 getUsedLoops(S, LoopsUsed); 11861 for (auto *L : LoopsUsed) 11862 LoopUsers[L].push_back(S); 11863 } 11864 11865 void ScalarEvolution::verify() const { 11866 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11867 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11868 11869 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11870 11871 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11872 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11873 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11874 11875 const SCEV *visitConstant(const SCEVConstant *Constant) { 11876 return SE.getConstant(Constant->getAPInt()); 11877 } 11878 11879 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11880 return SE.getUnknown(Expr->getValue()); 11881 } 11882 11883 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11884 return SE.getCouldNotCompute(); 11885 } 11886 }; 11887 11888 SCEVMapper SCM(SE2); 11889 11890 while (!LoopStack.empty()) { 11891 auto *L = LoopStack.pop_back_val(); 11892 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11893 11894 auto *CurBECount = SCM.visit( 11895 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11896 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11897 11898 if (CurBECount == SE2.getCouldNotCompute() || 11899 NewBECount == SE2.getCouldNotCompute()) { 11900 // NB! This situation is legal, but is very suspicious -- whatever pass 11901 // change the loop to make a trip count go from could not compute to 11902 // computable or vice-versa *should have* invalidated SCEV. However, we 11903 // choose not to assert here (for now) since we don't want false 11904 // positives. 11905 continue; 11906 } 11907 11908 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11909 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11910 // not propagate undef aggressively). This means we can (and do) fail 11911 // verification in cases where a transform makes the trip count of a loop 11912 // go from "undef" to "undef+1" (say). The transform is fine, since in 11913 // both cases the loop iterates "undef" times, but SCEV thinks we 11914 // increased the trip count of the loop by 1 incorrectly. 11915 continue; 11916 } 11917 11918 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11919 SE.getTypeSizeInBits(NewBECount->getType())) 11920 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11921 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11922 SE.getTypeSizeInBits(NewBECount->getType())) 11923 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11924 11925 auto *ConstantDelta = 11926 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11927 11928 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11929 dbgs() << "Trip Count Changed!\n"; 11930 dbgs() << "Old: " << *CurBECount << "\n"; 11931 dbgs() << "New: " << *NewBECount << "\n"; 11932 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11933 std::abort(); 11934 } 11935 } 11936 } 11937 11938 bool ScalarEvolution::invalidate( 11939 Function &F, const PreservedAnalyses &PA, 11940 FunctionAnalysisManager::Invalidator &Inv) { 11941 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11942 // of its dependencies is invalidated. 11943 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11944 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11945 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11946 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11947 Inv.invalidate<LoopAnalysis>(F, PA); 11948 } 11949 11950 AnalysisKey ScalarEvolutionAnalysis::Key; 11951 11952 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11953 FunctionAnalysisManager &AM) { 11954 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11955 AM.getResult<AssumptionAnalysis>(F), 11956 AM.getResult<DominatorTreeAnalysis>(F), 11957 AM.getResult<LoopAnalysis>(F)); 11958 } 11959 11960 PreservedAnalyses 11961 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11962 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11963 return PreservedAnalyses::all(); 11964 } 11965 11966 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11967 "Scalar Evolution Analysis", false, true) 11968 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11969 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11970 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11971 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11972 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11973 "Scalar Evolution Analysis", false, true) 11974 11975 char ScalarEvolutionWrapperPass::ID = 0; 11976 11977 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11978 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11979 } 11980 11981 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11982 SE.reset(new ScalarEvolution( 11983 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 11984 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11985 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11986 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11987 return false; 11988 } 11989 11990 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11991 11992 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11993 SE->print(OS); 11994 } 11995 11996 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11997 if (!VerifySCEV) 11998 return; 11999 12000 SE->verify(); 12001 } 12002 12003 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12004 AU.setPreservesAll(); 12005 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12006 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12007 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12008 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12009 } 12010 12011 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12012 const SCEV *RHS) { 12013 FoldingSetNodeID ID; 12014 assert(LHS->getType() == RHS->getType() && 12015 "Type mismatch between LHS and RHS"); 12016 // Unique this node based on the arguments 12017 ID.AddInteger(SCEVPredicate::P_Equal); 12018 ID.AddPointer(LHS); 12019 ID.AddPointer(RHS); 12020 void *IP = nullptr; 12021 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12022 return S; 12023 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12024 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12025 UniquePreds.InsertNode(Eq, IP); 12026 return Eq; 12027 } 12028 12029 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12030 const SCEVAddRecExpr *AR, 12031 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12032 FoldingSetNodeID ID; 12033 // Unique this node based on the arguments 12034 ID.AddInteger(SCEVPredicate::P_Wrap); 12035 ID.AddPointer(AR); 12036 ID.AddInteger(AddedFlags); 12037 void *IP = nullptr; 12038 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12039 return S; 12040 auto *OF = new (SCEVAllocator) 12041 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12042 UniquePreds.InsertNode(OF, IP); 12043 return OF; 12044 } 12045 12046 namespace { 12047 12048 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12049 public: 12050 12051 /// Rewrites \p S in the context of a loop L and the SCEV predication 12052 /// infrastructure. 12053 /// 12054 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12055 /// equivalences present in \p Pred. 12056 /// 12057 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12058 /// \p NewPreds such that the result will be an AddRecExpr. 12059 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12060 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12061 SCEVUnionPredicate *Pred) { 12062 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12063 return Rewriter.visit(S); 12064 } 12065 12066 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12067 if (Pred) { 12068 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12069 for (auto *Pred : ExprPreds) 12070 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12071 if (IPred->getLHS() == Expr) 12072 return IPred->getRHS(); 12073 } 12074 return convertToAddRecWithPreds(Expr); 12075 } 12076 12077 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12078 const SCEV *Operand = visit(Expr->getOperand()); 12079 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12080 if (AR && AR->getLoop() == L && AR->isAffine()) { 12081 // This couldn't be folded because the operand didn't have the nuw 12082 // flag. Add the nusw flag as an assumption that we could make. 12083 const SCEV *Step = AR->getStepRecurrence(SE); 12084 Type *Ty = Expr->getType(); 12085 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12086 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12087 SE.getSignExtendExpr(Step, Ty), L, 12088 AR->getNoWrapFlags()); 12089 } 12090 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12091 } 12092 12093 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12094 const SCEV *Operand = visit(Expr->getOperand()); 12095 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12096 if (AR && AR->getLoop() == L && AR->isAffine()) { 12097 // This couldn't be folded because the operand didn't have the nsw 12098 // flag. Add the nssw flag as an assumption that we could make. 12099 const SCEV *Step = AR->getStepRecurrence(SE); 12100 Type *Ty = Expr->getType(); 12101 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12102 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12103 SE.getSignExtendExpr(Step, Ty), L, 12104 AR->getNoWrapFlags()); 12105 } 12106 return SE.getSignExtendExpr(Operand, Expr->getType()); 12107 } 12108 12109 private: 12110 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12111 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12112 SCEVUnionPredicate *Pred) 12113 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12114 12115 bool addOverflowAssumption(const SCEVPredicate *P) { 12116 if (!NewPreds) { 12117 // Check if we've already made this assumption. 12118 return Pred && Pred->implies(P); 12119 } 12120 NewPreds->insert(P); 12121 return true; 12122 } 12123 12124 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12125 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12126 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12127 return addOverflowAssumption(A); 12128 } 12129 12130 // If \p Expr represents a PHINode, we try to see if it can be represented 12131 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12132 // to add this predicate as a runtime overflow check, we return the AddRec. 12133 // If \p Expr does not meet these conditions (is not a PHI node, or we 12134 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12135 // return \p Expr. 12136 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12137 if (!isa<PHINode>(Expr->getValue())) 12138 return Expr; 12139 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12140 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12141 if (!PredicatedRewrite) 12142 return Expr; 12143 for (auto *P : PredicatedRewrite->second){ 12144 // Wrap predicates from outer loops are not supported. 12145 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12146 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12147 if (L != AR->getLoop()) 12148 return Expr; 12149 } 12150 if (!addOverflowAssumption(P)) 12151 return Expr; 12152 } 12153 return PredicatedRewrite->first; 12154 } 12155 12156 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12157 SCEVUnionPredicate *Pred; 12158 const Loop *L; 12159 }; 12160 12161 } // end anonymous namespace 12162 12163 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12164 SCEVUnionPredicate &Preds) { 12165 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12166 } 12167 12168 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12169 const SCEV *S, const Loop *L, 12170 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12171 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12172 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12173 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12174 12175 if (!AddRec) 12176 return nullptr; 12177 12178 // Since the transformation was successful, we can now transfer the SCEV 12179 // predicates. 12180 for (auto *P : TransformPreds) 12181 Preds.insert(P); 12182 12183 return AddRec; 12184 } 12185 12186 /// SCEV predicates 12187 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12188 SCEVPredicateKind Kind) 12189 : FastID(ID), Kind(Kind) {} 12190 12191 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12192 const SCEV *LHS, const SCEV *RHS) 12193 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12194 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12195 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12196 } 12197 12198 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12199 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12200 12201 if (!Op) 12202 return false; 12203 12204 return Op->LHS == LHS && Op->RHS == RHS; 12205 } 12206 12207 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12208 12209 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12210 12211 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12212 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12213 } 12214 12215 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12216 const SCEVAddRecExpr *AR, 12217 IncrementWrapFlags Flags) 12218 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12219 12220 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12221 12222 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12223 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12224 12225 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12226 } 12227 12228 bool SCEVWrapPredicate::isAlwaysTrue() const { 12229 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12230 IncrementWrapFlags IFlags = Flags; 12231 12232 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12233 IFlags = clearFlags(IFlags, IncrementNSSW); 12234 12235 return IFlags == IncrementAnyWrap; 12236 } 12237 12238 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12239 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12240 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12241 OS << "<nusw>"; 12242 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12243 OS << "<nssw>"; 12244 OS << "\n"; 12245 } 12246 12247 SCEVWrapPredicate::IncrementWrapFlags 12248 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12249 ScalarEvolution &SE) { 12250 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12251 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12252 12253 // We can safely transfer the NSW flag as NSSW. 12254 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12255 ImpliedFlags = IncrementNSSW; 12256 12257 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12258 // If the increment is positive, the SCEV NUW flag will also imply the 12259 // WrapPredicate NUSW flag. 12260 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12261 if (Step->getValue()->getValue().isNonNegative()) 12262 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12263 } 12264 12265 return ImpliedFlags; 12266 } 12267 12268 /// Union predicates don't get cached so create a dummy set ID for it. 12269 SCEVUnionPredicate::SCEVUnionPredicate() 12270 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12271 12272 bool SCEVUnionPredicate::isAlwaysTrue() const { 12273 return all_of(Preds, 12274 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12275 } 12276 12277 ArrayRef<const SCEVPredicate *> 12278 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12279 auto I = SCEVToPreds.find(Expr); 12280 if (I == SCEVToPreds.end()) 12281 return ArrayRef<const SCEVPredicate *>(); 12282 return I->second; 12283 } 12284 12285 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12286 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12287 return all_of(Set->Preds, 12288 [this](const SCEVPredicate *I) { return this->implies(I); }); 12289 12290 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12291 if (ScevPredsIt == SCEVToPreds.end()) 12292 return false; 12293 auto &SCEVPreds = ScevPredsIt->second; 12294 12295 return any_of(SCEVPreds, 12296 [N](const SCEVPredicate *I) { return I->implies(N); }); 12297 } 12298 12299 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12300 12301 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12302 for (auto Pred : Preds) 12303 Pred->print(OS, Depth); 12304 } 12305 12306 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12307 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12308 for (auto Pred : Set->Preds) 12309 add(Pred); 12310 return; 12311 } 12312 12313 if (implies(N)) 12314 return; 12315 12316 const SCEV *Key = N->getExpr(); 12317 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12318 " associated expression!"); 12319 12320 SCEVToPreds[Key].push_back(N); 12321 Preds.push_back(N); 12322 } 12323 12324 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12325 Loop &L) 12326 : SE(SE), L(L) {} 12327 12328 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12329 const SCEV *Expr = SE.getSCEV(V); 12330 RewriteEntry &Entry = RewriteMap[Expr]; 12331 12332 // If we already have an entry and the version matches, return it. 12333 if (Entry.second && Generation == Entry.first) 12334 return Entry.second; 12335 12336 // We found an entry but it's stale. Rewrite the stale entry 12337 // according to the current predicate. 12338 if (Entry.second) 12339 Expr = Entry.second; 12340 12341 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12342 Entry = {Generation, NewSCEV}; 12343 12344 return NewSCEV; 12345 } 12346 12347 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12348 if (!BackedgeCount) { 12349 SCEVUnionPredicate BackedgePred; 12350 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12351 addPredicate(BackedgePred); 12352 } 12353 return BackedgeCount; 12354 } 12355 12356 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12357 if (Preds.implies(&Pred)) 12358 return; 12359 Preds.add(&Pred); 12360 updateGeneration(); 12361 } 12362 12363 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12364 return Preds; 12365 } 12366 12367 void PredicatedScalarEvolution::updateGeneration() { 12368 // If the generation number wrapped recompute everything. 12369 if (++Generation == 0) { 12370 for (auto &II : RewriteMap) { 12371 const SCEV *Rewritten = II.second.second; 12372 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12373 } 12374 } 12375 } 12376 12377 void PredicatedScalarEvolution::setNoOverflow( 12378 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12379 const SCEV *Expr = getSCEV(V); 12380 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12381 12382 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12383 12384 // Clear the statically implied flags. 12385 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12386 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12387 12388 auto II = FlagsMap.insert({V, Flags}); 12389 if (!II.second) 12390 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12391 } 12392 12393 bool PredicatedScalarEvolution::hasNoOverflow( 12394 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12395 const SCEV *Expr = getSCEV(V); 12396 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12397 12398 Flags = SCEVWrapPredicate::clearFlags( 12399 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12400 12401 auto II = FlagsMap.find(V); 12402 12403 if (II != FlagsMap.end()) 12404 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12405 12406 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12407 } 12408 12409 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12410 const SCEV *Expr = this->getSCEV(V); 12411 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12412 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12413 12414 if (!New) 12415 return nullptr; 12416 12417 for (auto *P : NewPreds) 12418 Preds.add(P); 12419 12420 updateGeneration(); 12421 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12422 return New; 12423 } 12424 12425 PredicatedScalarEvolution::PredicatedScalarEvolution( 12426 const PredicatedScalarEvolution &Init) 12427 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12428 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12429 for (const auto &I : Init.FlagsMap) 12430 FlagsMap.insert(I); 12431 } 12432 12433 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12434 // For each block. 12435 for (auto *BB : L.getBlocks()) 12436 for (auto &I : *BB) { 12437 if (!SE.isSCEVable(I.getType())) 12438 continue; 12439 12440 auto *Expr = SE.getSCEV(&I); 12441 auto II = RewriteMap.find(Expr); 12442 12443 if (II == RewriteMap.end()) 12444 continue; 12445 12446 // Don't print things that are not interesting. 12447 if (II->second.second == Expr) 12448 continue; 12449 12450 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12451 OS.indent(Depth + 2) << *Expr << "\n"; 12452 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12453 } 12454 } 12455 12456 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12457 // arbitrary expressions. 12458 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12459 // 4, A / B becomes X / 8). 12460 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12461 const SCEV *&RHS) { 12462 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12463 if (Add == nullptr || Add->getNumOperands() != 2) 12464 return false; 12465 12466 const SCEV *A = Add->getOperand(1); 12467 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12468 12469 if (Mul == nullptr) 12470 return false; 12471 12472 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12473 // (SomeExpr + (-(SomeExpr / B) * B)). 12474 if (Expr == getURemExpr(A, B)) { 12475 LHS = A; 12476 RHS = B; 12477 return true; 12478 } 12479 return false; 12480 }; 12481 12482 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12483 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12484 return MatchURemWithDivisor(Mul->getOperand(1)) || 12485 MatchURemWithDivisor(Mul->getOperand(2)); 12486 12487 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12488 if (Mul->getNumOperands() == 2) 12489 return MatchURemWithDivisor(Mul->getOperand(1)) || 12490 MatchURemWithDivisor(Mul->getOperand(0)) || 12491 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12492 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12493 return false; 12494 } 12495