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/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (static_cast<SCEVTypes>(getSCEVType())) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 } 308 OS << "("; 309 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 310 I != E; ++I) { 311 OS << **I; 312 if (std::next(I) != E) 313 OS << OpStr; 314 } 315 OS << ")"; 316 switch (NAry->getSCEVType()) { 317 case scAddExpr: 318 case scMulExpr: 319 if (NAry->hasNoUnsignedWrap()) 320 OS << "<nuw>"; 321 if (NAry->hasNoSignedWrap()) 322 OS << "<nsw>"; 323 } 324 return; 325 } 326 case scUDivExpr: { 327 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 328 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 329 return; 330 } 331 case scUnknown: { 332 const SCEVUnknown *U = cast<SCEVUnknown>(this); 333 Type *AllocTy; 334 if (U->isSizeOf(AllocTy)) { 335 OS << "sizeof(" << *AllocTy << ")"; 336 return; 337 } 338 if (U->isAlignOf(AllocTy)) { 339 OS << "alignof(" << *AllocTy << ")"; 340 return; 341 } 342 343 Type *CTy; 344 Constant *FieldNo; 345 if (U->isOffsetOf(CTy, FieldNo)) { 346 OS << "offsetof(" << *CTy << ", "; 347 FieldNo->printAsOperand(OS, false); 348 OS << ")"; 349 return; 350 } 351 352 // Otherwise just print it normally. 353 U->getValue()->printAsOperand(OS, false); 354 return; 355 } 356 case scCouldNotCompute: 357 OS << "***COULDNOTCOMPUTE***"; 358 return; 359 } 360 llvm_unreachable("Unknown SCEV kind!"); 361 } 362 363 Type *SCEV::getType() const { 364 switch (static_cast<SCEVTypes>(getSCEVType())) { 365 case scConstant: 366 return cast<SCEVConstant>(this)->getType(); 367 case scTruncate: 368 case scZeroExtend: 369 case scSignExtend: 370 return cast<SCEVCastExpr>(this)->getType(); 371 case scAddRecExpr: 372 case scMulExpr: 373 case scUMaxExpr: 374 case scSMaxExpr: 375 case scUMinExpr: 376 case scSMinExpr: 377 return cast<SCEVNAryExpr>(this)->getType(); 378 case scAddExpr: 379 return cast<SCEVAddExpr>(this)->getType(); 380 case scUDivExpr: 381 return cast<SCEVUDivExpr>(this)->getType(); 382 case scUnknown: 383 return cast<SCEVUnknown>(this)->getType(); 384 case scCouldNotCompute: 385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 386 } 387 llvm_unreachable("Unknown SCEV kind!"); 388 } 389 390 bool SCEV::isZero() const { 391 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 392 return SC->getValue()->isZero(); 393 return false; 394 } 395 396 bool SCEV::isOne() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isOne(); 399 return false; 400 } 401 402 bool SCEV::isAllOnesValue() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isMinusOne(); 405 return false; 406 } 407 408 bool SCEV::isNonConstantNegative() const { 409 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 410 if (!Mul) return false; 411 412 // If there is a constant factor, it will be first. 413 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 414 if (!SC) return false; 415 416 // Return true if the value is negative, this matches things like (-42 * V). 417 return SC->getAPInt().isNegative(); 418 } 419 420 SCEVCouldNotCompute::SCEVCouldNotCompute() : 421 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 422 423 bool SCEVCouldNotCompute::classof(const SCEV *S) { 424 return S->getSCEVType() == scCouldNotCompute; 425 } 426 427 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 428 FoldingSetNodeID ID; 429 ID.AddInteger(scConstant); 430 ID.AddPointer(V); 431 void *IP = nullptr; 432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 433 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 434 UniqueSCEVs.InsertNode(S, IP); 435 return S; 436 } 437 438 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 439 return getConstant(ConstantInt::get(getContext(), Val)); 440 } 441 442 const SCEV * 443 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 445 return getConstant(ConstantInt::get(ITy, V, isSigned)); 446 } 447 448 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 449 unsigned SCEVTy, const SCEV *op, Type *ty) 450 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 451 452 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 453 const SCEV *op, Type *ty) 454 : SCEVCastExpr(ID, scTruncate, op, ty) { 455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 456 "Cannot truncate non-integer value!"); 457 } 458 459 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 460 const SCEV *op, Type *ty) 461 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 463 "Cannot zero extend non-integer value!"); 464 } 465 466 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 467 const SCEV *op, Type *ty) 468 : SCEVCastExpr(ID, scSignExtend, op, ty) { 469 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 470 "Cannot sign extend non-integer value!"); 471 } 472 473 void SCEVUnknown::deleted() { 474 // Clear this SCEVUnknown from various maps. 475 SE->forgetMemoizedResults(this); 476 477 // Remove this SCEVUnknown from the uniquing map. 478 SE->UniqueSCEVs.RemoveNode(this); 479 480 // Release the value. 481 setValPtr(nullptr); 482 } 483 484 void SCEVUnknown::allUsesReplacedWith(Value *New) { 485 // Remove this SCEVUnknown from the uniquing map. 486 SE->UniqueSCEVs.RemoveNode(this); 487 488 // Update this SCEVUnknown to point to the new value. This is needed 489 // because there may still be outstanding SCEVs which still point to 490 // this SCEVUnknown. 491 setValPtr(New); 492 } 493 494 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 495 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 496 if (VCE->getOpcode() == Instruction::PtrToInt) 497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 498 if (CE->getOpcode() == Instruction::GetElementPtr && 499 CE->getOperand(0)->isNullValue() && 500 CE->getNumOperands() == 2) 501 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 502 if (CI->isOne()) { 503 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 504 ->getElementType(); 505 return true; 506 } 507 508 return false; 509 } 510 511 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 512 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 513 if (VCE->getOpcode() == Instruction::PtrToInt) 514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 515 if (CE->getOpcode() == Instruction::GetElementPtr && 516 CE->getOperand(0)->isNullValue()) { 517 Type *Ty = 518 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 519 if (StructType *STy = dyn_cast<StructType>(Ty)) 520 if (!STy->isPacked() && 521 CE->getNumOperands() == 3 && 522 CE->getOperand(1)->isNullValue()) { 523 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 524 if (CI->isOne() && 525 STy->getNumElements() == 2 && 526 STy->getElementType(0)->isIntegerTy(1)) { 527 AllocTy = STy->getElementType(1); 528 return true; 529 } 530 } 531 } 532 533 return false; 534 } 535 536 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 537 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 538 if (VCE->getOpcode() == Instruction::PtrToInt) 539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 540 if (CE->getOpcode() == Instruction::GetElementPtr && 541 CE->getNumOperands() == 3 && 542 CE->getOperand(0)->isNullValue() && 543 CE->getOperand(1)->isNullValue()) { 544 Type *Ty = 545 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 546 // Ignore vector types here so that ScalarEvolutionExpander doesn't 547 // emit getelementptrs that index into vectors. 548 if (Ty->isStructTy() || Ty->isArrayTy()) { 549 CTy = Ty; 550 FieldNo = CE->getOperand(2); 551 return true; 552 } 553 } 554 555 return false; 556 } 557 558 //===----------------------------------------------------------------------===// 559 // SCEV Utilities 560 //===----------------------------------------------------------------------===// 561 562 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 563 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 564 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 565 /// have been previously deemed to be "equally complex" by this routine. It is 566 /// intended to avoid exponential time complexity in cases like: 567 /// 568 /// %a = f(%x, %y) 569 /// %b = f(%a, %a) 570 /// %c = f(%b, %b) 571 /// 572 /// %d = f(%x, %y) 573 /// %e = f(%d, %d) 574 /// %f = f(%e, %e) 575 /// 576 /// CompareValueComplexity(%f, %c) 577 /// 578 /// Since we do not continue running this routine on expression trees once we 579 /// have seen unequal values, there is no need to track them in the cache. 580 static int 581 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 582 const LoopInfo *const LI, Value *LV, Value *RV, 583 unsigned Depth) { 584 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 585 return 0; 586 587 // Order pointer values after integer values. This helps SCEVExpander form 588 // GEPs. 589 bool LIsPointer = LV->getType()->isPointerTy(), 590 RIsPointer = RV->getType()->isPointerTy(); 591 if (LIsPointer != RIsPointer) 592 return (int)LIsPointer - (int)RIsPointer; 593 594 // Compare getValueID values. 595 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 596 if (LID != RID) 597 return (int)LID - (int)RID; 598 599 // Sort arguments by their position. 600 if (const auto *LA = dyn_cast<Argument>(LV)) { 601 const auto *RA = cast<Argument>(RV); 602 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 603 return (int)LArgNo - (int)RArgNo; 604 } 605 606 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 607 const auto *RGV = cast<GlobalValue>(RV); 608 609 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 610 auto LT = GV->getLinkage(); 611 return !(GlobalValue::isPrivateLinkage(LT) || 612 GlobalValue::isInternalLinkage(LT)); 613 }; 614 615 // Use the names to distinguish the two values, but only if the 616 // names are semantically important. 617 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 618 return LGV->getName().compare(RGV->getName()); 619 } 620 621 // For instructions, compare their loop depth, and their operand count. This 622 // is pretty loose. 623 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 624 const auto *RInst = cast<Instruction>(RV); 625 626 // Compare loop depths. 627 const BasicBlock *LParent = LInst->getParent(), 628 *RParent = RInst->getParent(); 629 if (LParent != RParent) { 630 unsigned LDepth = LI->getLoopDepth(LParent), 631 RDepth = LI->getLoopDepth(RParent); 632 if (LDepth != RDepth) 633 return (int)LDepth - (int)RDepth; 634 } 635 636 // Compare the number of operands. 637 unsigned LNumOps = LInst->getNumOperands(), 638 RNumOps = RInst->getNumOperands(); 639 if (LNumOps != RNumOps) 640 return (int)LNumOps - (int)RNumOps; 641 642 for (unsigned Idx : seq(0u, LNumOps)) { 643 int Result = 644 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 645 RInst->getOperand(Idx), Depth + 1); 646 if (Result != 0) 647 return Result; 648 } 649 } 650 651 EqCacheValue.unionSets(LV, RV); 652 return 0; 653 } 654 655 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 656 // than RHS, respectively. A three-way result allows recursive comparisons to be 657 // more efficient. 658 static int CompareSCEVComplexity( 659 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 660 EquivalenceClasses<const Value *> &EqCacheValue, 661 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 662 DominatorTree &DT, unsigned Depth = 0) { 663 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 664 if (LHS == RHS) 665 return 0; 666 667 // Primarily, sort the SCEVs by their getSCEVType(). 668 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 669 if (LType != RType) 670 return (int)LType - (int)RType; 671 672 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 673 return 0; 674 // Aside from the getSCEVType() ordering, the particular ordering 675 // isn't very important except that it's beneficial to be consistent, 676 // so that (a + b) and (b + a) don't end up as different expressions. 677 switch (static_cast<SCEVTypes>(LType)) { 678 case scUnknown: { 679 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 680 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 681 682 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 683 RU->getValue(), Depth + 1); 684 if (X == 0) 685 EqCacheSCEV.unionSets(LHS, RHS); 686 return X; 687 } 688 689 case scConstant: { 690 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 691 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 692 693 // Compare constant values. 694 const APInt &LA = LC->getAPInt(); 695 const APInt &RA = RC->getAPInt(); 696 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 697 if (LBitWidth != RBitWidth) 698 return (int)LBitWidth - (int)RBitWidth; 699 return LA.ult(RA) ? -1 : 1; 700 } 701 702 case scAddRecExpr: { 703 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 704 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 705 706 // There is always a dominance between two recs that are used by one SCEV, 707 // so we can safely sort recs by loop header dominance. We require such 708 // order in getAddExpr. 709 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 710 if (LLoop != RLoop) { 711 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 712 assert(LHead != RHead && "Two loops share the same header?"); 713 if (DT.dominates(LHead, RHead)) 714 return 1; 715 else 716 assert(DT.dominates(RHead, LHead) && 717 "No dominance between recurrences used by one SCEV?"); 718 return -1; 719 } 720 721 // Addrec complexity grows with operand count. 722 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 723 if (LNumOps != RNumOps) 724 return (int)LNumOps - (int)RNumOps; 725 726 // Lexicographically compare. 727 for (unsigned i = 0; i != LNumOps; ++i) { 728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 729 LA->getOperand(i), RA->getOperand(i), DT, 730 Depth + 1); 731 if (X != 0) 732 return X; 733 } 734 EqCacheSCEV.unionSets(LHS, RHS); 735 return 0; 736 } 737 738 case scAddExpr: 739 case scMulExpr: 740 case scSMaxExpr: 741 case scUMaxExpr: 742 case scSMinExpr: 743 case scUMinExpr: { 744 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 745 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 746 747 // Lexicographically compare n-ary expressions. 748 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 749 if (LNumOps != RNumOps) 750 return (int)LNumOps - (int)RNumOps; 751 752 for (unsigned i = 0; i != LNumOps; ++i) { 753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 754 LC->getOperand(i), RC->getOperand(i), DT, 755 Depth + 1); 756 if (X != 0) 757 return X; 758 } 759 EqCacheSCEV.unionSets(LHS, RHS); 760 return 0; 761 } 762 763 case scUDivExpr: { 764 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 765 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 766 767 // Lexicographically compare udiv expressions. 768 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 769 RC->getLHS(), DT, Depth + 1); 770 if (X != 0) 771 return X; 772 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 773 RC->getRHS(), DT, Depth + 1); 774 if (X == 0) 775 EqCacheSCEV.unionSets(LHS, RHS); 776 return X; 777 } 778 779 case scTruncate: 780 case scZeroExtend: 781 case scSignExtend: { 782 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 783 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 784 785 // Compare cast expressions by operand. 786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 787 LC->getOperand(), RC->getOperand(), DT, 788 Depth + 1); 789 if (X == 0) 790 EqCacheSCEV.unionSets(LHS, RHS); 791 return X; 792 } 793 794 case scCouldNotCompute: 795 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 796 } 797 llvm_unreachable("Unknown SCEV kind!"); 798 } 799 800 /// Given a list of SCEV objects, order them by their complexity, and group 801 /// objects of the same complexity together by value. When this routine is 802 /// finished, we know that any duplicates in the vector are consecutive and that 803 /// complexity is monotonically increasing. 804 /// 805 /// Note that we go take special precautions to ensure that we get deterministic 806 /// results from this routine. In other words, we don't want the results of 807 /// this to depend on where the addresses of various SCEV objects happened to 808 /// land in memory. 809 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 810 LoopInfo *LI, DominatorTree &DT) { 811 if (Ops.size() < 2) return; // Noop 812 813 EquivalenceClasses<const SCEV *> EqCacheSCEV; 814 EquivalenceClasses<const Value *> EqCacheValue; 815 if (Ops.size() == 2) { 816 // This is the common case, which also happens to be trivially simple. 817 // Special case it. 818 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 819 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 820 std::swap(LHS, RHS); 821 return; 822 } 823 824 // Do the rough sort by complexity. 825 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 826 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 827 0; 828 }); 829 830 // Now that we are sorted by complexity, group elements of the same 831 // complexity. Note that this is, at worst, N^2, but the vector is likely to 832 // be extremely short in practice. Note that we take this approach because we 833 // do not want to depend on the addresses of the objects we are grouping. 834 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 835 const SCEV *S = Ops[i]; 836 unsigned Complexity = S->getSCEVType(); 837 838 // If there are any objects of the same complexity and same value as this 839 // one, group them. 840 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 841 if (Ops[j] == S) { // Found a duplicate. 842 // Move it to immediately after i'th element. 843 std::swap(Ops[i+1], Ops[j]); 844 ++i; // no need to rescan it. 845 if (i == e-2) return; // Done! 846 } 847 } 848 } 849 } 850 851 // Returns the size of the SCEV S. 852 static inline int sizeOfSCEV(const SCEV *S) { 853 struct FindSCEVSize { 854 int Size = 0; 855 856 FindSCEVSize() = default; 857 858 bool follow(const SCEV *S) { 859 ++Size; 860 // Keep looking at all operands of S. 861 return true; 862 } 863 864 bool isDone() const { 865 return false; 866 } 867 }; 868 869 FindSCEVSize F; 870 SCEVTraversal<FindSCEVSize> ST(F); 871 ST.visitAll(S); 872 return F.Size; 873 } 874 875 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 876 /// nodes. 877 static bool isHugeExpression(const SCEV *S) { 878 return S->getExpressionSize() >= HugeExprThreshold; 879 } 880 881 /// Returns true of \p Ops contains a huge SCEV (see definition above). 882 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 883 return any_of(Ops, isHugeExpression); 884 } 885 886 namespace { 887 888 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 889 public: 890 // Computes the Quotient and Remainder of the division of Numerator by 891 // Denominator. 892 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 893 const SCEV *Denominator, const SCEV **Quotient, 894 const SCEV **Remainder) { 895 assert(Numerator && Denominator && "Uninitialized SCEV"); 896 897 SCEVDivision D(SE, Numerator, Denominator); 898 899 // Check for the trivial case here to avoid having to check for it in the 900 // rest of the code. 901 if (Numerator == Denominator) { 902 *Quotient = D.One; 903 *Remainder = D.Zero; 904 return; 905 } 906 907 if (Numerator->isZero()) { 908 *Quotient = D.Zero; 909 *Remainder = D.Zero; 910 return; 911 } 912 913 // A simple case when N/1. The quotient is N. 914 if (Denominator->isOne()) { 915 *Quotient = Numerator; 916 *Remainder = D.Zero; 917 return; 918 } 919 920 // Split the Denominator when it is a product. 921 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 922 const SCEV *Q, *R; 923 *Quotient = Numerator; 924 for (const SCEV *Op : T->operands()) { 925 divide(SE, *Quotient, Op, &Q, &R); 926 *Quotient = Q; 927 928 // Bail out when the Numerator is not divisible by one of the terms of 929 // the Denominator. 930 if (!R->isZero()) { 931 *Quotient = D.Zero; 932 *Remainder = Numerator; 933 return; 934 } 935 } 936 *Remainder = D.Zero; 937 return; 938 } 939 940 D.visit(Numerator); 941 *Quotient = D.Quotient; 942 *Remainder = D.Remainder; 943 } 944 945 // Except in the trivial case described above, we do not know how to divide 946 // Expr by Denominator for the following functions with empty implementation. 947 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 948 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 949 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 950 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 951 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 952 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 953 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 954 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 955 void visitUnknown(const SCEVUnknown *Numerator) {} 956 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 957 958 void visitConstant(const SCEVConstant *Numerator) { 959 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 960 APInt NumeratorVal = Numerator->getAPInt(); 961 APInt DenominatorVal = D->getAPInt(); 962 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 963 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 964 965 if (NumeratorBW > DenominatorBW) 966 DenominatorVal = DenominatorVal.sext(NumeratorBW); 967 else if (NumeratorBW < DenominatorBW) 968 NumeratorVal = NumeratorVal.sext(DenominatorBW); 969 970 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 971 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 972 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 973 Quotient = SE.getConstant(QuotientVal); 974 Remainder = SE.getConstant(RemainderVal); 975 return; 976 } 977 } 978 979 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 980 const SCEV *StartQ, *StartR, *StepQ, *StepR; 981 if (!Numerator->isAffine()) 982 return cannotDivide(Numerator); 983 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 984 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 985 // Bail out if the types do not match. 986 Type *Ty = Denominator->getType(); 987 if (Ty != StartQ->getType() || Ty != StartR->getType() || 988 Ty != StepQ->getType() || Ty != StepR->getType()) 989 return cannotDivide(Numerator); 990 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 991 Numerator->getNoWrapFlags()); 992 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 993 Numerator->getNoWrapFlags()); 994 } 995 996 void visitAddExpr(const SCEVAddExpr *Numerator) { 997 SmallVector<const SCEV *, 2> Qs, Rs; 998 Type *Ty = Denominator->getType(); 999 1000 for (const SCEV *Op : Numerator->operands()) { 1001 const SCEV *Q, *R; 1002 divide(SE, Op, Denominator, &Q, &R); 1003 1004 // Bail out if types do not match. 1005 if (Ty != Q->getType() || Ty != R->getType()) 1006 return cannotDivide(Numerator); 1007 1008 Qs.push_back(Q); 1009 Rs.push_back(R); 1010 } 1011 1012 if (Qs.size() == 1) { 1013 Quotient = Qs[0]; 1014 Remainder = Rs[0]; 1015 return; 1016 } 1017 1018 Quotient = SE.getAddExpr(Qs); 1019 Remainder = SE.getAddExpr(Rs); 1020 } 1021 1022 void visitMulExpr(const SCEVMulExpr *Numerator) { 1023 SmallVector<const SCEV *, 2> Qs; 1024 Type *Ty = Denominator->getType(); 1025 1026 bool FoundDenominatorTerm = false; 1027 for (const SCEV *Op : Numerator->operands()) { 1028 // Bail out if types do not match. 1029 if (Ty != Op->getType()) 1030 return cannotDivide(Numerator); 1031 1032 if (FoundDenominatorTerm) { 1033 Qs.push_back(Op); 1034 continue; 1035 } 1036 1037 // Check whether Denominator divides one of the product operands. 1038 const SCEV *Q, *R; 1039 divide(SE, Op, Denominator, &Q, &R); 1040 if (!R->isZero()) { 1041 Qs.push_back(Op); 1042 continue; 1043 } 1044 1045 // Bail out if types do not match. 1046 if (Ty != Q->getType()) 1047 return cannotDivide(Numerator); 1048 1049 FoundDenominatorTerm = true; 1050 Qs.push_back(Q); 1051 } 1052 1053 if (FoundDenominatorTerm) { 1054 Remainder = Zero; 1055 if (Qs.size() == 1) 1056 Quotient = Qs[0]; 1057 else 1058 Quotient = SE.getMulExpr(Qs); 1059 return; 1060 } 1061 1062 if (!isa<SCEVUnknown>(Denominator)) 1063 return cannotDivide(Numerator); 1064 1065 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1066 ValueToValueMap RewriteMap; 1067 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1068 cast<SCEVConstant>(Zero)->getValue(); 1069 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1070 1071 if (Remainder->isZero()) { 1072 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1073 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1074 cast<SCEVConstant>(One)->getValue(); 1075 Quotient = 1076 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1077 return; 1078 } 1079 1080 // Quotient is (Numerator - Remainder) divided by Denominator. 1081 const SCEV *Q, *R; 1082 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1083 // This SCEV does not seem to simplify: fail the division here. 1084 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1085 return cannotDivide(Numerator); 1086 divide(SE, Diff, Denominator, &Q, &R); 1087 if (R != Zero) 1088 return cannotDivide(Numerator); 1089 Quotient = Q; 1090 } 1091 1092 private: 1093 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1094 const SCEV *Denominator) 1095 : SE(S), Denominator(Denominator) { 1096 Zero = SE.getZero(Denominator->getType()); 1097 One = SE.getOne(Denominator->getType()); 1098 1099 // We generally do not know how to divide Expr by Denominator. We 1100 // initialize the division to a "cannot divide" state to simplify the rest 1101 // of the code. 1102 cannotDivide(Numerator); 1103 } 1104 1105 // Convenience function for giving up on the division. We set the quotient to 1106 // be equal to zero and the remainder to be equal to the numerator. 1107 void cannotDivide(const SCEV *Numerator) { 1108 Quotient = Zero; 1109 Remainder = Numerator; 1110 } 1111 1112 ScalarEvolution &SE; 1113 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1114 }; 1115 1116 } // end anonymous namespace 1117 1118 //===----------------------------------------------------------------------===// 1119 // Simple SCEV method implementations 1120 //===----------------------------------------------------------------------===// 1121 1122 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1123 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1124 ScalarEvolution &SE, 1125 Type *ResultTy) { 1126 // Handle the simplest case efficiently. 1127 if (K == 1) 1128 return SE.getTruncateOrZeroExtend(It, ResultTy); 1129 1130 // We are using the following formula for BC(It, K): 1131 // 1132 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1133 // 1134 // Suppose, W is the bitwidth of the return value. We must be prepared for 1135 // overflow. Hence, we must assure that the result of our computation is 1136 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1137 // safe in modular arithmetic. 1138 // 1139 // However, this code doesn't use exactly that formula; the formula it uses 1140 // is something like the following, where T is the number of factors of 2 in 1141 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1142 // exponentiation: 1143 // 1144 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1145 // 1146 // This formula is trivially equivalent to the previous formula. However, 1147 // this formula can be implemented much more efficiently. The trick is that 1148 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1149 // arithmetic. To do exact division in modular arithmetic, all we have 1150 // to do is multiply by the inverse. Therefore, this step can be done at 1151 // width W. 1152 // 1153 // The next issue is how to safely do the division by 2^T. The way this 1154 // is done is by doing the multiplication step at a width of at least W + T 1155 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1156 // when we perform the division by 2^T (which is equivalent to a right shift 1157 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1158 // truncated out after the division by 2^T. 1159 // 1160 // In comparison to just directly using the first formula, this technique 1161 // is much more efficient; using the first formula requires W * K bits, 1162 // but this formula less than W + K bits. Also, the first formula requires 1163 // a division step, whereas this formula only requires multiplies and shifts. 1164 // 1165 // It doesn't matter whether the subtraction step is done in the calculation 1166 // width or the input iteration count's width; if the subtraction overflows, 1167 // the result must be zero anyway. We prefer here to do it in the width of 1168 // the induction variable because it helps a lot for certain cases; CodeGen 1169 // isn't smart enough to ignore the overflow, which leads to much less 1170 // efficient code if the width of the subtraction is wider than the native 1171 // register width. 1172 // 1173 // (It's possible to not widen at all by pulling out factors of 2 before 1174 // the multiplication; for example, K=2 can be calculated as 1175 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1176 // extra arithmetic, so it's not an obvious win, and it gets 1177 // much more complicated for K > 3.) 1178 1179 // Protection from insane SCEVs; this bound is conservative, 1180 // but it probably doesn't matter. 1181 if (K > 1000) 1182 return SE.getCouldNotCompute(); 1183 1184 unsigned W = SE.getTypeSizeInBits(ResultTy); 1185 1186 // Calculate K! / 2^T and T; we divide out the factors of two before 1187 // multiplying for calculating K! / 2^T to avoid overflow. 1188 // Other overflow doesn't matter because we only care about the bottom 1189 // W bits of the result. 1190 APInt OddFactorial(W, 1); 1191 unsigned T = 1; 1192 for (unsigned i = 3; i <= K; ++i) { 1193 APInt Mult(W, i); 1194 unsigned TwoFactors = Mult.countTrailingZeros(); 1195 T += TwoFactors; 1196 Mult.lshrInPlace(TwoFactors); 1197 OddFactorial *= Mult; 1198 } 1199 1200 // We need at least W + T bits for the multiplication step 1201 unsigned CalculationBits = W + T; 1202 1203 // Calculate 2^T, at width T+W. 1204 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1205 1206 // Calculate the multiplicative inverse of K! / 2^T; 1207 // this multiplication factor will perform the exact division by 1208 // K! / 2^T. 1209 APInt Mod = APInt::getSignedMinValue(W+1); 1210 APInt MultiplyFactor = OddFactorial.zext(W+1); 1211 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1212 MultiplyFactor = MultiplyFactor.trunc(W); 1213 1214 // Calculate the product, at width T+W 1215 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1216 CalculationBits); 1217 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1218 for (unsigned i = 1; i != K; ++i) { 1219 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1220 Dividend = SE.getMulExpr(Dividend, 1221 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1222 } 1223 1224 // Divide by 2^T 1225 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1226 1227 // Truncate the result, and divide by K! / 2^T. 1228 1229 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1230 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1231 } 1232 1233 /// Return the value of this chain of recurrences at the specified iteration 1234 /// number. We can evaluate this recurrence by multiplying each element in the 1235 /// chain by the binomial coefficient corresponding to it. In other words, we 1236 /// can evaluate {A,+,B,+,C,+,D} as: 1237 /// 1238 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1239 /// 1240 /// where BC(It, k) stands for binomial coefficient. 1241 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1242 ScalarEvolution &SE) const { 1243 const SCEV *Result = getStart(); 1244 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1245 // The computation is correct in the face of overflow provided that the 1246 // multiplication is performed _after_ the evaluation of the binomial 1247 // coefficient. 1248 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1249 if (isa<SCEVCouldNotCompute>(Coeff)) 1250 return Coeff; 1251 1252 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1253 } 1254 return Result; 1255 } 1256 1257 //===----------------------------------------------------------------------===// 1258 // SCEV Expression folder implementations 1259 //===----------------------------------------------------------------------===// 1260 1261 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1262 unsigned Depth) { 1263 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1264 "This is not a truncating conversion!"); 1265 assert(isSCEVable(Ty) && 1266 "This is not a conversion to a SCEVable type!"); 1267 Ty = getEffectiveSCEVType(Ty); 1268 1269 FoldingSetNodeID ID; 1270 ID.AddInteger(scTruncate); 1271 ID.AddPointer(Op); 1272 ID.AddPointer(Ty); 1273 void *IP = nullptr; 1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1275 1276 // Fold if the operand is constant. 1277 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1278 return getConstant( 1279 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1280 1281 // trunc(trunc(x)) --> trunc(x) 1282 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1283 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1284 1285 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1286 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1287 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1288 1289 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1290 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1291 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1292 1293 if (Depth > MaxCastDepth) { 1294 SCEV *S = 1295 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1296 UniqueSCEVs.InsertNode(S, IP); 1297 addToLoopUseLists(S); 1298 return S; 1299 } 1300 1301 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1302 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1303 // if after transforming we have at most one truncate, not counting truncates 1304 // that replace other casts. 1305 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1306 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1307 SmallVector<const SCEV *, 4> Operands; 1308 unsigned numTruncs = 0; 1309 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1310 ++i) { 1311 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1312 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1313 numTruncs++; 1314 Operands.push_back(S); 1315 } 1316 if (numTruncs < 2) { 1317 if (isa<SCEVAddExpr>(Op)) 1318 return getAddExpr(Operands); 1319 else if (isa<SCEVMulExpr>(Op)) 1320 return getMulExpr(Operands); 1321 else 1322 llvm_unreachable("Unexpected SCEV type for Op."); 1323 } 1324 // Although we checked in the beginning that ID is not in the cache, it is 1325 // possible that during recursion and different modification ID was inserted 1326 // into the cache. So if we find it, just return it. 1327 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1328 return S; 1329 } 1330 1331 // If the input value is a chrec scev, truncate the chrec's operands. 1332 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1333 SmallVector<const SCEV *, 4> Operands; 1334 for (const SCEV *Op : AddRec->operands()) 1335 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1336 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1337 } 1338 1339 // The cast wasn't folded; create an explicit cast node. We can reuse 1340 // the existing insert position since if we get here, we won't have 1341 // made any changes which would invalidate it. 1342 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1343 Op, Ty); 1344 UniqueSCEVs.InsertNode(S, IP); 1345 addToLoopUseLists(S); 1346 return S; 1347 } 1348 1349 // Get the limit of a recurrence such that incrementing by Step cannot cause 1350 // signed overflow as long as the value of the recurrence within the 1351 // loop does not exceed this limit before incrementing. 1352 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1353 ICmpInst::Predicate *Pred, 1354 ScalarEvolution *SE) { 1355 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1356 if (SE->isKnownPositive(Step)) { 1357 *Pred = ICmpInst::ICMP_SLT; 1358 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1359 SE->getSignedRangeMax(Step)); 1360 } 1361 if (SE->isKnownNegative(Step)) { 1362 *Pred = ICmpInst::ICMP_SGT; 1363 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1364 SE->getSignedRangeMin(Step)); 1365 } 1366 return nullptr; 1367 } 1368 1369 // Get the limit of a recurrence such that incrementing by Step cannot cause 1370 // unsigned overflow as long as the value of the recurrence within the loop does 1371 // not exceed this limit before incrementing. 1372 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1373 ICmpInst::Predicate *Pred, 1374 ScalarEvolution *SE) { 1375 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1376 *Pred = ICmpInst::ICMP_ULT; 1377 1378 return SE->getConstant(APInt::getMinValue(BitWidth) - 1379 SE->getUnsignedRangeMax(Step)); 1380 } 1381 1382 namespace { 1383 1384 struct ExtendOpTraitsBase { 1385 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1386 unsigned); 1387 }; 1388 1389 // Used to make code generic over signed and unsigned overflow. 1390 template <typename ExtendOp> struct ExtendOpTraits { 1391 // Members present: 1392 // 1393 // static const SCEV::NoWrapFlags WrapType; 1394 // 1395 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1396 // 1397 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1398 // ICmpInst::Predicate *Pred, 1399 // ScalarEvolution *SE); 1400 }; 1401 1402 template <> 1403 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1404 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1405 1406 static const GetExtendExprTy GetExtendExpr; 1407 1408 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1409 ICmpInst::Predicate *Pred, 1410 ScalarEvolution *SE) { 1411 return getSignedOverflowLimitForStep(Step, Pred, SE); 1412 } 1413 }; 1414 1415 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1416 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1417 1418 template <> 1419 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1420 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1421 1422 static const GetExtendExprTy GetExtendExpr; 1423 1424 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1425 ICmpInst::Predicate *Pred, 1426 ScalarEvolution *SE) { 1427 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1428 } 1429 }; 1430 1431 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1432 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1433 1434 } // end anonymous namespace 1435 1436 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1437 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1438 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1439 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1440 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1441 // expression "Step + sext/zext(PreIncAR)" is congruent with 1442 // "sext/zext(PostIncAR)" 1443 template <typename ExtendOpTy> 1444 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1445 ScalarEvolution *SE, unsigned Depth) { 1446 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1447 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1448 1449 const Loop *L = AR->getLoop(); 1450 const SCEV *Start = AR->getStart(); 1451 const SCEV *Step = AR->getStepRecurrence(*SE); 1452 1453 // Check for a simple looking step prior to loop entry. 1454 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1455 if (!SA) 1456 return nullptr; 1457 1458 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1459 // subtraction is expensive. For this purpose, perform a quick and dirty 1460 // difference, by checking for Step in the operand list. 1461 SmallVector<const SCEV *, 4> DiffOps; 1462 for (const SCEV *Op : SA->operands()) 1463 if (Op != Step) 1464 DiffOps.push_back(Op); 1465 1466 if (DiffOps.size() == SA->getNumOperands()) 1467 return nullptr; 1468 1469 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1470 // `Step`: 1471 1472 // 1. NSW/NUW flags on the step increment. 1473 auto PreStartFlags = 1474 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1475 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1476 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1477 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1478 1479 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1480 // "S+X does not sign/unsign-overflow". 1481 // 1482 1483 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1484 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1485 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1486 return PreStart; 1487 1488 // 2. Direct overflow check on the step operation's expression. 1489 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1490 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1491 const SCEV *OperandExtendedStart = 1492 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1493 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1494 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1495 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1496 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1497 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1498 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1499 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1500 } 1501 return PreStart; 1502 } 1503 1504 // 3. Loop precondition. 1505 ICmpInst::Predicate Pred; 1506 const SCEV *OverflowLimit = 1507 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1508 1509 if (OverflowLimit && 1510 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1511 return PreStart; 1512 1513 return nullptr; 1514 } 1515 1516 // Get the normalized zero or sign extended expression for this AddRec's Start. 1517 template <typename ExtendOpTy> 1518 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1519 ScalarEvolution *SE, 1520 unsigned Depth) { 1521 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1522 1523 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1524 if (!PreStart) 1525 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1526 1527 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1528 Depth), 1529 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1530 } 1531 1532 // Try to prove away overflow by looking at "nearby" add recurrences. A 1533 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1534 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1535 // 1536 // Formally: 1537 // 1538 // {S,+,X} == {S-T,+,X} + T 1539 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1540 // 1541 // If ({S-T,+,X} + T) does not overflow ... (1) 1542 // 1543 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1544 // 1545 // If {S-T,+,X} does not overflow ... (2) 1546 // 1547 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1548 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1549 // 1550 // If (S-T)+T does not overflow ... (3) 1551 // 1552 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1553 // == {Ext(S),+,Ext(X)} == LHS 1554 // 1555 // Thus, if (1), (2) and (3) are true for some T, then 1556 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1557 // 1558 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1559 // does not overflow" restricted to the 0th iteration. Therefore we only need 1560 // to check for (1) and (2). 1561 // 1562 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1563 // is `Delta` (defined below). 1564 template <typename ExtendOpTy> 1565 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1566 const SCEV *Step, 1567 const Loop *L) { 1568 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1569 1570 // We restrict `Start` to a constant to prevent SCEV from spending too much 1571 // time here. It is correct (but more expensive) to continue with a 1572 // non-constant `Start` and do a general SCEV subtraction to compute 1573 // `PreStart` below. 1574 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1575 if (!StartC) 1576 return false; 1577 1578 APInt StartAI = StartC->getAPInt(); 1579 1580 for (unsigned Delta : {-2, -1, 1, 2}) { 1581 const SCEV *PreStart = getConstant(StartAI - Delta); 1582 1583 FoldingSetNodeID ID; 1584 ID.AddInteger(scAddRecExpr); 1585 ID.AddPointer(PreStart); 1586 ID.AddPointer(Step); 1587 ID.AddPointer(L); 1588 void *IP = nullptr; 1589 const auto *PreAR = 1590 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1591 1592 // Give up if we don't already have the add recurrence we need because 1593 // actually constructing an add recurrence is relatively expensive. 1594 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1595 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1596 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1597 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1598 DeltaS, &Pred, this); 1599 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1600 return true; 1601 } 1602 } 1603 1604 return false; 1605 } 1606 1607 // Finds an integer D for an expression (C + x + y + ...) such that the top 1608 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1609 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1610 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1611 // the (C + x + y + ...) expression is \p WholeAddExpr. 1612 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1613 const SCEVConstant *ConstantTerm, 1614 const SCEVAddExpr *WholeAddExpr) { 1615 const APInt C = ConstantTerm->getAPInt(); 1616 const unsigned BitWidth = C.getBitWidth(); 1617 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1618 uint32_t TZ = BitWidth; 1619 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1620 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1621 if (TZ) { 1622 // Set D to be as many least significant bits of C as possible while still 1623 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1624 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1625 } 1626 return APInt(BitWidth, 0); 1627 } 1628 1629 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1630 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1631 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1632 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1633 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1634 const APInt &ConstantStart, 1635 const SCEV *Step) { 1636 const unsigned BitWidth = ConstantStart.getBitWidth(); 1637 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1638 if (TZ) 1639 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1640 : ConstantStart; 1641 return APInt(BitWidth, 0); 1642 } 1643 1644 const SCEV * 1645 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1646 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1647 "This is not an extending conversion!"); 1648 assert(isSCEVable(Ty) && 1649 "This is not a conversion to a SCEVable type!"); 1650 Ty = getEffectiveSCEVType(Ty); 1651 1652 // Fold if the operand is constant. 1653 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1654 return getConstant( 1655 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1656 1657 // zext(zext(x)) --> zext(x) 1658 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1659 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1660 1661 // Before doing any expensive analysis, check to see if we've already 1662 // computed a SCEV for this Op and Ty. 1663 FoldingSetNodeID ID; 1664 ID.AddInteger(scZeroExtend); 1665 ID.AddPointer(Op); 1666 ID.AddPointer(Ty); 1667 void *IP = nullptr; 1668 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1669 if (Depth > MaxCastDepth) { 1670 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1671 Op, Ty); 1672 UniqueSCEVs.InsertNode(S, IP); 1673 addToLoopUseLists(S); 1674 return S; 1675 } 1676 1677 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1678 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1679 // It's possible the bits taken off by the truncate were all zero bits. If 1680 // so, we should be able to simplify this further. 1681 const SCEV *X = ST->getOperand(); 1682 ConstantRange CR = getUnsignedRange(X); 1683 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1684 unsigned NewBits = getTypeSizeInBits(Ty); 1685 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1686 CR.zextOrTrunc(NewBits))) 1687 return getTruncateOrZeroExtend(X, Ty, Depth); 1688 } 1689 1690 // If the input value is a chrec scev, and we can prove that the value 1691 // did not overflow the old, smaller, value, we can zero extend all of the 1692 // operands (often constants). This allows analysis of something like 1693 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1694 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1695 if (AR->isAffine()) { 1696 const SCEV *Start = AR->getStart(); 1697 const SCEV *Step = AR->getStepRecurrence(*this); 1698 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1699 const Loop *L = AR->getLoop(); 1700 1701 if (!AR->hasNoUnsignedWrap()) { 1702 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1703 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1704 } 1705 1706 // If we have special knowledge that this addrec won't overflow, 1707 // we don't need to do any further analysis. 1708 if (AR->hasNoUnsignedWrap()) 1709 return getAddRecExpr( 1710 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1711 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1712 1713 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1714 // Note that this serves two purposes: It filters out loops that are 1715 // simply not analyzable, and it covers the case where this code is 1716 // being called from within backedge-taken count analysis, such that 1717 // attempting to ask for the backedge-taken count would likely result 1718 // in infinite recursion. In the later case, the analysis code will 1719 // cope with a conservative value, and it will take care to purge 1720 // that value once it has finished. 1721 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1722 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1723 // Manually compute the final value for AR, checking for 1724 // overflow. 1725 1726 // Check whether the backedge-taken count can be losslessly casted to 1727 // the addrec's type. The count is always unsigned. 1728 const SCEV *CastedMaxBECount = 1729 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1730 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1731 CastedMaxBECount, MaxBECount->getType(), Depth); 1732 if (MaxBECount == RecastedMaxBECount) { 1733 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1734 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1735 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1736 SCEV::FlagAnyWrap, Depth + 1); 1737 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1738 SCEV::FlagAnyWrap, 1739 Depth + 1), 1740 WideTy, Depth + 1); 1741 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1742 const SCEV *WideMaxBECount = 1743 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1744 const SCEV *OperandExtendedAdd = 1745 getAddExpr(WideStart, 1746 getMulExpr(WideMaxBECount, 1747 getZeroExtendExpr(Step, WideTy, Depth + 1), 1748 SCEV::FlagAnyWrap, Depth + 1), 1749 SCEV::FlagAnyWrap, Depth + 1); 1750 if (ZAdd == OperandExtendedAdd) { 1751 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1752 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1753 // Return the expression with the addrec on the outside. 1754 return getAddRecExpr( 1755 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1756 Depth + 1), 1757 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1758 AR->getNoWrapFlags()); 1759 } 1760 // Similar to above, only this time treat the step value as signed. 1761 // This covers loops that count down. 1762 OperandExtendedAdd = 1763 getAddExpr(WideStart, 1764 getMulExpr(WideMaxBECount, 1765 getSignExtendExpr(Step, WideTy, Depth + 1), 1766 SCEV::FlagAnyWrap, Depth + 1), 1767 SCEV::FlagAnyWrap, Depth + 1); 1768 if (ZAdd == OperandExtendedAdd) { 1769 // Cache knowledge of AR NW, which is propagated to this AddRec. 1770 // Negative step causes unsigned wrap, but it still can't self-wrap. 1771 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1772 // Return the expression with the addrec on the outside. 1773 return getAddRecExpr( 1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1775 Depth + 1), 1776 getSignExtendExpr(Step, Ty, Depth + 1), L, 1777 AR->getNoWrapFlags()); 1778 } 1779 } 1780 } 1781 1782 // Normally, in the cases we can prove no-overflow via a 1783 // backedge guarding condition, we can also compute a backedge 1784 // taken count for the loop. The exceptions are assumptions and 1785 // guards present in the loop -- SCEV is not great at exploiting 1786 // these to compute max backedge taken counts, but can still use 1787 // these to prove lack of overflow. Use this fact to avoid 1788 // doing extra work that may not pay off. 1789 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1790 !AC.assumptions().empty()) { 1791 // If the backedge is guarded by a comparison with the pre-inc 1792 // value the addrec is safe. Also, if the entry is guarded by 1793 // a comparison with the start value and the backedge is 1794 // guarded by a comparison with the post-inc value, the addrec 1795 // is safe. 1796 if (isKnownPositive(Step)) { 1797 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1798 getUnsignedRangeMax(Step)); 1799 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1800 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1801 // Cache knowledge of AR NUW, which is propagated to this 1802 // AddRec. 1803 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1804 // Return the expression with the addrec on the outside. 1805 return getAddRecExpr( 1806 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1807 Depth + 1), 1808 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1809 AR->getNoWrapFlags()); 1810 } 1811 } else if (isKnownNegative(Step)) { 1812 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1813 getSignedRangeMin(Step)); 1814 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1815 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1816 // Cache knowledge of AR NW, which is propagated to this 1817 // AddRec. Negative step causes unsigned wrap, but it 1818 // still can't self-wrap. 1819 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1820 // Return the expression with the addrec on the outside. 1821 return getAddRecExpr( 1822 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1823 Depth + 1), 1824 getSignExtendExpr(Step, Ty, Depth + 1), L, 1825 AR->getNoWrapFlags()); 1826 } 1827 } 1828 } 1829 1830 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1831 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1832 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1833 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1834 const APInt &C = SC->getAPInt(); 1835 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1836 if (D != 0) { 1837 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1838 const SCEV *SResidual = 1839 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1840 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1841 return getAddExpr(SZExtD, SZExtR, 1842 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1843 Depth + 1); 1844 } 1845 } 1846 1847 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1848 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1849 return getAddRecExpr( 1850 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1851 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1852 } 1853 } 1854 1855 // zext(A % B) --> zext(A) % zext(B) 1856 { 1857 const SCEV *LHS; 1858 const SCEV *RHS; 1859 if (matchURem(Op, LHS, RHS)) 1860 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1861 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1862 } 1863 1864 // zext(A / B) --> zext(A) / zext(B). 1865 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1866 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1867 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1868 1869 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1870 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1871 if (SA->hasNoUnsignedWrap()) { 1872 // If the addition does not unsign overflow then we can, by definition, 1873 // commute the zero extension with the addition operation. 1874 SmallVector<const SCEV *, 4> Ops; 1875 for (const auto *Op : SA->operands()) 1876 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1877 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1878 } 1879 1880 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1881 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1882 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1883 // 1884 // Often address arithmetics contain expressions like 1885 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1886 // This transformation is useful while proving that such expressions are 1887 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1888 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1889 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1890 if (D != 0) { 1891 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1892 const SCEV *SResidual = 1893 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1894 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1895 return getAddExpr(SZExtD, SZExtR, 1896 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1897 Depth + 1); 1898 } 1899 } 1900 } 1901 1902 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1903 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1904 if (SM->hasNoUnsignedWrap()) { 1905 // If the multiply does not unsign overflow then we can, by definition, 1906 // commute the zero extension with the multiply operation. 1907 SmallVector<const SCEV *, 4> Ops; 1908 for (const auto *Op : SM->operands()) 1909 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1910 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1911 } 1912 1913 // zext(2^K * (trunc X to iN)) to iM -> 1914 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1915 // 1916 // Proof: 1917 // 1918 // zext(2^K * (trunc X to iN)) to iM 1919 // = zext((trunc X to iN) << K) to iM 1920 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1921 // (because shl removes the top K bits) 1922 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1923 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1924 // 1925 if (SM->getNumOperands() == 2) 1926 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1927 if (MulLHS->getAPInt().isPowerOf2()) 1928 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1929 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1930 MulLHS->getAPInt().logBase2(); 1931 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1932 return getMulExpr( 1933 getZeroExtendExpr(MulLHS, Ty), 1934 getZeroExtendExpr( 1935 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1936 SCEV::FlagNUW, Depth + 1); 1937 } 1938 } 1939 1940 // The cast wasn't folded; create an explicit cast node. 1941 // Recompute the insert position, as it may have been invalidated. 1942 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1943 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1944 Op, Ty); 1945 UniqueSCEVs.InsertNode(S, IP); 1946 addToLoopUseLists(S); 1947 return S; 1948 } 1949 1950 const SCEV * 1951 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1952 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1953 "This is not an extending conversion!"); 1954 assert(isSCEVable(Ty) && 1955 "This is not a conversion to a SCEVable type!"); 1956 Ty = getEffectiveSCEVType(Ty); 1957 1958 // Fold if the operand is constant. 1959 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1960 return getConstant( 1961 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1962 1963 // sext(sext(x)) --> sext(x) 1964 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1965 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1966 1967 // sext(zext(x)) --> zext(x) 1968 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1969 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1970 1971 // Before doing any expensive analysis, check to see if we've already 1972 // computed a SCEV for this Op and Ty. 1973 FoldingSetNodeID ID; 1974 ID.AddInteger(scSignExtend); 1975 ID.AddPointer(Op); 1976 ID.AddPointer(Ty); 1977 void *IP = nullptr; 1978 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1979 // Limit recursion depth. 1980 if (Depth > MaxCastDepth) { 1981 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1982 Op, Ty); 1983 UniqueSCEVs.InsertNode(S, IP); 1984 addToLoopUseLists(S); 1985 return S; 1986 } 1987 1988 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1989 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1990 // It's possible the bits taken off by the truncate were all sign bits. If 1991 // so, we should be able to simplify this further. 1992 const SCEV *X = ST->getOperand(); 1993 ConstantRange CR = getSignedRange(X); 1994 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1995 unsigned NewBits = getTypeSizeInBits(Ty); 1996 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1997 CR.sextOrTrunc(NewBits))) 1998 return getTruncateOrSignExtend(X, Ty, Depth); 1999 } 2000 2001 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 2002 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 2003 if (SA->hasNoSignedWrap()) { 2004 // If the addition does not sign overflow then we can, by definition, 2005 // commute the sign extension with the addition operation. 2006 SmallVector<const SCEV *, 4> Ops; 2007 for (const auto *Op : SA->operands()) 2008 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2009 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2010 } 2011 2012 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2013 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2014 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2015 // 2016 // For instance, this will bring two seemingly different expressions: 2017 // 1 + sext(5 + 20 * %x + 24 * %y) and 2018 // sext(6 + 20 * %x + 24 * %y) 2019 // to the same form: 2020 // 2 + sext(4 + 20 * %x + 24 * %y) 2021 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2022 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2023 if (D != 0) { 2024 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2025 const SCEV *SResidual = 2026 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2027 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2028 return getAddExpr(SSExtD, SSExtR, 2029 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2030 Depth + 1); 2031 } 2032 } 2033 } 2034 // If the input value is a chrec scev, and we can prove that the value 2035 // did not overflow the old, smaller, value, we can sign extend all of the 2036 // operands (often constants). This allows analysis of something like 2037 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2038 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2039 if (AR->isAffine()) { 2040 const SCEV *Start = AR->getStart(); 2041 const SCEV *Step = AR->getStepRecurrence(*this); 2042 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2043 const Loop *L = AR->getLoop(); 2044 2045 if (!AR->hasNoSignedWrap()) { 2046 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2047 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2048 } 2049 2050 // If we have special knowledge that this addrec won't overflow, 2051 // we don't need to do any further analysis. 2052 if (AR->hasNoSignedWrap()) 2053 return getAddRecExpr( 2054 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2055 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2056 2057 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2058 // Note that this serves two purposes: It filters out loops that are 2059 // simply not analyzable, and it covers the case where this code is 2060 // being called from within backedge-taken count analysis, such that 2061 // attempting to ask for the backedge-taken count would likely result 2062 // in infinite recursion. In the later case, the analysis code will 2063 // cope with a conservative value, and it will take care to purge 2064 // that value once it has finished. 2065 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2066 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2067 // Manually compute the final value for AR, checking for 2068 // overflow. 2069 2070 // Check whether the backedge-taken count can be losslessly casted to 2071 // the addrec's type. The count is always unsigned. 2072 const SCEV *CastedMaxBECount = 2073 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2074 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2075 CastedMaxBECount, MaxBECount->getType(), Depth); 2076 if (MaxBECount == RecastedMaxBECount) { 2077 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2078 // Check whether Start+Step*MaxBECount has no signed overflow. 2079 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2080 SCEV::FlagAnyWrap, Depth + 1); 2081 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2082 SCEV::FlagAnyWrap, 2083 Depth + 1), 2084 WideTy, Depth + 1); 2085 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2086 const SCEV *WideMaxBECount = 2087 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2088 const SCEV *OperandExtendedAdd = 2089 getAddExpr(WideStart, 2090 getMulExpr(WideMaxBECount, 2091 getSignExtendExpr(Step, WideTy, Depth + 1), 2092 SCEV::FlagAnyWrap, Depth + 1), 2093 SCEV::FlagAnyWrap, Depth + 1); 2094 if (SAdd == OperandExtendedAdd) { 2095 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2096 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2097 // Return the expression with the addrec on the outside. 2098 return getAddRecExpr( 2099 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2100 Depth + 1), 2101 getSignExtendExpr(Step, Ty, Depth + 1), L, 2102 AR->getNoWrapFlags()); 2103 } 2104 // Similar to above, only this time treat the step value as unsigned. 2105 // This covers loops that count up with an unsigned step. 2106 OperandExtendedAdd = 2107 getAddExpr(WideStart, 2108 getMulExpr(WideMaxBECount, 2109 getZeroExtendExpr(Step, WideTy, Depth + 1), 2110 SCEV::FlagAnyWrap, Depth + 1), 2111 SCEV::FlagAnyWrap, Depth + 1); 2112 if (SAdd == OperandExtendedAdd) { 2113 // If AR wraps around then 2114 // 2115 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2116 // => SAdd != OperandExtendedAdd 2117 // 2118 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2119 // (SAdd == OperandExtendedAdd => AR is NW) 2120 2121 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2122 2123 // Return the expression with the addrec on the outside. 2124 return getAddRecExpr( 2125 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2126 Depth + 1), 2127 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2128 AR->getNoWrapFlags()); 2129 } 2130 } 2131 } 2132 2133 // Normally, in the cases we can prove no-overflow via a 2134 // backedge guarding condition, we can also compute a backedge 2135 // taken count for the loop. The exceptions are assumptions and 2136 // guards present in the loop -- SCEV is not great at exploiting 2137 // these to compute max backedge taken counts, but can still use 2138 // these to prove lack of overflow. Use this fact to avoid 2139 // doing extra work that may not pay off. 2140 2141 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2142 !AC.assumptions().empty()) { 2143 // If the backedge is guarded by a comparison with the pre-inc 2144 // value the addrec is safe. Also, if the entry is guarded by 2145 // a comparison with the start value and the backedge is 2146 // guarded by a comparison with the post-inc value, the addrec 2147 // is safe. 2148 ICmpInst::Predicate Pred; 2149 const SCEV *OverflowLimit = 2150 getSignedOverflowLimitForStep(Step, &Pred, this); 2151 if (OverflowLimit && 2152 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2153 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2154 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2155 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2156 return getAddRecExpr( 2157 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2158 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2159 } 2160 } 2161 2162 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2163 // if D + (C - D + Step * n) could be proven to not signed wrap 2164 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2165 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2166 const APInt &C = SC->getAPInt(); 2167 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2168 if (D != 0) { 2169 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2170 const SCEV *SResidual = 2171 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2172 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2173 return getAddExpr(SSExtD, SSExtR, 2174 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2175 Depth + 1); 2176 } 2177 } 2178 2179 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2180 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2181 return getAddRecExpr( 2182 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2183 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2184 } 2185 } 2186 2187 // If the input value is provably positive and we could not simplify 2188 // away the sext build a zext instead. 2189 if (isKnownNonNegative(Op)) 2190 return getZeroExtendExpr(Op, Ty, Depth + 1); 2191 2192 // The cast wasn't folded; create an explicit cast node. 2193 // Recompute the insert position, as it may have been invalidated. 2194 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2195 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2196 Op, Ty); 2197 UniqueSCEVs.InsertNode(S, IP); 2198 addToLoopUseLists(S); 2199 return S; 2200 } 2201 2202 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2203 /// unspecified bits out to the given type. 2204 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2205 Type *Ty) { 2206 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2207 "This is not an extending conversion!"); 2208 assert(isSCEVable(Ty) && 2209 "This is not a conversion to a SCEVable type!"); 2210 Ty = getEffectiveSCEVType(Ty); 2211 2212 // Sign-extend negative constants. 2213 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2214 if (SC->getAPInt().isNegative()) 2215 return getSignExtendExpr(Op, Ty); 2216 2217 // Peel off a truncate cast. 2218 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2219 const SCEV *NewOp = T->getOperand(); 2220 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2221 return getAnyExtendExpr(NewOp, Ty); 2222 return getTruncateOrNoop(NewOp, Ty); 2223 } 2224 2225 // Next try a zext cast. If the cast is folded, use it. 2226 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2227 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2228 return ZExt; 2229 2230 // Next try a sext cast. If the cast is folded, use it. 2231 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2232 if (!isa<SCEVSignExtendExpr>(SExt)) 2233 return SExt; 2234 2235 // Force the cast to be folded into the operands of an addrec. 2236 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2237 SmallVector<const SCEV *, 4> Ops; 2238 for (const SCEV *Op : AR->operands()) 2239 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2240 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2241 } 2242 2243 // If the expression is obviously signed, use the sext cast value. 2244 if (isa<SCEVSMaxExpr>(Op)) 2245 return SExt; 2246 2247 // Absent any other information, use the zext cast value. 2248 return ZExt; 2249 } 2250 2251 /// Process the given Ops list, which is a list of operands to be added under 2252 /// the given scale, update the given map. This is a helper function for 2253 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2254 /// that would form an add expression like this: 2255 /// 2256 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2257 /// 2258 /// where A and B are constants, update the map with these values: 2259 /// 2260 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2261 /// 2262 /// and add 13 + A*B*29 to AccumulatedConstant. 2263 /// This will allow getAddRecExpr to produce this: 2264 /// 2265 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2266 /// 2267 /// This form often exposes folding opportunities that are hidden in 2268 /// the original operand list. 2269 /// 2270 /// Return true iff it appears that any interesting folding opportunities 2271 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2272 /// the common case where no interesting opportunities are present, and 2273 /// is also used as a check to avoid infinite recursion. 2274 static bool 2275 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2276 SmallVectorImpl<const SCEV *> &NewOps, 2277 APInt &AccumulatedConstant, 2278 const SCEV *const *Ops, size_t NumOperands, 2279 const APInt &Scale, 2280 ScalarEvolution &SE) { 2281 bool Interesting = false; 2282 2283 // Iterate over the add operands. They are sorted, with constants first. 2284 unsigned i = 0; 2285 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2286 ++i; 2287 // Pull a buried constant out to the outside. 2288 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2289 Interesting = true; 2290 AccumulatedConstant += Scale * C->getAPInt(); 2291 } 2292 2293 // Next comes everything else. We're especially interested in multiplies 2294 // here, but they're in the middle, so just visit the rest with one loop. 2295 for (; i != NumOperands; ++i) { 2296 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2297 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2298 APInt NewScale = 2299 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2300 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2301 // A multiplication of a constant with another add; recurse. 2302 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2303 Interesting |= 2304 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2305 Add->op_begin(), Add->getNumOperands(), 2306 NewScale, SE); 2307 } else { 2308 // A multiplication of a constant with some other value. Update 2309 // the map. 2310 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2311 const SCEV *Key = SE.getMulExpr(MulOps); 2312 auto Pair = M.insert({Key, NewScale}); 2313 if (Pair.second) { 2314 NewOps.push_back(Pair.first->first); 2315 } else { 2316 Pair.first->second += NewScale; 2317 // The map already had an entry for this value, which may indicate 2318 // a folding opportunity. 2319 Interesting = true; 2320 } 2321 } 2322 } else { 2323 // An ordinary operand. Update the map. 2324 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2325 M.insert({Ops[i], Scale}); 2326 if (Pair.second) { 2327 NewOps.push_back(Pair.first->first); 2328 } else { 2329 Pair.first->second += Scale; 2330 // The map already had an entry for this value, which may indicate 2331 // a folding opportunity. 2332 Interesting = true; 2333 } 2334 } 2335 } 2336 2337 return Interesting; 2338 } 2339 2340 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2341 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2342 // can't-overflow flags for the operation if possible. 2343 static SCEV::NoWrapFlags 2344 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2345 const ArrayRef<const SCEV *> Ops, 2346 SCEV::NoWrapFlags Flags) { 2347 using namespace std::placeholders; 2348 2349 using OBO = OverflowingBinaryOperator; 2350 2351 bool CanAnalyze = 2352 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2353 (void)CanAnalyze; 2354 assert(CanAnalyze && "don't call from other places!"); 2355 2356 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2357 SCEV::NoWrapFlags SignOrUnsignWrap = 2358 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2359 2360 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2361 auto IsKnownNonNegative = [&](const SCEV *S) { 2362 return SE->isKnownNonNegative(S); 2363 }; 2364 2365 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2366 Flags = 2367 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2368 2369 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2370 2371 if (SignOrUnsignWrap != SignOrUnsignMask && 2372 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2373 isa<SCEVConstant>(Ops[0])) { 2374 2375 auto Opcode = [&] { 2376 switch (Type) { 2377 case scAddExpr: 2378 return Instruction::Add; 2379 case scMulExpr: 2380 return Instruction::Mul; 2381 default: 2382 llvm_unreachable("Unexpected SCEV op."); 2383 } 2384 }(); 2385 2386 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2387 2388 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2389 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2390 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2391 Opcode, C, OBO::NoSignedWrap); 2392 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2393 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2394 } 2395 2396 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2397 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2398 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2399 Opcode, C, OBO::NoUnsignedWrap); 2400 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2401 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2402 } 2403 } 2404 2405 return Flags; 2406 } 2407 2408 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2409 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2410 } 2411 2412 /// Get a canonical add expression, or something simpler if possible. 2413 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2414 SCEV::NoWrapFlags Flags, 2415 unsigned Depth) { 2416 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2417 "only nuw or nsw allowed"); 2418 assert(!Ops.empty() && "Cannot get empty add!"); 2419 if (Ops.size() == 1) return Ops[0]; 2420 #ifndef NDEBUG 2421 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2422 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2423 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2424 "SCEVAddExpr operand types don't match!"); 2425 #endif 2426 2427 // Sort by complexity, this groups all similar expression types together. 2428 GroupByComplexity(Ops, &LI, DT); 2429 2430 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2431 2432 // If there are any constants, fold them together. 2433 unsigned Idx = 0; 2434 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2435 ++Idx; 2436 assert(Idx < Ops.size()); 2437 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2438 // We found two constants, fold them together! 2439 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2440 if (Ops.size() == 2) return Ops[0]; 2441 Ops.erase(Ops.begin()+1); // Erase the folded element 2442 LHSC = cast<SCEVConstant>(Ops[0]); 2443 } 2444 2445 // If we are left with a constant zero being added, strip it off. 2446 if (LHSC->getValue()->isZero()) { 2447 Ops.erase(Ops.begin()); 2448 --Idx; 2449 } 2450 2451 if (Ops.size() == 1) return Ops[0]; 2452 } 2453 2454 // Limit recursion calls depth. 2455 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2456 return getOrCreateAddExpr(Ops, Flags); 2457 2458 // Okay, check to see if the same value occurs in the operand list more than 2459 // once. If so, merge them together into an multiply expression. Since we 2460 // sorted the list, these values are required to be adjacent. 2461 Type *Ty = Ops[0]->getType(); 2462 bool FoundMatch = false; 2463 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2464 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2465 // Scan ahead to count how many equal operands there are. 2466 unsigned Count = 2; 2467 while (i+Count != e && Ops[i+Count] == Ops[i]) 2468 ++Count; 2469 // Merge the values into a multiply. 2470 const SCEV *Scale = getConstant(Ty, Count); 2471 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2472 if (Ops.size() == Count) 2473 return Mul; 2474 Ops[i] = Mul; 2475 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2476 --i; e -= Count - 1; 2477 FoundMatch = true; 2478 } 2479 if (FoundMatch) 2480 return getAddExpr(Ops, Flags, Depth + 1); 2481 2482 // Check for truncates. If all the operands are truncated from the same 2483 // type, see if factoring out the truncate would permit the result to be 2484 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2485 // if the contents of the resulting outer trunc fold to something simple. 2486 auto FindTruncSrcType = [&]() -> Type * { 2487 // We're ultimately looking to fold an addrec of truncs and muls of only 2488 // constants and truncs, so if we find any other types of SCEV 2489 // as operands of the addrec then we bail and return nullptr here. 2490 // Otherwise, we return the type of the operand of a trunc that we find. 2491 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2492 return T->getOperand()->getType(); 2493 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2494 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2495 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2496 return T->getOperand()->getType(); 2497 } 2498 return nullptr; 2499 }; 2500 if (auto *SrcType = FindTruncSrcType()) { 2501 SmallVector<const SCEV *, 8> LargeOps; 2502 bool Ok = true; 2503 // Check all the operands to see if they can be represented in the 2504 // source type of the truncate. 2505 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2506 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2507 if (T->getOperand()->getType() != SrcType) { 2508 Ok = false; 2509 break; 2510 } 2511 LargeOps.push_back(T->getOperand()); 2512 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2513 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2514 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2515 SmallVector<const SCEV *, 8> LargeMulOps; 2516 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2517 if (const SCEVTruncateExpr *T = 2518 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2519 if (T->getOperand()->getType() != SrcType) { 2520 Ok = false; 2521 break; 2522 } 2523 LargeMulOps.push_back(T->getOperand()); 2524 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2525 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) 2532 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2533 } else { 2534 Ok = false; 2535 break; 2536 } 2537 } 2538 if (Ok) { 2539 // Evaluate the expression in the larger type. 2540 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2541 // If it folds to something simple, use it. Otherwise, don't. 2542 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2543 return getTruncateExpr(Fold, Ty); 2544 } 2545 } 2546 2547 // Skip past any other cast SCEVs. 2548 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2549 ++Idx; 2550 2551 // If there are add operands they would be next. 2552 if (Idx < Ops.size()) { 2553 bool DeletedAdd = false; 2554 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2555 if (Ops.size() > AddOpsInlineThreshold || 2556 Add->getNumOperands() > AddOpsInlineThreshold) 2557 break; 2558 // If we have an add, expand the add operands onto the end of the operands 2559 // list. 2560 Ops.erase(Ops.begin()+Idx); 2561 Ops.append(Add->op_begin(), Add->op_end()); 2562 DeletedAdd = true; 2563 } 2564 2565 // If we deleted at least one add, we added operands to the end of the list, 2566 // and they are not necessarily sorted. Recurse to resort and resimplify 2567 // any operands we just acquired. 2568 if (DeletedAdd) 2569 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2570 } 2571 2572 // Skip over the add expression until we get to a multiply. 2573 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2574 ++Idx; 2575 2576 // Check to see if there are any folding opportunities present with 2577 // operands multiplied by constant values. 2578 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2579 uint64_t BitWidth = getTypeSizeInBits(Ty); 2580 DenseMap<const SCEV *, APInt> M; 2581 SmallVector<const SCEV *, 8> NewOps; 2582 APInt AccumulatedConstant(BitWidth, 0); 2583 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2584 Ops.data(), Ops.size(), 2585 APInt(BitWidth, 1), *this)) { 2586 struct APIntCompare { 2587 bool operator()(const APInt &LHS, const APInt &RHS) const { 2588 return LHS.ult(RHS); 2589 } 2590 }; 2591 2592 // Some interesting folding opportunity is present, so its worthwhile to 2593 // re-generate the operands list. Group the operands by constant scale, 2594 // to avoid multiplying by the same constant scale multiple times. 2595 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2596 for (const SCEV *NewOp : NewOps) 2597 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2598 // Re-generate the operands list. 2599 Ops.clear(); 2600 if (AccumulatedConstant != 0) 2601 Ops.push_back(getConstant(AccumulatedConstant)); 2602 for (auto &MulOp : MulOpLists) 2603 if (MulOp.first != 0) 2604 Ops.push_back(getMulExpr( 2605 getConstant(MulOp.first), 2606 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2607 SCEV::FlagAnyWrap, Depth + 1)); 2608 if (Ops.empty()) 2609 return getZero(Ty); 2610 if (Ops.size() == 1) 2611 return Ops[0]; 2612 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2613 } 2614 } 2615 2616 // If we are adding something to a multiply expression, make sure the 2617 // something is not already an operand of the multiply. If so, merge it into 2618 // the multiply. 2619 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2620 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2621 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2622 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2623 if (isa<SCEVConstant>(MulOpSCEV)) 2624 continue; 2625 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2626 if (MulOpSCEV == Ops[AddOp]) { 2627 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2628 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2629 if (Mul->getNumOperands() != 2) { 2630 // If the multiply has more than two operands, we must get the 2631 // Y*Z term. 2632 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2633 Mul->op_begin()+MulOp); 2634 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2635 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2636 } 2637 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2638 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2639 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2640 SCEV::FlagAnyWrap, Depth + 1); 2641 if (Ops.size() == 2) return OuterMul; 2642 if (AddOp < Idx) { 2643 Ops.erase(Ops.begin()+AddOp); 2644 Ops.erase(Ops.begin()+Idx-1); 2645 } else { 2646 Ops.erase(Ops.begin()+Idx); 2647 Ops.erase(Ops.begin()+AddOp-1); 2648 } 2649 Ops.push_back(OuterMul); 2650 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2651 } 2652 2653 // Check this multiply against other multiplies being added together. 2654 for (unsigned OtherMulIdx = Idx+1; 2655 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2656 ++OtherMulIdx) { 2657 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2658 // If MulOp occurs in OtherMul, we can fold the two multiplies 2659 // together. 2660 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2661 OMulOp != e; ++OMulOp) 2662 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2663 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2664 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2665 if (Mul->getNumOperands() != 2) { 2666 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2667 Mul->op_begin()+MulOp); 2668 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2669 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2672 if (OtherMul->getNumOperands() != 2) { 2673 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2674 OtherMul->op_begin()+OMulOp); 2675 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2676 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2677 } 2678 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2679 const SCEV *InnerMulSum = 2680 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2681 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2682 SCEV::FlagAnyWrap, Depth + 1); 2683 if (Ops.size() == 2) return OuterMul; 2684 Ops.erase(Ops.begin()+Idx); 2685 Ops.erase(Ops.begin()+OtherMulIdx-1); 2686 Ops.push_back(OuterMul); 2687 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2688 } 2689 } 2690 } 2691 } 2692 2693 // If there are any add recurrences in the operands list, see if any other 2694 // added values are loop invariant. If so, we can fold them into the 2695 // recurrence. 2696 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2697 ++Idx; 2698 2699 // Scan over all recurrences, trying to fold loop invariants into them. 2700 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2701 // Scan all of the other operands to this add and add them to the vector if 2702 // they are loop invariant w.r.t. the recurrence. 2703 SmallVector<const SCEV *, 8> LIOps; 2704 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2705 const Loop *AddRecLoop = AddRec->getLoop(); 2706 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2707 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2708 LIOps.push_back(Ops[i]); 2709 Ops.erase(Ops.begin()+i); 2710 --i; --e; 2711 } 2712 2713 // If we found some loop invariants, fold them into the recurrence. 2714 if (!LIOps.empty()) { 2715 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2716 LIOps.push_back(AddRec->getStart()); 2717 2718 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2719 AddRec->op_end()); 2720 // This follows from the fact that the no-wrap flags on the outer add 2721 // expression are applicable on the 0th iteration, when the add recurrence 2722 // will be equal to its start value. 2723 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2724 2725 // Build the new addrec. Propagate the NUW and NSW flags if both the 2726 // outer add and the inner addrec are guaranteed to have no overflow. 2727 // Always propagate NW. 2728 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2729 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2730 2731 // If all of the other operands were loop invariant, we are done. 2732 if (Ops.size() == 1) return NewRec; 2733 2734 // Otherwise, add the folded AddRec by the non-invariant parts. 2735 for (unsigned i = 0;; ++i) 2736 if (Ops[i] == AddRec) { 2737 Ops[i] = NewRec; 2738 break; 2739 } 2740 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2741 } 2742 2743 // Okay, if there weren't any loop invariants to be folded, check to see if 2744 // there are multiple AddRec's with the same loop induction variable being 2745 // added together. If so, we can fold them. 2746 for (unsigned OtherIdx = Idx+1; 2747 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2748 ++OtherIdx) { 2749 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2750 // so that the 1st found AddRecExpr is dominated by all others. 2751 assert(DT.dominates( 2752 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2753 AddRec->getLoop()->getHeader()) && 2754 "AddRecExprs are not sorted in reverse dominance order?"); 2755 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2756 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2757 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2758 AddRec->op_end()); 2759 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2760 ++OtherIdx) { 2761 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2762 if (OtherAddRec->getLoop() == AddRecLoop) { 2763 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2764 i != e; ++i) { 2765 if (i >= AddRecOps.size()) { 2766 AddRecOps.append(OtherAddRec->op_begin()+i, 2767 OtherAddRec->op_end()); 2768 break; 2769 } 2770 SmallVector<const SCEV *, 2> TwoOps = { 2771 AddRecOps[i], OtherAddRec->getOperand(i)}; 2772 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2773 } 2774 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2775 } 2776 } 2777 // Step size has changed, so we cannot guarantee no self-wraparound. 2778 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2779 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2780 } 2781 } 2782 2783 // Otherwise couldn't fold anything into this recurrence. Move onto the 2784 // next one. 2785 } 2786 2787 // Okay, it looks like we really DO need an add expr. Check to see if we 2788 // already have one, otherwise create a new one. 2789 return getOrCreateAddExpr(Ops, Flags); 2790 } 2791 2792 const SCEV * 2793 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2794 SCEV::NoWrapFlags Flags) { 2795 FoldingSetNodeID ID; 2796 ID.AddInteger(scAddExpr); 2797 for (const SCEV *Op : Ops) 2798 ID.AddPointer(Op); 2799 void *IP = nullptr; 2800 SCEVAddExpr *S = 2801 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2802 if (!S) { 2803 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2804 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2805 S = new (SCEVAllocator) 2806 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2807 UniqueSCEVs.InsertNode(S, IP); 2808 addToLoopUseLists(S); 2809 } 2810 S->setNoWrapFlags(Flags); 2811 return S; 2812 } 2813 2814 const SCEV * 2815 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2816 const Loop *L, SCEV::NoWrapFlags Flags) { 2817 FoldingSetNodeID ID; 2818 ID.AddInteger(scAddRecExpr); 2819 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2820 ID.AddPointer(Ops[i]); 2821 ID.AddPointer(L); 2822 void *IP = nullptr; 2823 SCEVAddRecExpr *S = 2824 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2825 if (!S) { 2826 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2827 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2828 S = new (SCEVAllocator) 2829 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2830 UniqueSCEVs.InsertNode(S, IP); 2831 addToLoopUseLists(S); 2832 } 2833 S->setNoWrapFlags(Flags); 2834 return S; 2835 } 2836 2837 const SCEV * 2838 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2839 SCEV::NoWrapFlags Flags) { 2840 FoldingSetNodeID ID; 2841 ID.AddInteger(scMulExpr); 2842 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2843 ID.AddPointer(Ops[i]); 2844 void *IP = nullptr; 2845 SCEVMulExpr *S = 2846 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2847 if (!S) { 2848 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2849 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2850 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2851 O, Ops.size()); 2852 UniqueSCEVs.InsertNode(S, IP); 2853 addToLoopUseLists(S); 2854 } 2855 S->setNoWrapFlags(Flags); 2856 return S; 2857 } 2858 2859 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2860 uint64_t k = i*j; 2861 if (j > 1 && k / j != i) Overflow = true; 2862 return k; 2863 } 2864 2865 /// Compute the result of "n choose k", the binomial coefficient. If an 2866 /// intermediate computation overflows, Overflow will be set and the return will 2867 /// be garbage. Overflow is not cleared on absence of overflow. 2868 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2869 // We use the multiplicative formula: 2870 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2871 // At each iteration, we take the n-th term of the numeral and divide by the 2872 // (k-n)th term of the denominator. This division will always produce an 2873 // integral result, and helps reduce the chance of overflow in the 2874 // intermediate computations. However, we can still overflow even when the 2875 // final result would fit. 2876 2877 if (n == 0 || n == k) return 1; 2878 if (k > n) return 0; 2879 2880 if (k > n/2) 2881 k = n-k; 2882 2883 uint64_t r = 1; 2884 for (uint64_t i = 1; i <= k; ++i) { 2885 r = umul_ov(r, n-(i-1), Overflow); 2886 r /= i; 2887 } 2888 return r; 2889 } 2890 2891 /// Determine if any of the operands in this SCEV are a constant or if 2892 /// any of the add or multiply expressions in this SCEV contain a constant. 2893 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2894 struct FindConstantInAddMulChain { 2895 bool FoundConstant = false; 2896 2897 bool follow(const SCEV *S) { 2898 FoundConstant |= isa<SCEVConstant>(S); 2899 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2900 } 2901 2902 bool isDone() const { 2903 return FoundConstant; 2904 } 2905 }; 2906 2907 FindConstantInAddMulChain F; 2908 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2909 ST.visitAll(StartExpr); 2910 return F.FoundConstant; 2911 } 2912 2913 /// Get a canonical multiply expression, or something simpler if possible. 2914 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2915 SCEV::NoWrapFlags Flags, 2916 unsigned Depth) { 2917 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2918 "only nuw or nsw allowed"); 2919 assert(!Ops.empty() && "Cannot get empty mul!"); 2920 if (Ops.size() == 1) return Ops[0]; 2921 #ifndef NDEBUG 2922 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2923 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2924 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2925 "SCEVMulExpr operand types don't match!"); 2926 #endif 2927 2928 // Sort by complexity, this groups all similar expression types together. 2929 GroupByComplexity(Ops, &LI, DT); 2930 2931 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2932 2933 // Limit recursion calls depth. 2934 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2935 return getOrCreateMulExpr(Ops, Flags); 2936 2937 // If there are any constants, fold them together. 2938 unsigned Idx = 0; 2939 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2940 2941 if (Ops.size() == 2) 2942 // C1*(C2+V) -> C1*C2 + C1*V 2943 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2944 // If any of Add's ops are Adds or Muls with a constant, apply this 2945 // transformation as well. 2946 // 2947 // TODO: There are some cases where this transformation is not 2948 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2949 // this transformation should be narrowed down. 2950 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2951 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2952 SCEV::FlagAnyWrap, Depth + 1), 2953 getMulExpr(LHSC, Add->getOperand(1), 2954 SCEV::FlagAnyWrap, Depth + 1), 2955 SCEV::FlagAnyWrap, Depth + 1); 2956 2957 ++Idx; 2958 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2959 // We found two constants, fold them together! 2960 ConstantInt *Fold = 2961 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2962 Ops[0] = getConstant(Fold); 2963 Ops.erase(Ops.begin()+1); // Erase the folded element 2964 if (Ops.size() == 1) return Ops[0]; 2965 LHSC = cast<SCEVConstant>(Ops[0]); 2966 } 2967 2968 // If we are left with a constant one being multiplied, strip it off. 2969 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2970 Ops.erase(Ops.begin()); 2971 --Idx; 2972 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2973 // If we have a multiply of zero, it will always be zero. 2974 return Ops[0]; 2975 } else if (Ops[0]->isAllOnesValue()) { 2976 // If we have a mul by -1 of an add, try distributing the -1 among the 2977 // add operands. 2978 if (Ops.size() == 2) { 2979 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2980 SmallVector<const SCEV *, 4> NewOps; 2981 bool AnyFolded = false; 2982 for (const SCEV *AddOp : Add->operands()) { 2983 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2984 Depth + 1); 2985 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2986 NewOps.push_back(Mul); 2987 } 2988 if (AnyFolded) 2989 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2990 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2991 // Negation preserves a recurrence's no self-wrap property. 2992 SmallVector<const SCEV *, 4> Operands; 2993 for (const SCEV *AddRecOp : AddRec->operands()) 2994 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2995 Depth + 1)); 2996 2997 return getAddRecExpr(Operands, AddRec->getLoop(), 2998 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2999 } 3000 } 3001 } 3002 3003 if (Ops.size() == 1) 3004 return Ops[0]; 3005 } 3006 3007 // Skip over the add expression until we get to a multiply. 3008 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3009 ++Idx; 3010 3011 // If there are mul operands inline them all into this expression. 3012 if (Idx < Ops.size()) { 3013 bool DeletedMul = false; 3014 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3015 if (Ops.size() > MulOpsInlineThreshold) 3016 break; 3017 // If we have an mul, expand the mul operands onto the end of the 3018 // operands list. 3019 Ops.erase(Ops.begin()+Idx); 3020 Ops.append(Mul->op_begin(), Mul->op_end()); 3021 DeletedMul = true; 3022 } 3023 3024 // If we deleted at least one mul, we added operands to the end of the 3025 // list, and they are not necessarily sorted. Recurse to resort and 3026 // resimplify any operands we just acquired. 3027 if (DeletedMul) 3028 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3029 } 3030 3031 // If there are any add recurrences in the operands list, see if any other 3032 // added values are loop invariant. If so, we can fold them into the 3033 // recurrence. 3034 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3035 ++Idx; 3036 3037 // Scan over all recurrences, trying to fold loop invariants into them. 3038 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3039 // Scan all of the other operands to this mul and add them to the vector 3040 // if they are loop invariant w.r.t. the recurrence. 3041 SmallVector<const SCEV *, 8> LIOps; 3042 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3043 const Loop *AddRecLoop = AddRec->getLoop(); 3044 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3045 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3046 LIOps.push_back(Ops[i]); 3047 Ops.erase(Ops.begin()+i); 3048 --i; --e; 3049 } 3050 3051 // If we found some loop invariants, fold them into the recurrence. 3052 if (!LIOps.empty()) { 3053 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3054 SmallVector<const SCEV *, 4> NewOps; 3055 NewOps.reserve(AddRec->getNumOperands()); 3056 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3057 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3058 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3059 SCEV::FlagAnyWrap, Depth + 1)); 3060 3061 // Build the new addrec. Propagate the NUW and NSW flags if both the 3062 // outer mul and the inner addrec are guaranteed to have no overflow. 3063 // 3064 // No self-wrap cannot be guaranteed after changing the step size, but 3065 // will be inferred if either NUW or NSW is true. 3066 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3067 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3068 3069 // If all of the other operands were loop invariant, we are done. 3070 if (Ops.size() == 1) return NewRec; 3071 3072 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3073 for (unsigned i = 0;; ++i) 3074 if (Ops[i] == AddRec) { 3075 Ops[i] = NewRec; 3076 break; 3077 } 3078 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3079 } 3080 3081 // Okay, if there weren't any loop invariants to be folded, check to see 3082 // if there are multiple AddRec's with the same loop induction variable 3083 // being multiplied together. If so, we can fold them. 3084 3085 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3086 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3087 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3088 // ]]],+,...up to x=2n}. 3089 // Note that the arguments to choose() are always integers with values 3090 // known at compile time, never SCEV objects. 3091 // 3092 // The implementation avoids pointless extra computations when the two 3093 // addrec's are of different length (mathematically, it's equivalent to 3094 // an infinite stream of zeros on the right). 3095 bool OpsModified = false; 3096 for (unsigned OtherIdx = Idx+1; 3097 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3098 ++OtherIdx) { 3099 const SCEVAddRecExpr *OtherAddRec = 3100 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3101 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3102 continue; 3103 3104 // Limit max number of arguments to avoid creation of unreasonably big 3105 // SCEVAddRecs with very complex operands. 3106 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3107 MaxAddRecSize || isHugeExpression(AddRec) || 3108 isHugeExpression(OtherAddRec)) 3109 continue; 3110 3111 bool Overflow = false; 3112 Type *Ty = AddRec->getType(); 3113 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3114 SmallVector<const SCEV*, 7> AddRecOps; 3115 for (int x = 0, xe = AddRec->getNumOperands() + 3116 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3117 SmallVector <const SCEV *, 7> SumOps; 3118 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3119 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3120 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3121 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3122 z < ze && !Overflow; ++z) { 3123 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3124 uint64_t Coeff; 3125 if (LargerThan64Bits) 3126 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3127 else 3128 Coeff = Coeff1*Coeff2; 3129 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3130 const SCEV *Term1 = AddRec->getOperand(y-z); 3131 const SCEV *Term2 = OtherAddRec->getOperand(z); 3132 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3133 SCEV::FlagAnyWrap, Depth + 1)); 3134 } 3135 } 3136 if (SumOps.empty()) 3137 SumOps.push_back(getZero(Ty)); 3138 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3139 } 3140 if (!Overflow) { 3141 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3142 SCEV::FlagAnyWrap); 3143 if (Ops.size() == 2) return NewAddRec; 3144 Ops[Idx] = NewAddRec; 3145 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3146 OpsModified = true; 3147 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3148 if (!AddRec) 3149 break; 3150 } 3151 } 3152 if (OpsModified) 3153 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3154 3155 // Otherwise couldn't fold anything into this recurrence. Move onto the 3156 // next one. 3157 } 3158 3159 // Okay, it looks like we really DO need an mul expr. Check to see if we 3160 // already have one, otherwise create a new one. 3161 return getOrCreateMulExpr(Ops, Flags); 3162 } 3163 3164 /// Represents an unsigned remainder expression based on unsigned division. 3165 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3166 const SCEV *RHS) { 3167 assert(getEffectiveSCEVType(LHS->getType()) == 3168 getEffectiveSCEVType(RHS->getType()) && 3169 "SCEVURemExpr operand types don't match!"); 3170 3171 // Short-circuit easy cases 3172 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3173 // If constant is one, the result is trivial 3174 if (RHSC->getValue()->isOne()) 3175 return getZero(LHS->getType()); // X urem 1 --> 0 3176 3177 // If constant is a power of two, fold into a zext(trunc(LHS)). 3178 if (RHSC->getAPInt().isPowerOf2()) { 3179 Type *FullTy = LHS->getType(); 3180 Type *TruncTy = 3181 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3182 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3183 } 3184 } 3185 3186 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3187 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3188 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3189 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3190 } 3191 3192 /// Get a canonical unsigned division expression, or something simpler if 3193 /// possible. 3194 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3195 const SCEV *RHS) { 3196 assert(getEffectiveSCEVType(LHS->getType()) == 3197 getEffectiveSCEVType(RHS->getType()) && 3198 "SCEVUDivExpr operand types don't match!"); 3199 3200 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3201 if (RHSC->getValue()->isOne()) 3202 return LHS; // X udiv 1 --> x 3203 // If the denominator is zero, the result of the udiv is undefined. Don't 3204 // try to analyze it, because the resolution chosen here may differ from 3205 // the resolution chosen in other parts of the compiler. 3206 if (!RHSC->getValue()->isZero()) { 3207 // Determine if the division can be folded into the operands of 3208 // its operands. 3209 // TODO: Generalize this to non-constants by using known-bits information. 3210 Type *Ty = LHS->getType(); 3211 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3212 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3213 // For non-power-of-two values, effectively round the value up to the 3214 // nearest power of two. 3215 if (!RHSC->getAPInt().isPowerOf2()) 3216 ++MaxShiftAmt; 3217 IntegerType *ExtTy = 3218 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3219 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3220 if (const SCEVConstant *Step = 3221 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3222 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3223 const APInt &StepInt = Step->getAPInt(); 3224 const APInt &DivInt = RHSC->getAPInt(); 3225 if (!StepInt.urem(DivInt) && 3226 getZeroExtendExpr(AR, ExtTy) == 3227 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3228 getZeroExtendExpr(Step, ExtTy), 3229 AR->getLoop(), SCEV::FlagAnyWrap)) { 3230 SmallVector<const SCEV *, 4> Operands; 3231 for (const SCEV *Op : AR->operands()) 3232 Operands.push_back(getUDivExpr(Op, RHS)); 3233 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3234 } 3235 /// Get a canonical UDivExpr for a recurrence. 3236 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3237 // We can currently only fold X%N if X is constant. 3238 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3239 if (StartC && !DivInt.urem(StepInt) && 3240 getZeroExtendExpr(AR, ExtTy) == 3241 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3242 getZeroExtendExpr(Step, ExtTy), 3243 AR->getLoop(), SCEV::FlagAnyWrap)) { 3244 const APInt &StartInt = StartC->getAPInt(); 3245 const APInt &StartRem = StartInt.urem(StepInt); 3246 if (StartRem != 0) 3247 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3248 AR->getLoop(), SCEV::FlagNW); 3249 } 3250 } 3251 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3252 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3253 SmallVector<const SCEV *, 4> Operands; 3254 for (const SCEV *Op : M->operands()) 3255 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3256 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3257 // Find an operand that's safely divisible. 3258 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3259 const SCEV *Op = M->getOperand(i); 3260 const SCEV *Div = getUDivExpr(Op, RHSC); 3261 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3262 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3263 M->op_end()); 3264 Operands[i] = Div; 3265 return getMulExpr(Operands); 3266 } 3267 } 3268 } 3269 3270 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3271 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3272 if (auto *DivisorConstant = 3273 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3274 bool Overflow = false; 3275 APInt NewRHS = 3276 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3277 if (Overflow) { 3278 return getConstant(RHSC->getType(), 0, false); 3279 } 3280 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3281 } 3282 } 3283 3284 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3285 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3286 SmallVector<const SCEV *, 4> Operands; 3287 for (const SCEV *Op : A->operands()) 3288 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3289 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3290 Operands.clear(); 3291 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3292 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3293 if (isa<SCEVUDivExpr>(Op) || 3294 getMulExpr(Op, RHS) != A->getOperand(i)) 3295 break; 3296 Operands.push_back(Op); 3297 } 3298 if (Operands.size() == A->getNumOperands()) 3299 return getAddExpr(Operands); 3300 } 3301 } 3302 3303 // Fold if both operands are constant. 3304 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3305 Constant *LHSCV = LHSC->getValue(); 3306 Constant *RHSCV = RHSC->getValue(); 3307 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3308 RHSCV))); 3309 } 3310 } 3311 } 3312 3313 FoldingSetNodeID ID; 3314 ID.AddInteger(scUDivExpr); 3315 ID.AddPointer(LHS); 3316 ID.AddPointer(RHS); 3317 void *IP = nullptr; 3318 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3319 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3320 LHS, RHS); 3321 UniqueSCEVs.InsertNode(S, IP); 3322 addToLoopUseLists(S); 3323 return S; 3324 } 3325 3326 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3327 APInt A = C1->getAPInt().abs(); 3328 APInt B = C2->getAPInt().abs(); 3329 uint32_t ABW = A.getBitWidth(); 3330 uint32_t BBW = B.getBitWidth(); 3331 3332 if (ABW > BBW) 3333 B = B.zext(ABW); 3334 else if (ABW < BBW) 3335 A = A.zext(BBW); 3336 3337 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3338 } 3339 3340 /// Get a canonical unsigned division expression, or something simpler if 3341 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3342 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3343 /// it's not exact because the udiv may be clearing bits. 3344 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3345 const SCEV *RHS) { 3346 // TODO: we could try to find factors in all sorts of things, but for now we 3347 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3348 // end of this file for inspiration. 3349 3350 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3351 if (!Mul || !Mul->hasNoUnsignedWrap()) 3352 return getUDivExpr(LHS, RHS); 3353 3354 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3355 // If the mulexpr multiplies by a constant, then that constant must be the 3356 // first element of the mulexpr. 3357 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3358 if (LHSCst == RHSCst) { 3359 SmallVector<const SCEV *, 2> Operands; 3360 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3361 return getMulExpr(Operands); 3362 } 3363 3364 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3365 // that there's a factor provided by one of the other terms. We need to 3366 // check. 3367 APInt Factor = gcd(LHSCst, RHSCst); 3368 if (!Factor.isIntN(1)) { 3369 LHSCst = 3370 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3371 RHSCst = 3372 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3373 SmallVector<const SCEV *, 2> Operands; 3374 Operands.push_back(LHSCst); 3375 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3376 LHS = getMulExpr(Operands); 3377 RHS = RHSCst; 3378 Mul = dyn_cast<SCEVMulExpr>(LHS); 3379 if (!Mul) 3380 return getUDivExactExpr(LHS, RHS); 3381 } 3382 } 3383 } 3384 3385 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3386 if (Mul->getOperand(i) == RHS) { 3387 SmallVector<const SCEV *, 2> Operands; 3388 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3389 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3390 return getMulExpr(Operands); 3391 } 3392 } 3393 3394 return getUDivExpr(LHS, RHS); 3395 } 3396 3397 /// Get an add recurrence expression for the specified loop. Simplify the 3398 /// expression as much as possible. 3399 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3400 const Loop *L, 3401 SCEV::NoWrapFlags Flags) { 3402 SmallVector<const SCEV *, 4> Operands; 3403 Operands.push_back(Start); 3404 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3405 if (StepChrec->getLoop() == L) { 3406 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3407 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3408 } 3409 3410 Operands.push_back(Step); 3411 return getAddRecExpr(Operands, L, Flags); 3412 } 3413 3414 /// Get an add recurrence expression for the specified loop. Simplify the 3415 /// expression as much as possible. 3416 const SCEV * 3417 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3418 const Loop *L, SCEV::NoWrapFlags Flags) { 3419 if (Operands.size() == 1) return Operands[0]; 3420 #ifndef NDEBUG 3421 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3422 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3423 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3424 "SCEVAddRecExpr operand types don't match!"); 3425 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3426 assert(isLoopInvariant(Operands[i], L) && 3427 "SCEVAddRecExpr operand is not loop-invariant!"); 3428 #endif 3429 3430 if (Operands.back()->isZero()) { 3431 Operands.pop_back(); 3432 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3433 } 3434 3435 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3436 // use that information to infer NUW and NSW flags. However, computing a 3437 // BE count requires calling getAddRecExpr, so we may not yet have a 3438 // meaningful BE count at this point (and if we don't, we'd be stuck 3439 // with a SCEVCouldNotCompute as the cached BE count). 3440 3441 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3442 3443 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3444 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3445 const Loop *NestedLoop = NestedAR->getLoop(); 3446 if (L->contains(NestedLoop) 3447 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3448 : (!NestedLoop->contains(L) && 3449 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3450 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3451 NestedAR->op_end()); 3452 Operands[0] = NestedAR->getStart(); 3453 // AddRecs require their operands be loop-invariant with respect to their 3454 // loops. Don't perform this transformation if it would break this 3455 // requirement. 3456 bool AllInvariant = all_of( 3457 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3458 3459 if (AllInvariant) { 3460 // Create a recurrence for the outer loop with the same step size. 3461 // 3462 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3463 // inner recurrence has the same property. 3464 SCEV::NoWrapFlags OuterFlags = 3465 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3466 3467 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3468 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3469 return isLoopInvariant(Op, NestedLoop); 3470 }); 3471 3472 if (AllInvariant) { 3473 // Ok, both add recurrences are valid after the transformation. 3474 // 3475 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3476 // the outer recurrence has the same property. 3477 SCEV::NoWrapFlags InnerFlags = 3478 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3479 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3480 } 3481 } 3482 // Reset Operands to its original state. 3483 Operands[0] = NestedAR; 3484 } 3485 } 3486 3487 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3488 // already have one, otherwise create a new one. 3489 return getOrCreateAddRecExpr(Operands, L, Flags); 3490 } 3491 3492 const SCEV * 3493 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3494 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3495 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3496 // getSCEV(Base)->getType() has the same address space as Base->getType() 3497 // because SCEV::getType() preserves the address space. 3498 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3499 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3500 // instruction to its SCEV, because the Instruction may be guarded by control 3501 // flow and the no-overflow bits may not be valid for the expression in any 3502 // context. This can be fixed similarly to how these flags are handled for 3503 // adds. 3504 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3505 : SCEV::FlagAnyWrap; 3506 3507 const SCEV *TotalOffset = getZero(IntIdxTy); 3508 // The array size is unimportant. The first thing we do on CurTy is getting 3509 // its element type. 3510 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3511 for (const SCEV *IndexExpr : IndexExprs) { 3512 // Compute the (potentially symbolic) offset in bytes for this index. 3513 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3514 // For a struct, add the member offset. 3515 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3516 unsigned FieldNo = Index->getZExtValue(); 3517 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3518 3519 // Add the field offset to the running total offset. 3520 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3521 3522 // Update CurTy to the type of the field at Index. 3523 CurTy = STy->getTypeAtIndex(Index); 3524 } else { 3525 // Update CurTy to its element type. 3526 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3527 // For an array, add the element offset, explicitly scaled. 3528 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3529 // Getelementptr indices are signed. 3530 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3531 3532 // Multiply the index by the element size to compute the element offset. 3533 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3534 3535 // Add the element offset to the running total offset. 3536 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3537 } 3538 } 3539 3540 // Add the total offset from all the GEP indices to the base. 3541 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3542 } 3543 3544 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3545 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3546 ArrayRef<const SCEV *> Ops) { 3547 FoldingSetNodeID ID; 3548 void *IP = nullptr; 3549 ID.AddInteger(SCEVType); 3550 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3551 ID.AddPointer(Ops[i]); 3552 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3553 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3554 } 3555 3556 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3557 SmallVectorImpl<const SCEV *> &Ops) { 3558 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3559 if (Ops.size() == 1) return Ops[0]; 3560 #ifndef NDEBUG 3561 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3562 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3563 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3564 "Operand types don't match!"); 3565 #endif 3566 3567 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3568 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3569 3570 // Sort by complexity, this groups all similar expression types together. 3571 GroupByComplexity(Ops, &LI, DT); 3572 3573 // Check if we have created the same expression before. 3574 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3575 return S; 3576 } 3577 3578 // If there are any constants, fold them together. 3579 unsigned Idx = 0; 3580 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3581 ++Idx; 3582 assert(Idx < Ops.size()); 3583 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3584 if (Kind == scSMaxExpr) 3585 return APIntOps::smax(LHS, RHS); 3586 else if (Kind == scSMinExpr) 3587 return APIntOps::smin(LHS, RHS); 3588 else if (Kind == scUMaxExpr) 3589 return APIntOps::umax(LHS, RHS); 3590 else if (Kind == scUMinExpr) 3591 return APIntOps::umin(LHS, RHS); 3592 llvm_unreachable("Unknown SCEV min/max opcode"); 3593 }; 3594 3595 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3596 // We found two constants, fold them together! 3597 ConstantInt *Fold = ConstantInt::get( 3598 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3599 Ops[0] = getConstant(Fold); 3600 Ops.erase(Ops.begin()+1); // Erase the folded element 3601 if (Ops.size() == 1) return Ops[0]; 3602 LHSC = cast<SCEVConstant>(Ops[0]); 3603 } 3604 3605 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3606 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3607 3608 if (IsMax ? IsMinV : IsMaxV) { 3609 // If we are left with a constant minimum(/maximum)-int, strip it off. 3610 Ops.erase(Ops.begin()); 3611 --Idx; 3612 } else if (IsMax ? IsMaxV : IsMinV) { 3613 // If we have a max(/min) with a constant maximum(/minimum)-int, 3614 // it will always be the extremum. 3615 return LHSC; 3616 } 3617 3618 if (Ops.size() == 1) return Ops[0]; 3619 } 3620 3621 // Find the first operation of the same kind 3622 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3623 ++Idx; 3624 3625 // Check to see if one of the operands is of the same kind. If so, expand its 3626 // operands onto our operand list, and recurse to simplify. 3627 if (Idx < Ops.size()) { 3628 bool DeletedAny = false; 3629 while (Ops[Idx]->getSCEVType() == Kind) { 3630 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3631 Ops.erase(Ops.begin()+Idx); 3632 Ops.append(SMME->op_begin(), SMME->op_end()); 3633 DeletedAny = true; 3634 } 3635 3636 if (DeletedAny) 3637 return getMinMaxExpr(Kind, Ops); 3638 } 3639 3640 // Okay, check to see if the same value occurs in the operand list twice. If 3641 // so, delete one. Since we sorted the list, these values are required to 3642 // be adjacent. 3643 llvm::CmpInst::Predicate GEPred = 3644 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3645 llvm::CmpInst::Predicate LEPred = 3646 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3647 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3648 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3649 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3650 if (Ops[i] == Ops[i + 1] || 3651 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3652 // X op Y op Y --> X op Y 3653 // X op Y --> X, if we know X, Y are ordered appropriately 3654 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3655 --i; 3656 --e; 3657 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3658 Ops[i + 1])) { 3659 // X op Y --> Y, if we know X, Y are ordered appropriately 3660 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3661 --i; 3662 --e; 3663 } 3664 } 3665 3666 if (Ops.size() == 1) return Ops[0]; 3667 3668 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3669 3670 // Okay, it looks like we really DO need an expr. Check to see if we 3671 // already have one, otherwise create a new one. 3672 const SCEV *ExistingSCEV; 3673 FoldingSetNodeID ID; 3674 void *IP; 3675 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3676 if (ExistingSCEV) 3677 return ExistingSCEV; 3678 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3679 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3680 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3681 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3682 3683 UniqueSCEVs.InsertNode(S, IP); 3684 addToLoopUseLists(S); 3685 return S; 3686 } 3687 3688 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3689 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3690 return getSMaxExpr(Ops); 3691 } 3692 3693 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3694 return getMinMaxExpr(scSMaxExpr, Ops); 3695 } 3696 3697 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3698 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3699 return getUMaxExpr(Ops); 3700 } 3701 3702 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3703 return getMinMaxExpr(scUMaxExpr, Ops); 3704 } 3705 3706 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3707 const SCEV *RHS) { 3708 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3709 return getSMinExpr(Ops); 3710 } 3711 3712 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3713 return getMinMaxExpr(scSMinExpr, Ops); 3714 } 3715 3716 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3717 const SCEV *RHS) { 3718 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3719 return getUMinExpr(Ops); 3720 } 3721 3722 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3723 return getMinMaxExpr(scUMinExpr, Ops); 3724 } 3725 3726 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3727 // We can bypass creating a target-independent 3728 // constant expression and then folding it back into a ConstantInt. 3729 // This is just a compile-time optimization. 3730 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3731 } 3732 3733 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3734 StructType *STy, 3735 unsigned FieldNo) { 3736 // We can bypass creating a target-independent 3737 // constant expression and then folding it back into a ConstantInt. 3738 // This is just a compile-time optimization. 3739 return getConstant( 3740 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3741 } 3742 3743 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3744 // Don't attempt to do anything other than create a SCEVUnknown object 3745 // here. createSCEV only calls getUnknown after checking for all other 3746 // interesting possibilities, and any other code that calls getUnknown 3747 // is doing so in order to hide a value from SCEV canonicalization. 3748 3749 FoldingSetNodeID ID; 3750 ID.AddInteger(scUnknown); 3751 ID.AddPointer(V); 3752 void *IP = nullptr; 3753 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3754 assert(cast<SCEVUnknown>(S)->getValue() == V && 3755 "Stale SCEVUnknown in uniquing map!"); 3756 return S; 3757 } 3758 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3759 FirstUnknown); 3760 FirstUnknown = cast<SCEVUnknown>(S); 3761 UniqueSCEVs.InsertNode(S, IP); 3762 return S; 3763 } 3764 3765 //===----------------------------------------------------------------------===// 3766 // Basic SCEV Analysis and PHI Idiom Recognition Code 3767 // 3768 3769 /// Test if values of the given type are analyzable within the SCEV 3770 /// framework. This primarily includes integer types, and it can optionally 3771 /// include pointer types if the ScalarEvolution class has access to 3772 /// target-specific information. 3773 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3774 // Integers and pointers are always SCEVable. 3775 return Ty->isIntOrPtrTy(); 3776 } 3777 3778 /// Return the size in bits of the specified type, for which isSCEVable must 3779 /// return true. 3780 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3781 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3782 if (Ty->isPointerTy()) 3783 return getDataLayout().getIndexTypeSizeInBits(Ty); 3784 return getDataLayout().getTypeSizeInBits(Ty); 3785 } 3786 3787 /// Return a type with the same bitwidth as the given type and which represents 3788 /// how SCEV will treat the given type, for which isSCEVable must return 3789 /// true. For pointer types, this is the pointer index sized integer type. 3790 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3791 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3792 3793 if (Ty->isIntegerTy()) 3794 return Ty; 3795 3796 // The only other support type is pointer. 3797 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3798 return getDataLayout().getIndexType(Ty); 3799 } 3800 3801 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3802 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3803 } 3804 3805 const SCEV *ScalarEvolution::getCouldNotCompute() { 3806 return CouldNotCompute.get(); 3807 } 3808 3809 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3810 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3811 auto *SU = dyn_cast<SCEVUnknown>(S); 3812 return SU && SU->getValue() == nullptr; 3813 }); 3814 3815 return !ContainsNulls; 3816 } 3817 3818 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3819 HasRecMapType::iterator I = HasRecMap.find(S); 3820 if (I != HasRecMap.end()) 3821 return I->second; 3822 3823 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3824 HasRecMap.insert({S, FoundAddRec}); 3825 return FoundAddRec; 3826 } 3827 3828 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3829 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3830 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3831 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3832 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3833 if (!Add) 3834 return {S, nullptr}; 3835 3836 if (Add->getNumOperands() != 2) 3837 return {S, nullptr}; 3838 3839 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3840 if (!ConstOp) 3841 return {S, nullptr}; 3842 3843 return {Add->getOperand(1), ConstOp->getValue()}; 3844 } 3845 3846 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3847 /// by the value and offset from any ValueOffsetPair in the set. 3848 SetVector<ScalarEvolution::ValueOffsetPair> * 3849 ScalarEvolution::getSCEVValues(const SCEV *S) { 3850 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3851 if (SI == ExprValueMap.end()) 3852 return nullptr; 3853 #ifndef NDEBUG 3854 if (VerifySCEVMap) { 3855 // Check there is no dangling Value in the set returned. 3856 for (const auto &VE : SI->second) 3857 assert(ValueExprMap.count(VE.first)); 3858 } 3859 #endif 3860 return &SI->second; 3861 } 3862 3863 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3864 /// cannot be used separately. eraseValueFromMap should be used to remove 3865 /// V from ValueExprMap and ExprValueMap at the same time. 3866 void ScalarEvolution::eraseValueFromMap(Value *V) { 3867 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3868 if (I != ValueExprMap.end()) { 3869 const SCEV *S = I->second; 3870 // Remove {V, 0} from the set of ExprValueMap[S] 3871 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3872 SV->remove({V, nullptr}); 3873 3874 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3875 const SCEV *Stripped; 3876 ConstantInt *Offset; 3877 std::tie(Stripped, Offset) = splitAddExpr(S); 3878 if (Offset != nullptr) { 3879 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3880 SV->remove({V, Offset}); 3881 } 3882 ValueExprMap.erase(V); 3883 } 3884 } 3885 3886 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3887 /// TODO: In reality it is better to check the poison recursively 3888 /// but this is better than nothing. 3889 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3890 if (auto *I = dyn_cast<Instruction>(V)) { 3891 if (isa<OverflowingBinaryOperator>(I)) { 3892 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3893 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3894 return true; 3895 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3896 return true; 3897 } 3898 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3899 return true; 3900 } 3901 return false; 3902 } 3903 3904 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3905 /// create a new one. 3906 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3907 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3908 3909 const SCEV *S = getExistingSCEV(V); 3910 if (S == nullptr) { 3911 S = createSCEV(V); 3912 // During PHI resolution, it is possible to create two SCEVs for the same 3913 // V, so it is needed to double check whether V->S is inserted into 3914 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3915 std::pair<ValueExprMapType::iterator, bool> Pair = 3916 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3917 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3918 ExprValueMap[S].insert({V, nullptr}); 3919 3920 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3921 // ExprValueMap. 3922 const SCEV *Stripped = S; 3923 ConstantInt *Offset = nullptr; 3924 std::tie(Stripped, Offset) = splitAddExpr(S); 3925 // If stripped is SCEVUnknown, don't bother to save 3926 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3927 // increase the complexity of the expansion code. 3928 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3929 // because it may generate add/sub instead of GEP in SCEV expansion. 3930 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3931 !isa<GetElementPtrInst>(V)) 3932 ExprValueMap[Stripped].insert({V, Offset}); 3933 } 3934 } 3935 return S; 3936 } 3937 3938 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3939 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3940 3941 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3942 if (I != ValueExprMap.end()) { 3943 const SCEV *S = I->second; 3944 if (checkValidity(S)) 3945 return S; 3946 eraseValueFromMap(V); 3947 forgetMemoizedResults(S); 3948 } 3949 return nullptr; 3950 } 3951 3952 /// Return a SCEV corresponding to -V = -1*V 3953 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3954 SCEV::NoWrapFlags Flags) { 3955 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3956 return getConstant( 3957 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3958 3959 Type *Ty = V->getType(); 3960 Ty = getEffectiveSCEVType(Ty); 3961 return getMulExpr( 3962 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3963 } 3964 3965 /// If Expr computes ~A, return A else return nullptr 3966 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3967 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3968 if (!Add || Add->getNumOperands() != 2 || 3969 !Add->getOperand(0)->isAllOnesValue()) 3970 return nullptr; 3971 3972 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3973 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3974 !AddRHS->getOperand(0)->isAllOnesValue()) 3975 return nullptr; 3976 3977 return AddRHS->getOperand(1); 3978 } 3979 3980 /// Return a SCEV corresponding to ~V = -1-V 3981 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3982 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3983 return getConstant( 3984 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3985 3986 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3987 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3988 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3989 SmallVector<const SCEV *, 2> MatchedOperands; 3990 for (const SCEV *Operand : MME->operands()) { 3991 const SCEV *Matched = MatchNotExpr(Operand); 3992 if (!Matched) 3993 return (const SCEV *)nullptr; 3994 MatchedOperands.push_back(Matched); 3995 } 3996 return getMinMaxExpr( 3997 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3998 MatchedOperands); 3999 }; 4000 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4001 return Replaced; 4002 } 4003 4004 Type *Ty = V->getType(); 4005 Ty = getEffectiveSCEVType(Ty); 4006 const SCEV *AllOnes = 4007 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4008 return getMinusSCEV(AllOnes, V); 4009 } 4010 4011 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4012 SCEV::NoWrapFlags Flags, 4013 unsigned Depth) { 4014 // Fast path: X - X --> 0. 4015 if (LHS == RHS) 4016 return getZero(LHS->getType()); 4017 4018 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4019 // makes it so that we cannot make much use of NUW. 4020 auto AddFlags = SCEV::FlagAnyWrap; 4021 const bool RHSIsNotMinSigned = 4022 !getSignedRangeMin(RHS).isMinSignedValue(); 4023 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4024 // Let M be the minimum representable signed value. Then (-1)*RHS 4025 // signed-wraps if and only if RHS is M. That can happen even for 4026 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4027 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4028 // (-1)*RHS, we need to prove that RHS != M. 4029 // 4030 // If LHS is non-negative and we know that LHS - RHS does not 4031 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4032 // either by proving that RHS > M or that LHS >= 0. 4033 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4034 AddFlags = SCEV::FlagNSW; 4035 } 4036 } 4037 4038 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4039 // RHS is NSW and LHS >= 0. 4040 // 4041 // The difficulty here is that the NSW flag may have been proven 4042 // relative to a loop that is to be found in a recurrence in LHS and 4043 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4044 // larger scope than intended. 4045 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4046 4047 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4048 } 4049 4050 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4051 unsigned Depth) { 4052 Type *SrcTy = V->getType(); 4053 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4054 "Cannot truncate or zero extend with non-integer arguments!"); 4055 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4056 return V; // No conversion 4057 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4058 return getTruncateExpr(V, Ty, Depth); 4059 return getZeroExtendExpr(V, Ty, Depth); 4060 } 4061 4062 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4063 unsigned Depth) { 4064 Type *SrcTy = V->getType(); 4065 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4066 "Cannot truncate or zero extend with non-integer arguments!"); 4067 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4068 return V; // No conversion 4069 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4070 return getTruncateExpr(V, Ty, Depth); 4071 return getSignExtendExpr(V, Ty, Depth); 4072 } 4073 4074 const SCEV * 4075 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4076 Type *SrcTy = V->getType(); 4077 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4078 "Cannot noop or zero extend with non-integer arguments!"); 4079 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4080 "getNoopOrZeroExtend cannot truncate!"); 4081 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4082 return V; // No conversion 4083 return getZeroExtendExpr(V, Ty); 4084 } 4085 4086 const SCEV * 4087 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4088 Type *SrcTy = V->getType(); 4089 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4090 "Cannot noop or sign extend with non-integer arguments!"); 4091 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4092 "getNoopOrSignExtend cannot truncate!"); 4093 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4094 return V; // No conversion 4095 return getSignExtendExpr(V, Ty); 4096 } 4097 4098 const SCEV * 4099 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4100 Type *SrcTy = V->getType(); 4101 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4102 "Cannot noop or any extend with non-integer arguments!"); 4103 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4104 "getNoopOrAnyExtend cannot truncate!"); 4105 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4106 return V; // No conversion 4107 return getAnyExtendExpr(V, Ty); 4108 } 4109 4110 const SCEV * 4111 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4112 Type *SrcTy = V->getType(); 4113 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4114 "Cannot truncate or noop with non-integer arguments!"); 4115 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4116 "getTruncateOrNoop cannot extend!"); 4117 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4118 return V; // No conversion 4119 return getTruncateExpr(V, Ty); 4120 } 4121 4122 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4123 const SCEV *RHS) { 4124 const SCEV *PromotedLHS = LHS; 4125 const SCEV *PromotedRHS = RHS; 4126 4127 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4128 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4129 else 4130 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4131 4132 return getUMaxExpr(PromotedLHS, PromotedRHS); 4133 } 4134 4135 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4136 const SCEV *RHS) { 4137 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4138 return getUMinFromMismatchedTypes(Ops); 4139 } 4140 4141 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4142 SmallVectorImpl<const SCEV *> &Ops) { 4143 assert(!Ops.empty() && "At least one operand must be!"); 4144 // Trivial case. 4145 if (Ops.size() == 1) 4146 return Ops[0]; 4147 4148 // Find the max type first. 4149 Type *MaxType = nullptr; 4150 for (auto *S : Ops) 4151 if (MaxType) 4152 MaxType = getWiderType(MaxType, S->getType()); 4153 else 4154 MaxType = S->getType(); 4155 4156 // Extend all ops to max type. 4157 SmallVector<const SCEV *, 2> PromotedOps; 4158 for (auto *S : Ops) 4159 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4160 4161 // Generate umin. 4162 return getUMinExpr(PromotedOps); 4163 } 4164 4165 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4166 // A pointer operand may evaluate to a nonpointer expression, such as null. 4167 if (!V->getType()->isPointerTy()) 4168 return V; 4169 4170 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4171 return getPointerBase(Cast->getOperand()); 4172 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4173 const SCEV *PtrOp = nullptr; 4174 for (const SCEV *NAryOp : NAry->operands()) { 4175 if (NAryOp->getType()->isPointerTy()) { 4176 // Cannot find the base of an expression with multiple pointer operands. 4177 if (PtrOp) 4178 return V; 4179 PtrOp = NAryOp; 4180 } 4181 } 4182 if (!PtrOp) 4183 return V; 4184 return getPointerBase(PtrOp); 4185 } 4186 return V; 4187 } 4188 4189 /// Push users of the given Instruction onto the given Worklist. 4190 static void 4191 PushDefUseChildren(Instruction *I, 4192 SmallVectorImpl<Instruction *> &Worklist) { 4193 // Push the def-use children onto the Worklist stack. 4194 for (User *U : I->users()) 4195 Worklist.push_back(cast<Instruction>(U)); 4196 } 4197 4198 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4199 SmallVector<Instruction *, 16> Worklist; 4200 PushDefUseChildren(PN, Worklist); 4201 4202 SmallPtrSet<Instruction *, 8> Visited; 4203 Visited.insert(PN); 4204 while (!Worklist.empty()) { 4205 Instruction *I = Worklist.pop_back_val(); 4206 if (!Visited.insert(I).second) 4207 continue; 4208 4209 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4210 if (It != ValueExprMap.end()) { 4211 const SCEV *Old = It->second; 4212 4213 // Short-circuit the def-use traversal if the symbolic name 4214 // ceases to appear in expressions. 4215 if (Old != SymName && !hasOperand(Old, SymName)) 4216 continue; 4217 4218 // SCEVUnknown for a PHI either means that it has an unrecognized 4219 // structure, it's a PHI that's in the progress of being computed 4220 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4221 // additional loop trip count information isn't going to change anything. 4222 // In the second case, createNodeForPHI will perform the necessary 4223 // updates on its own when it gets to that point. In the third, we do 4224 // want to forget the SCEVUnknown. 4225 if (!isa<PHINode>(I) || 4226 !isa<SCEVUnknown>(Old) || 4227 (I != PN && Old == SymName)) { 4228 eraseValueFromMap(It->first); 4229 forgetMemoizedResults(Old); 4230 } 4231 } 4232 4233 PushDefUseChildren(I, Worklist); 4234 } 4235 } 4236 4237 namespace { 4238 4239 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4240 /// expression in case its Loop is L. If it is not L then 4241 /// if IgnoreOtherLoops is true then use AddRec itself 4242 /// otherwise rewrite cannot be done. 4243 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4244 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4245 public: 4246 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4247 bool IgnoreOtherLoops = true) { 4248 SCEVInitRewriter Rewriter(L, SE); 4249 const SCEV *Result = Rewriter.visit(S); 4250 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4251 return SE.getCouldNotCompute(); 4252 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4253 ? SE.getCouldNotCompute() 4254 : Result; 4255 } 4256 4257 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4258 if (!SE.isLoopInvariant(Expr, L)) 4259 SeenLoopVariantSCEVUnknown = true; 4260 return Expr; 4261 } 4262 4263 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4264 // Only re-write AddRecExprs for this loop. 4265 if (Expr->getLoop() == L) 4266 return Expr->getStart(); 4267 SeenOtherLoops = true; 4268 return Expr; 4269 } 4270 4271 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4272 4273 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4274 4275 private: 4276 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4277 : SCEVRewriteVisitor(SE), L(L) {} 4278 4279 const Loop *L; 4280 bool SeenLoopVariantSCEVUnknown = false; 4281 bool SeenOtherLoops = false; 4282 }; 4283 4284 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4285 /// increment expression in case its Loop is L. If it is not L then 4286 /// use AddRec itself. 4287 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4288 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4289 public: 4290 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4291 SCEVPostIncRewriter Rewriter(L, SE); 4292 const SCEV *Result = Rewriter.visit(S); 4293 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4294 ? SE.getCouldNotCompute() 4295 : Result; 4296 } 4297 4298 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4299 if (!SE.isLoopInvariant(Expr, L)) 4300 SeenLoopVariantSCEVUnknown = true; 4301 return Expr; 4302 } 4303 4304 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4305 // Only re-write AddRecExprs for this loop. 4306 if (Expr->getLoop() == L) 4307 return Expr->getPostIncExpr(SE); 4308 SeenOtherLoops = true; 4309 return Expr; 4310 } 4311 4312 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4313 4314 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4315 4316 private: 4317 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4318 : SCEVRewriteVisitor(SE), L(L) {} 4319 4320 const Loop *L; 4321 bool SeenLoopVariantSCEVUnknown = false; 4322 bool SeenOtherLoops = false; 4323 }; 4324 4325 /// This class evaluates the compare condition by matching it against the 4326 /// condition of loop latch. If there is a match we assume a true value 4327 /// for the condition while building SCEV nodes. 4328 class SCEVBackedgeConditionFolder 4329 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4330 public: 4331 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4332 ScalarEvolution &SE) { 4333 bool IsPosBECond = false; 4334 Value *BECond = nullptr; 4335 if (BasicBlock *Latch = L->getLoopLatch()) { 4336 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4337 if (BI && BI->isConditional()) { 4338 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4339 "Both outgoing branches should not target same header!"); 4340 BECond = BI->getCondition(); 4341 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4342 } else { 4343 return S; 4344 } 4345 } 4346 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4347 return Rewriter.visit(S); 4348 } 4349 4350 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4351 const SCEV *Result = Expr; 4352 bool InvariantF = SE.isLoopInvariant(Expr, L); 4353 4354 if (!InvariantF) { 4355 Instruction *I = cast<Instruction>(Expr->getValue()); 4356 switch (I->getOpcode()) { 4357 case Instruction::Select: { 4358 SelectInst *SI = cast<SelectInst>(I); 4359 Optional<const SCEV *> Res = 4360 compareWithBackedgeCondition(SI->getCondition()); 4361 if (Res.hasValue()) { 4362 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4363 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4364 } 4365 break; 4366 } 4367 default: { 4368 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4369 if (Res.hasValue()) 4370 Result = Res.getValue(); 4371 break; 4372 } 4373 } 4374 } 4375 return Result; 4376 } 4377 4378 private: 4379 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4380 bool IsPosBECond, ScalarEvolution &SE) 4381 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4382 IsPositiveBECond(IsPosBECond) {} 4383 4384 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4385 4386 const Loop *L; 4387 /// Loop back condition. 4388 Value *BackedgeCond = nullptr; 4389 /// Set to true if loop back is on positive branch condition. 4390 bool IsPositiveBECond; 4391 }; 4392 4393 Optional<const SCEV *> 4394 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4395 4396 // If value matches the backedge condition for loop latch, 4397 // then return a constant evolution node based on loopback 4398 // branch taken. 4399 if (BackedgeCond == IC) 4400 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4401 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4402 return None; 4403 } 4404 4405 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4406 public: 4407 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4408 ScalarEvolution &SE) { 4409 SCEVShiftRewriter Rewriter(L, SE); 4410 const SCEV *Result = Rewriter.visit(S); 4411 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4412 } 4413 4414 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4415 // Only allow AddRecExprs for this loop. 4416 if (!SE.isLoopInvariant(Expr, L)) 4417 Valid = false; 4418 return Expr; 4419 } 4420 4421 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4422 if (Expr->getLoop() == L && Expr->isAffine()) 4423 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4424 Valid = false; 4425 return Expr; 4426 } 4427 4428 bool isValid() { return Valid; } 4429 4430 private: 4431 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4432 : SCEVRewriteVisitor(SE), L(L) {} 4433 4434 const Loop *L; 4435 bool Valid = true; 4436 }; 4437 4438 } // end anonymous namespace 4439 4440 SCEV::NoWrapFlags 4441 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4442 if (!AR->isAffine()) 4443 return SCEV::FlagAnyWrap; 4444 4445 using OBO = OverflowingBinaryOperator; 4446 4447 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4448 4449 if (!AR->hasNoSignedWrap()) { 4450 ConstantRange AddRecRange = getSignedRange(AR); 4451 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4452 4453 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4454 Instruction::Add, IncRange, OBO::NoSignedWrap); 4455 if (NSWRegion.contains(AddRecRange)) 4456 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4457 } 4458 4459 if (!AR->hasNoUnsignedWrap()) { 4460 ConstantRange AddRecRange = getUnsignedRange(AR); 4461 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4462 4463 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4464 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4465 if (NUWRegion.contains(AddRecRange)) 4466 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4467 } 4468 4469 return Result; 4470 } 4471 4472 namespace { 4473 4474 /// Represents an abstract binary operation. This may exist as a 4475 /// normal instruction or constant expression, or may have been 4476 /// derived from an expression tree. 4477 struct BinaryOp { 4478 unsigned Opcode; 4479 Value *LHS; 4480 Value *RHS; 4481 bool IsNSW = false; 4482 bool IsNUW = false; 4483 4484 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4485 /// constant expression. 4486 Operator *Op = nullptr; 4487 4488 explicit BinaryOp(Operator *Op) 4489 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4490 Op(Op) { 4491 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4492 IsNSW = OBO->hasNoSignedWrap(); 4493 IsNUW = OBO->hasNoUnsignedWrap(); 4494 } 4495 } 4496 4497 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4498 bool IsNUW = false) 4499 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4500 }; 4501 4502 } // end anonymous namespace 4503 4504 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4505 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4506 auto *Op = dyn_cast<Operator>(V); 4507 if (!Op) 4508 return None; 4509 4510 // Implementation detail: all the cleverness here should happen without 4511 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4512 // SCEV expressions when possible, and we should not break that. 4513 4514 switch (Op->getOpcode()) { 4515 case Instruction::Add: 4516 case Instruction::Sub: 4517 case Instruction::Mul: 4518 case Instruction::UDiv: 4519 case Instruction::URem: 4520 case Instruction::And: 4521 case Instruction::Or: 4522 case Instruction::AShr: 4523 case Instruction::Shl: 4524 return BinaryOp(Op); 4525 4526 case Instruction::Xor: 4527 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4528 // If the RHS of the xor is a signmask, then this is just an add. 4529 // Instcombine turns add of signmask into xor as a strength reduction step. 4530 if (RHSC->getValue().isSignMask()) 4531 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4532 return BinaryOp(Op); 4533 4534 case Instruction::LShr: 4535 // Turn logical shift right of a constant into a unsigned divide. 4536 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4537 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4538 4539 // If the shift count is not less than the bitwidth, the result of 4540 // the shift is undefined. Don't try to analyze it, because the 4541 // resolution chosen here may differ from the resolution chosen in 4542 // other parts of the compiler. 4543 if (SA->getValue().ult(BitWidth)) { 4544 Constant *X = 4545 ConstantInt::get(SA->getContext(), 4546 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4547 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4548 } 4549 } 4550 return BinaryOp(Op); 4551 4552 case Instruction::ExtractValue: { 4553 auto *EVI = cast<ExtractValueInst>(Op); 4554 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4555 break; 4556 4557 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4558 if (!WO) 4559 break; 4560 4561 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4562 bool Signed = WO->isSigned(); 4563 // TODO: Should add nuw/nsw flags for mul as well. 4564 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4565 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4566 4567 // Now that we know that all uses of the arithmetic-result component of 4568 // CI are guarded by the overflow check, we can go ahead and pretend 4569 // that the arithmetic is non-overflowing. 4570 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4571 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4572 } 4573 4574 default: 4575 break; 4576 } 4577 4578 return None; 4579 } 4580 4581 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4582 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4583 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4584 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4585 /// follows one of the following patterns: 4586 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4587 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4588 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4589 /// we return the type of the truncation operation, and indicate whether the 4590 /// truncated type should be treated as signed/unsigned by setting 4591 /// \p Signed to true/false, respectively. 4592 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4593 bool &Signed, ScalarEvolution &SE) { 4594 // The case where Op == SymbolicPHI (that is, with no type conversions on 4595 // the way) is handled by the regular add recurrence creating logic and 4596 // would have already been triggered in createAddRecForPHI. Reaching it here 4597 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4598 // because one of the other operands of the SCEVAddExpr updating this PHI is 4599 // not invariant). 4600 // 4601 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4602 // this case predicates that allow us to prove that Op == SymbolicPHI will 4603 // be added. 4604 if (Op == SymbolicPHI) 4605 return nullptr; 4606 4607 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4608 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4609 if (SourceBits != NewBits) 4610 return nullptr; 4611 4612 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4613 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4614 if (!SExt && !ZExt) 4615 return nullptr; 4616 const SCEVTruncateExpr *Trunc = 4617 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4618 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4619 if (!Trunc) 4620 return nullptr; 4621 const SCEV *X = Trunc->getOperand(); 4622 if (X != SymbolicPHI) 4623 return nullptr; 4624 Signed = SExt != nullptr; 4625 return Trunc->getType(); 4626 } 4627 4628 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4629 if (!PN->getType()->isIntegerTy()) 4630 return nullptr; 4631 const Loop *L = LI.getLoopFor(PN->getParent()); 4632 if (!L || L->getHeader() != PN->getParent()) 4633 return nullptr; 4634 return L; 4635 } 4636 4637 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4638 // computation that updates the phi follows the following pattern: 4639 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4640 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4641 // If so, try to see if it can be rewritten as an AddRecExpr under some 4642 // Predicates. If successful, return them as a pair. Also cache the results 4643 // of the analysis. 4644 // 4645 // Example usage scenario: 4646 // Say the Rewriter is called for the following SCEV: 4647 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4648 // where: 4649 // %X = phi i64 (%Start, %BEValue) 4650 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4651 // and call this function with %SymbolicPHI = %X. 4652 // 4653 // The analysis will find that the value coming around the backedge has 4654 // the following SCEV: 4655 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4656 // Upon concluding that this matches the desired pattern, the function 4657 // will return the pair {NewAddRec, SmallPredsVec} where: 4658 // NewAddRec = {%Start,+,%Step} 4659 // SmallPredsVec = {P1, P2, P3} as follows: 4660 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4661 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4662 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4663 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4664 // under the predicates {P1,P2,P3}. 4665 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4666 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4667 // 4668 // TODO's: 4669 // 4670 // 1) Extend the Induction descriptor to also support inductions that involve 4671 // casts: When needed (namely, when we are called in the context of the 4672 // vectorizer induction analysis), a Set of cast instructions will be 4673 // populated by this method, and provided back to isInductionPHI. This is 4674 // needed to allow the vectorizer to properly record them to be ignored by 4675 // the cost model and to avoid vectorizing them (otherwise these casts, 4676 // which are redundant under the runtime overflow checks, will be 4677 // vectorized, which can be costly). 4678 // 4679 // 2) Support additional induction/PHISCEV patterns: We also want to support 4680 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4681 // after the induction update operation (the induction increment): 4682 // 4683 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4684 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4685 // 4686 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4687 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4688 // 4689 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4690 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4691 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4692 SmallVector<const SCEVPredicate *, 3> Predicates; 4693 4694 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4695 // return an AddRec expression under some predicate. 4696 4697 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4698 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4699 assert(L && "Expecting an integer loop header phi"); 4700 4701 // The loop may have multiple entrances or multiple exits; we can analyze 4702 // this phi as an addrec if it has a unique entry value and a unique 4703 // backedge value. 4704 Value *BEValueV = nullptr, *StartValueV = nullptr; 4705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4706 Value *V = PN->getIncomingValue(i); 4707 if (L->contains(PN->getIncomingBlock(i))) { 4708 if (!BEValueV) { 4709 BEValueV = V; 4710 } else if (BEValueV != V) { 4711 BEValueV = nullptr; 4712 break; 4713 } 4714 } else if (!StartValueV) { 4715 StartValueV = V; 4716 } else if (StartValueV != V) { 4717 StartValueV = nullptr; 4718 break; 4719 } 4720 } 4721 if (!BEValueV || !StartValueV) 4722 return None; 4723 4724 const SCEV *BEValue = getSCEV(BEValueV); 4725 4726 // If the value coming around the backedge is an add with the symbolic 4727 // value we just inserted, possibly with casts that we can ignore under 4728 // an appropriate runtime guard, then we found a simple induction variable! 4729 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4730 if (!Add) 4731 return None; 4732 4733 // If there is a single occurrence of the symbolic value, possibly 4734 // casted, replace it with a recurrence. 4735 unsigned FoundIndex = Add->getNumOperands(); 4736 Type *TruncTy = nullptr; 4737 bool Signed; 4738 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4739 if ((TruncTy = 4740 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4741 if (FoundIndex == e) { 4742 FoundIndex = i; 4743 break; 4744 } 4745 4746 if (FoundIndex == Add->getNumOperands()) 4747 return None; 4748 4749 // Create an add with everything but the specified operand. 4750 SmallVector<const SCEV *, 8> Ops; 4751 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4752 if (i != FoundIndex) 4753 Ops.push_back(Add->getOperand(i)); 4754 const SCEV *Accum = getAddExpr(Ops); 4755 4756 // The runtime checks will not be valid if the step amount is 4757 // varying inside the loop. 4758 if (!isLoopInvariant(Accum, L)) 4759 return None; 4760 4761 // *** Part2: Create the predicates 4762 4763 // Analysis was successful: we have a phi-with-cast pattern for which we 4764 // can return an AddRec expression under the following predicates: 4765 // 4766 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4767 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4768 // P2: An Equal predicate that guarantees that 4769 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4770 // P3: An Equal predicate that guarantees that 4771 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4772 // 4773 // As we next prove, the above predicates guarantee that: 4774 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4775 // 4776 // 4777 // More formally, we want to prove that: 4778 // Expr(i+1) = Start + (i+1) * Accum 4779 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4780 // 4781 // Given that: 4782 // 1) Expr(0) = Start 4783 // 2) Expr(1) = Start + Accum 4784 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4785 // 3) Induction hypothesis (step i): 4786 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4787 // 4788 // Proof: 4789 // Expr(i+1) = 4790 // = Start + (i+1)*Accum 4791 // = (Start + i*Accum) + Accum 4792 // = Expr(i) + Accum 4793 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4794 // :: from step i 4795 // 4796 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4797 // 4798 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4799 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4800 // + Accum :: from P3 4801 // 4802 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4803 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4804 // 4805 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4806 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4807 // 4808 // By induction, the same applies to all iterations 1<=i<n: 4809 // 4810 4811 // Create a truncated addrec for which we will add a no overflow check (P1). 4812 const SCEV *StartVal = getSCEV(StartValueV); 4813 const SCEV *PHISCEV = 4814 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4815 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4816 4817 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4818 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4819 // will be constant. 4820 // 4821 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4822 // add P1. 4823 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4824 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4825 Signed ? SCEVWrapPredicate::IncrementNSSW 4826 : SCEVWrapPredicate::IncrementNUSW; 4827 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4828 Predicates.push_back(AddRecPred); 4829 } 4830 4831 // Create the Equal Predicates P2,P3: 4832 4833 // It is possible that the predicates P2 and/or P3 are computable at 4834 // compile time due to StartVal and/or Accum being constants. 4835 // If either one is, then we can check that now and escape if either P2 4836 // or P3 is false. 4837 4838 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4839 // for each of StartVal and Accum 4840 auto getExtendedExpr = [&](const SCEV *Expr, 4841 bool CreateSignExtend) -> const SCEV * { 4842 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4843 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4844 const SCEV *ExtendedExpr = 4845 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4846 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4847 return ExtendedExpr; 4848 }; 4849 4850 // Given: 4851 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4852 // = getExtendedExpr(Expr) 4853 // Determine whether the predicate P: Expr == ExtendedExpr 4854 // is known to be false at compile time 4855 auto PredIsKnownFalse = [&](const SCEV *Expr, 4856 const SCEV *ExtendedExpr) -> bool { 4857 return Expr != ExtendedExpr && 4858 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4859 }; 4860 4861 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4862 if (PredIsKnownFalse(StartVal, StartExtended)) { 4863 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4864 return None; 4865 } 4866 4867 // The Step is always Signed (because the overflow checks are either 4868 // NSSW or NUSW) 4869 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4870 if (PredIsKnownFalse(Accum, AccumExtended)) { 4871 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4872 return None; 4873 } 4874 4875 auto AppendPredicate = [&](const SCEV *Expr, 4876 const SCEV *ExtendedExpr) -> void { 4877 if (Expr != ExtendedExpr && 4878 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4879 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4880 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4881 Predicates.push_back(Pred); 4882 } 4883 }; 4884 4885 AppendPredicate(StartVal, StartExtended); 4886 AppendPredicate(Accum, AccumExtended); 4887 4888 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4889 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4890 // into NewAR if it will also add the runtime overflow checks specified in 4891 // Predicates. 4892 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4893 4894 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4895 std::make_pair(NewAR, Predicates); 4896 // Remember the result of the analysis for this SCEV at this locayyytion. 4897 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4898 return PredRewrite; 4899 } 4900 4901 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4902 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4903 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4904 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4905 if (!L) 4906 return None; 4907 4908 // Check to see if we already analyzed this PHI. 4909 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4910 if (I != PredicatedSCEVRewrites.end()) { 4911 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4912 I->second; 4913 // Analysis was done before and failed to create an AddRec: 4914 if (Rewrite.first == SymbolicPHI) 4915 return None; 4916 // Analysis was done before and succeeded to create an AddRec under 4917 // a predicate: 4918 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4919 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4920 return Rewrite; 4921 } 4922 4923 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4924 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4925 4926 // Record in the cache that the analysis failed 4927 if (!Rewrite) { 4928 SmallVector<const SCEVPredicate *, 3> Predicates; 4929 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4930 return None; 4931 } 4932 4933 return Rewrite; 4934 } 4935 4936 // FIXME: This utility is currently required because the Rewriter currently 4937 // does not rewrite this expression: 4938 // {0, +, (sext ix (trunc iy to ix) to iy)} 4939 // into {0, +, %step}, 4940 // even when the following Equal predicate exists: 4941 // "%step == (sext ix (trunc iy to ix) to iy)". 4942 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4943 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4944 if (AR1 == AR2) 4945 return true; 4946 4947 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4948 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4949 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4950 return false; 4951 return true; 4952 }; 4953 4954 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4955 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4956 return false; 4957 return true; 4958 } 4959 4960 /// A helper function for createAddRecFromPHI to handle simple cases. 4961 /// 4962 /// This function tries to find an AddRec expression for the simplest (yet most 4963 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4964 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4965 /// technique for finding the AddRec expression. 4966 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4967 Value *BEValueV, 4968 Value *StartValueV) { 4969 const Loop *L = LI.getLoopFor(PN->getParent()); 4970 assert(L && L->getHeader() == PN->getParent()); 4971 assert(BEValueV && StartValueV); 4972 4973 auto BO = MatchBinaryOp(BEValueV, DT); 4974 if (!BO) 4975 return nullptr; 4976 4977 if (BO->Opcode != Instruction::Add) 4978 return nullptr; 4979 4980 const SCEV *Accum = nullptr; 4981 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4982 Accum = getSCEV(BO->RHS); 4983 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4984 Accum = getSCEV(BO->LHS); 4985 4986 if (!Accum) 4987 return nullptr; 4988 4989 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4990 if (BO->IsNUW) 4991 Flags = setFlags(Flags, SCEV::FlagNUW); 4992 if (BO->IsNSW) 4993 Flags = setFlags(Flags, SCEV::FlagNSW); 4994 4995 const SCEV *StartVal = getSCEV(StartValueV); 4996 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4997 4998 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4999 5000 // We can add Flags to the post-inc expression only if we 5001 // know that it is *undefined behavior* for BEValueV to 5002 // overflow. 5003 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5004 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5005 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5006 5007 return PHISCEV; 5008 } 5009 5010 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5011 const Loop *L = LI.getLoopFor(PN->getParent()); 5012 if (!L || L->getHeader() != PN->getParent()) 5013 return nullptr; 5014 5015 // The loop may have multiple entrances or multiple exits; we can analyze 5016 // this phi as an addrec if it has a unique entry value and a unique 5017 // backedge value. 5018 Value *BEValueV = nullptr, *StartValueV = nullptr; 5019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5020 Value *V = PN->getIncomingValue(i); 5021 if (L->contains(PN->getIncomingBlock(i))) { 5022 if (!BEValueV) { 5023 BEValueV = V; 5024 } else if (BEValueV != V) { 5025 BEValueV = nullptr; 5026 break; 5027 } 5028 } else if (!StartValueV) { 5029 StartValueV = V; 5030 } else if (StartValueV != V) { 5031 StartValueV = nullptr; 5032 break; 5033 } 5034 } 5035 if (!BEValueV || !StartValueV) 5036 return nullptr; 5037 5038 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5039 "PHI node already processed?"); 5040 5041 // First, try to find AddRec expression without creating a fictituos symbolic 5042 // value for PN. 5043 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5044 return S; 5045 5046 // Handle PHI node value symbolically. 5047 const SCEV *SymbolicName = getUnknown(PN); 5048 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5049 5050 // Using this symbolic name for the PHI, analyze the value coming around 5051 // the back-edge. 5052 const SCEV *BEValue = getSCEV(BEValueV); 5053 5054 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5055 // has a special value for the first iteration of the loop. 5056 5057 // If the value coming around the backedge is an add with the symbolic 5058 // value we just inserted, then we found a simple induction variable! 5059 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5060 // If there is a single occurrence of the symbolic value, replace it 5061 // with a recurrence. 5062 unsigned FoundIndex = Add->getNumOperands(); 5063 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5064 if (Add->getOperand(i) == SymbolicName) 5065 if (FoundIndex == e) { 5066 FoundIndex = i; 5067 break; 5068 } 5069 5070 if (FoundIndex != Add->getNumOperands()) { 5071 // Create an add with everything but the specified operand. 5072 SmallVector<const SCEV *, 8> Ops; 5073 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5074 if (i != FoundIndex) 5075 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5076 L, *this)); 5077 const SCEV *Accum = getAddExpr(Ops); 5078 5079 // This is not a valid addrec if the step amount is varying each 5080 // loop iteration, but is not itself an addrec in this loop. 5081 if (isLoopInvariant(Accum, L) || 5082 (isa<SCEVAddRecExpr>(Accum) && 5083 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5084 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5085 5086 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5087 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5088 if (BO->IsNUW) 5089 Flags = setFlags(Flags, SCEV::FlagNUW); 5090 if (BO->IsNSW) 5091 Flags = setFlags(Flags, SCEV::FlagNSW); 5092 } 5093 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5094 // If the increment is an inbounds GEP, then we know the address 5095 // space cannot be wrapped around. We cannot make any guarantee 5096 // about signed or unsigned overflow because pointers are 5097 // unsigned but we may have a negative index from the base 5098 // pointer. We can guarantee that no unsigned wrap occurs if the 5099 // indices form a positive value. 5100 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5101 Flags = setFlags(Flags, SCEV::FlagNW); 5102 5103 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5104 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5105 Flags = setFlags(Flags, SCEV::FlagNUW); 5106 } 5107 5108 // We cannot transfer nuw and nsw flags from subtraction 5109 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5110 // for instance. 5111 } 5112 5113 const SCEV *StartVal = getSCEV(StartValueV); 5114 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5115 5116 // Okay, for the entire analysis of this edge we assumed the PHI 5117 // to be symbolic. We now need to go back and purge all of the 5118 // entries for the scalars that use the symbolic expression. 5119 forgetSymbolicName(PN, SymbolicName); 5120 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5121 5122 // We can add Flags to the post-inc expression only if we 5123 // know that it is *undefined behavior* for BEValueV to 5124 // overflow. 5125 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5126 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5127 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5128 5129 return PHISCEV; 5130 } 5131 } 5132 } else { 5133 // Otherwise, this could be a loop like this: 5134 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5135 // In this case, j = {1,+,1} and BEValue is j. 5136 // Because the other in-value of i (0) fits the evolution of BEValue 5137 // i really is an addrec evolution. 5138 // 5139 // We can generalize this saying that i is the shifted value of BEValue 5140 // by one iteration: 5141 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5142 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5143 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5144 if (Shifted != getCouldNotCompute() && 5145 Start != getCouldNotCompute()) { 5146 const SCEV *StartVal = getSCEV(StartValueV); 5147 if (Start == StartVal) { 5148 // Okay, for the entire analysis of this edge we assumed the PHI 5149 // to be symbolic. We now need to go back and purge all of the 5150 // entries for the scalars that use the symbolic expression. 5151 forgetSymbolicName(PN, SymbolicName); 5152 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5153 return Shifted; 5154 } 5155 } 5156 } 5157 5158 // Remove the temporary PHI node SCEV that has been inserted while intending 5159 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5160 // as it will prevent later (possibly simpler) SCEV expressions to be added 5161 // to the ValueExprMap. 5162 eraseValueFromMap(PN); 5163 5164 return nullptr; 5165 } 5166 5167 // Checks if the SCEV S is available at BB. S is considered available at BB 5168 // if S can be materialized at BB without introducing a fault. 5169 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5170 BasicBlock *BB) { 5171 struct CheckAvailable { 5172 bool TraversalDone = false; 5173 bool Available = true; 5174 5175 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5176 BasicBlock *BB = nullptr; 5177 DominatorTree &DT; 5178 5179 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5180 : L(L), BB(BB), DT(DT) {} 5181 5182 bool setUnavailable() { 5183 TraversalDone = true; 5184 Available = false; 5185 return false; 5186 } 5187 5188 bool follow(const SCEV *S) { 5189 switch (S->getSCEVType()) { 5190 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5191 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5192 case scUMinExpr: 5193 case scSMinExpr: 5194 // These expressions are available if their operand(s) is/are. 5195 return true; 5196 5197 case scAddRecExpr: { 5198 // We allow add recurrences that are on the loop BB is in, or some 5199 // outer loop. This guarantees availability because the value of the 5200 // add recurrence at BB is simply the "current" value of the induction 5201 // variable. We can relax this in the future; for instance an add 5202 // recurrence on a sibling dominating loop is also available at BB. 5203 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5204 if (L && (ARLoop == L || ARLoop->contains(L))) 5205 return true; 5206 5207 return setUnavailable(); 5208 } 5209 5210 case scUnknown: { 5211 // For SCEVUnknown, we check for simple dominance. 5212 const auto *SU = cast<SCEVUnknown>(S); 5213 Value *V = SU->getValue(); 5214 5215 if (isa<Argument>(V)) 5216 return false; 5217 5218 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5219 return false; 5220 5221 return setUnavailable(); 5222 } 5223 5224 case scUDivExpr: 5225 case scCouldNotCompute: 5226 // We do not try to smart about these at all. 5227 return setUnavailable(); 5228 } 5229 llvm_unreachable("switch should be fully covered!"); 5230 } 5231 5232 bool isDone() { return TraversalDone; } 5233 }; 5234 5235 CheckAvailable CA(L, BB, DT); 5236 SCEVTraversal<CheckAvailable> ST(CA); 5237 5238 ST.visitAll(S); 5239 return CA.Available; 5240 } 5241 5242 // Try to match a control flow sequence that branches out at BI and merges back 5243 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5244 // match. 5245 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5246 Value *&C, Value *&LHS, Value *&RHS) { 5247 C = BI->getCondition(); 5248 5249 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5250 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5251 5252 if (!LeftEdge.isSingleEdge()) 5253 return false; 5254 5255 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5256 5257 Use &LeftUse = Merge->getOperandUse(0); 5258 Use &RightUse = Merge->getOperandUse(1); 5259 5260 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5261 LHS = LeftUse; 5262 RHS = RightUse; 5263 return true; 5264 } 5265 5266 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5267 LHS = RightUse; 5268 RHS = LeftUse; 5269 return true; 5270 } 5271 5272 return false; 5273 } 5274 5275 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5276 auto IsReachable = 5277 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5278 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5279 const Loop *L = LI.getLoopFor(PN->getParent()); 5280 5281 // We don't want to break LCSSA, even in a SCEV expression tree. 5282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5283 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5284 return nullptr; 5285 5286 // Try to match 5287 // 5288 // br %cond, label %left, label %right 5289 // left: 5290 // br label %merge 5291 // right: 5292 // br label %merge 5293 // merge: 5294 // V = phi [ %x, %left ], [ %y, %right ] 5295 // 5296 // as "select %cond, %x, %y" 5297 5298 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5299 assert(IDom && "At least the entry block should dominate PN"); 5300 5301 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5302 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5303 5304 if (BI && BI->isConditional() && 5305 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5306 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5307 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5308 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5309 } 5310 5311 return nullptr; 5312 } 5313 5314 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5315 if (const SCEV *S = createAddRecFromPHI(PN)) 5316 return S; 5317 5318 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5319 return S; 5320 5321 // If the PHI has a single incoming value, follow that value, unless the 5322 // PHI's incoming blocks are in a different loop, in which case doing so 5323 // risks breaking LCSSA form. Instcombine would normally zap these, but 5324 // it doesn't have DominatorTree information, so it may miss cases. 5325 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5326 if (LI.replacementPreservesLCSSAForm(PN, V)) 5327 return getSCEV(V); 5328 5329 // If it's not a loop phi, we can't handle it yet. 5330 return getUnknown(PN); 5331 } 5332 5333 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5334 Value *Cond, 5335 Value *TrueVal, 5336 Value *FalseVal) { 5337 // Handle "constant" branch or select. This can occur for instance when a 5338 // loop pass transforms an inner loop and moves on to process the outer loop. 5339 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5340 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5341 5342 // Try to match some simple smax or umax patterns. 5343 auto *ICI = dyn_cast<ICmpInst>(Cond); 5344 if (!ICI) 5345 return getUnknown(I); 5346 5347 Value *LHS = ICI->getOperand(0); 5348 Value *RHS = ICI->getOperand(1); 5349 5350 switch (ICI->getPredicate()) { 5351 case ICmpInst::ICMP_SLT: 5352 case ICmpInst::ICMP_SLE: 5353 std::swap(LHS, RHS); 5354 LLVM_FALLTHROUGH; 5355 case ICmpInst::ICMP_SGT: 5356 case ICmpInst::ICMP_SGE: 5357 // a >s b ? a+x : b+x -> smax(a, b)+x 5358 // a >s b ? b+x : a+x -> smin(a, b)+x 5359 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5360 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5361 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5362 const SCEV *LA = getSCEV(TrueVal); 5363 const SCEV *RA = getSCEV(FalseVal); 5364 const SCEV *LDiff = getMinusSCEV(LA, LS); 5365 const SCEV *RDiff = getMinusSCEV(RA, RS); 5366 if (LDiff == RDiff) 5367 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5368 LDiff = getMinusSCEV(LA, RS); 5369 RDiff = getMinusSCEV(RA, LS); 5370 if (LDiff == RDiff) 5371 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5372 } 5373 break; 5374 case ICmpInst::ICMP_ULT: 5375 case ICmpInst::ICMP_ULE: 5376 std::swap(LHS, RHS); 5377 LLVM_FALLTHROUGH; 5378 case ICmpInst::ICMP_UGT: 5379 case ICmpInst::ICMP_UGE: 5380 // a >u b ? a+x : b+x -> umax(a, b)+x 5381 // a >u b ? b+x : a+x -> umin(a, b)+x 5382 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5383 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5384 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5385 const SCEV *LA = getSCEV(TrueVal); 5386 const SCEV *RA = getSCEV(FalseVal); 5387 const SCEV *LDiff = getMinusSCEV(LA, LS); 5388 const SCEV *RDiff = getMinusSCEV(RA, RS); 5389 if (LDiff == RDiff) 5390 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5391 LDiff = getMinusSCEV(LA, RS); 5392 RDiff = getMinusSCEV(RA, LS); 5393 if (LDiff == RDiff) 5394 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5395 } 5396 break; 5397 case ICmpInst::ICMP_NE: 5398 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5399 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5400 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5401 const SCEV *One = getOne(I->getType()); 5402 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5403 const SCEV *LA = getSCEV(TrueVal); 5404 const SCEV *RA = getSCEV(FalseVal); 5405 const SCEV *LDiff = getMinusSCEV(LA, LS); 5406 const SCEV *RDiff = getMinusSCEV(RA, One); 5407 if (LDiff == RDiff) 5408 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5409 } 5410 break; 5411 case ICmpInst::ICMP_EQ: 5412 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5413 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5414 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5415 const SCEV *One = getOne(I->getType()); 5416 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5417 const SCEV *LA = getSCEV(TrueVal); 5418 const SCEV *RA = getSCEV(FalseVal); 5419 const SCEV *LDiff = getMinusSCEV(LA, One); 5420 const SCEV *RDiff = getMinusSCEV(RA, LS); 5421 if (LDiff == RDiff) 5422 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5423 } 5424 break; 5425 default: 5426 break; 5427 } 5428 5429 return getUnknown(I); 5430 } 5431 5432 /// Expand GEP instructions into add and multiply operations. This allows them 5433 /// to be analyzed by regular SCEV code. 5434 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5435 // Don't attempt to analyze GEPs over unsized objects. 5436 if (!GEP->getSourceElementType()->isSized()) 5437 return getUnknown(GEP); 5438 5439 SmallVector<const SCEV *, 4> IndexExprs; 5440 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5441 IndexExprs.push_back(getSCEV(*Index)); 5442 return getGEPExpr(GEP, IndexExprs); 5443 } 5444 5445 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5446 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5447 return C->getAPInt().countTrailingZeros(); 5448 5449 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5450 return std::min(GetMinTrailingZeros(T->getOperand()), 5451 (uint32_t)getTypeSizeInBits(T->getType())); 5452 5453 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5455 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5456 ? getTypeSizeInBits(E->getType()) 5457 : OpRes; 5458 } 5459 5460 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5461 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5462 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5463 ? getTypeSizeInBits(E->getType()) 5464 : OpRes; 5465 } 5466 5467 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5468 // The result is the min of all operands results. 5469 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5470 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5472 return MinOpRes; 5473 } 5474 5475 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5476 // The result is the sum of all operands results. 5477 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5478 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5479 for (unsigned i = 1, e = M->getNumOperands(); 5480 SumOpRes != BitWidth && i != e; ++i) 5481 SumOpRes = 5482 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5483 return SumOpRes; 5484 } 5485 5486 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5487 // The result is the min of all operands results. 5488 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5489 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5491 return MinOpRes; 5492 } 5493 5494 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5495 // The result is the min of all operands results. 5496 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5497 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5499 return MinOpRes; 5500 } 5501 5502 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5503 // The result is the min of all operands results. 5504 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5505 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5506 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5507 return MinOpRes; 5508 } 5509 5510 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5511 // For a SCEVUnknown, ask ValueTracking. 5512 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5513 return Known.countMinTrailingZeros(); 5514 } 5515 5516 // SCEVUDivExpr 5517 return 0; 5518 } 5519 5520 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5521 auto I = MinTrailingZerosCache.find(S); 5522 if (I != MinTrailingZerosCache.end()) 5523 return I->second; 5524 5525 uint32_t Result = GetMinTrailingZerosImpl(S); 5526 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5527 assert(InsertPair.second && "Should insert a new key"); 5528 return InsertPair.first->second; 5529 } 5530 5531 /// Helper method to assign a range to V from metadata present in the IR. 5532 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5533 if (Instruction *I = dyn_cast<Instruction>(V)) 5534 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5535 return getConstantRangeFromMetadata(*MD); 5536 5537 return None; 5538 } 5539 5540 /// Determine the range for a particular SCEV. If SignHint is 5541 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5542 /// with a "cleaner" unsigned (resp. signed) representation. 5543 const ConstantRange & 5544 ScalarEvolution::getRangeRef(const SCEV *S, 5545 ScalarEvolution::RangeSignHint SignHint) { 5546 DenseMap<const SCEV *, ConstantRange> &Cache = 5547 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5548 : SignedRanges; 5549 ConstantRange::PreferredRangeType RangeType = 5550 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5551 ? ConstantRange::Unsigned : ConstantRange::Signed; 5552 5553 // See if we've computed this range already. 5554 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5555 if (I != Cache.end()) 5556 return I->second; 5557 5558 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5559 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5560 5561 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5562 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5563 5564 // If the value has known zeros, the maximum value will have those known zeros 5565 // as well. 5566 uint32_t TZ = GetMinTrailingZeros(S); 5567 if (TZ != 0) { 5568 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5569 ConservativeResult = 5570 ConstantRange(APInt::getMinValue(BitWidth), 5571 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5572 else 5573 ConservativeResult = ConstantRange( 5574 APInt::getSignedMinValue(BitWidth), 5575 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5576 } 5577 5578 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5579 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5580 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5581 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5582 return setRange(Add, SignHint, 5583 ConservativeResult.intersectWith(X, RangeType)); 5584 } 5585 5586 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5587 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5588 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5589 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5590 return setRange(Mul, SignHint, 5591 ConservativeResult.intersectWith(X, RangeType)); 5592 } 5593 5594 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5595 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5596 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5597 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5598 return setRange(SMax, SignHint, 5599 ConservativeResult.intersectWith(X, RangeType)); 5600 } 5601 5602 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5603 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5604 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5605 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5606 return setRange(UMax, SignHint, 5607 ConservativeResult.intersectWith(X, RangeType)); 5608 } 5609 5610 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5611 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5612 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5613 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5614 return setRange(SMin, SignHint, 5615 ConservativeResult.intersectWith(X, RangeType)); 5616 } 5617 5618 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5619 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5620 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5621 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5622 return setRange(UMin, SignHint, 5623 ConservativeResult.intersectWith(X, RangeType)); 5624 } 5625 5626 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5627 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5628 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5629 return setRange(UDiv, SignHint, 5630 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5631 } 5632 5633 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5634 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5635 return setRange(ZExt, SignHint, 5636 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5637 RangeType)); 5638 } 5639 5640 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5641 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5642 return setRange(SExt, SignHint, 5643 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5644 RangeType)); 5645 } 5646 5647 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5648 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5649 return setRange(Trunc, SignHint, 5650 ConservativeResult.intersectWith(X.truncate(BitWidth), 5651 RangeType)); 5652 } 5653 5654 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5655 // If there's no unsigned wrap, the value will never be less than its 5656 // initial value. 5657 if (AddRec->hasNoUnsignedWrap()) 5658 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5659 if (!C->getValue()->isZero()) 5660 ConservativeResult = ConservativeResult.intersectWith( 5661 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5662 5663 // If there's no signed wrap, and all the operands have the same sign or 5664 // zero, the value won't ever change sign. 5665 if (AddRec->hasNoSignedWrap()) { 5666 bool AllNonNeg = true; 5667 bool AllNonPos = true; 5668 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5669 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5670 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5671 } 5672 if (AllNonNeg) 5673 ConservativeResult = ConservativeResult.intersectWith( 5674 ConstantRange(APInt(BitWidth, 0), 5675 APInt::getSignedMinValue(BitWidth)), RangeType); 5676 else if (AllNonPos) 5677 ConservativeResult = ConservativeResult.intersectWith( 5678 ConstantRange(APInt::getSignedMinValue(BitWidth), 5679 APInt(BitWidth, 1)), RangeType); 5680 } 5681 5682 // TODO: non-affine addrec 5683 if (AddRec->isAffine()) { 5684 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5685 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5686 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5687 auto RangeFromAffine = getRangeForAffineAR( 5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5689 BitWidth); 5690 if (!RangeFromAffine.isFullSet()) 5691 ConservativeResult = 5692 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5693 5694 auto RangeFromFactoring = getRangeViaFactoring( 5695 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5696 BitWidth); 5697 if (!RangeFromFactoring.isFullSet()) 5698 ConservativeResult = 5699 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5700 } 5701 } 5702 5703 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5704 } 5705 5706 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5707 // Check if the IR explicitly contains !range metadata. 5708 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5709 if (MDRange.hasValue()) 5710 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5711 RangeType); 5712 5713 // Split here to avoid paying the compile-time cost of calling both 5714 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5715 // if needed. 5716 const DataLayout &DL = getDataLayout(); 5717 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5718 // For a SCEVUnknown, ask ValueTracking. 5719 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5720 if (Known.getBitWidth() != BitWidth) 5721 Known = Known.zextOrTrunc(BitWidth, true); 5722 // If Known does not result in full-set, intersect with it. 5723 if (Known.getMinValue() != Known.getMaxValue() + 1) 5724 ConservativeResult = ConservativeResult.intersectWith( 5725 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5726 RangeType); 5727 } else { 5728 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5729 "generalize as needed!"); 5730 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5731 // If the pointer size is larger than the index size type, this can cause 5732 // NS to be larger than BitWidth. So compensate for this. 5733 if (U->getType()->isPointerTy()) { 5734 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5735 int ptrIdxDiff = ptrSize - BitWidth; 5736 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5737 NS -= ptrIdxDiff; 5738 } 5739 5740 if (NS > 1) 5741 ConservativeResult = ConservativeResult.intersectWith( 5742 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5743 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5744 RangeType); 5745 } 5746 5747 // A range of Phi is a subset of union of all ranges of its input. 5748 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5749 // Make sure that we do not run over cycled Phis. 5750 if (PendingPhiRanges.insert(Phi).second) { 5751 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5752 for (auto &Op : Phi->operands()) { 5753 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5754 RangeFromOps = RangeFromOps.unionWith(OpRange); 5755 // No point to continue if we already have a full set. 5756 if (RangeFromOps.isFullSet()) 5757 break; 5758 } 5759 ConservativeResult = 5760 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5761 bool Erased = PendingPhiRanges.erase(Phi); 5762 assert(Erased && "Failed to erase Phi properly?"); 5763 (void) Erased; 5764 } 5765 } 5766 5767 return setRange(U, SignHint, std::move(ConservativeResult)); 5768 } 5769 5770 return setRange(S, SignHint, std::move(ConservativeResult)); 5771 } 5772 5773 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5774 // values that the expression can take. Initially, the expression has a value 5775 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5776 // argument defines if we treat Step as signed or unsigned. 5777 static ConstantRange getRangeForAffineARHelper(APInt Step, 5778 const ConstantRange &StartRange, 5779 const APInt &MaxBECount, 5780 unsigned BitWidth, bool Signed) { 5781 // If either Step or MaxBECount is 0, then the expression won't change, and we 5782 // just need to return the initial range. 5783 if (Step == 0 || MaxBECount == 0) 5784 return StartRange; 5785 5786 // If we don't know anything about the initial value (i.e. StartRange is 5787 // FullRange), then we don't know anything about the final range either. 5788 // Return FullRange. 5789 if (StartRange.isFullSet()) 5790 return ConstantRange::getFull(BitWidth); 5791 5792 // If Step is signed and negative, then we use its absolute value, but we also 5793 // note that we're moving in the opposite direction. 5794 bool Descending = Signed && Step.isNegative(); 5795 5796 if (Signed) 5797 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5798 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5799 // This equations hold true due to the well-defined wrap-around behavior of 5800 // APInt. 5801 Step = Step.abs(); 5802 5803 // Check if Offset is more than full span of BitWidth. If it is, the 5804 // expression is guaranteed to overflow. 5805 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5806 return ConstantRange::getFull(BitWidth); 5807 5808 // Offset is by how much the expression can change. Checks above guarantee no 5809 // overflow here. 5810 APInt Offset = Step * MaxBECount; 5811 5812 // Minimum value of the final range will match the minimal value of StartRange 5813 // if the expression is increasing and will be decreased by Offset otherwise. 5814 // Maximum value of the final range will match the maximal value of StartRange 5815 // if the expression is decreasing and will be increased by Offset otherwise. 5816 APInt StartLower = StartRange.getLower(); 5817 APInt StartUpper = StartRange.getUpper() - 1; 5818 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5819 : (StartUpper + std::move(Offset)); 5820 5821 // It's possible that the new minimum/maximum value will fall into the initial 5822 // range (due to wrap around). This means that the expression can take any 5823 // value in this bitwidth, and we have to return full range. 5824 if (StartRange.contains(MovedBoundary)) 5825 return ConstantRange::getFull(BitWidth); 5826 5827 APInt NewLower = 5828 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5829 APInt NewUpper = 5830 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5831 NewUpper += 1; 5832 5833 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5834 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5835 } 5836 5837 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5838 const SCEV *Step, 5839 const SCEV *MaxBECount, 5840 unsigned BitWidth) { 5841 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5842 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5843 "Precondition!"); 5844 5845 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5846 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5847 5848 // First, consider step signed. 5849 ConstantRange StartSRange = getSignedRange(Start); 5850 ConstantRange StepSRange = getSignedRange(Step); 5851 5852 // If Step can be both positive and negative, we need to find ranges for the 5853 // maximum absolute step values in both directions and union them. 5854 ConstantRange SR = 5855 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5856 MaxBECountValue, BitWidth, /* Signed = */ true); 5857 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5858 StartSRange, MaxBECountValue, 5859 BitWidth, /* Signed = */ true)); 5860 5861 // Next, consider step unsigned. 5862 ConstantRange UR = getRangeForAffineARHelper( 5863 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5864 MaxBECountValue, BitWidth, /* Signed = */ false); 5865 5866 // Finally, intersect signed and unsigned ranges. 5867 return SR.intersectWith(UR, ConstantRange::Smallest); 5868 } 5869 5870 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5871 const SCEV *Step, 5872 const SCEV *MaxBECount, 5873 unsigned BitWidth) { 5874 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5875 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5876 5877 struct SelectPattern { 5878 Value *Condition = nullptr; 5879 APInt TrueValue; 5880 APInt FalseValue; 5881 5882 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5883 const SCEV *S) { 5884 Optional<unsigned> CastOp; 5885 APInt Offset(BitWidth, 0); 5886 5887 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5888 "Should be!"); 5889 5890 // Peel off a constant offset: 5891 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5892 // In the future we could consider being smarter here and handle 5893 // {Start+Step,+,Step} too. 5894 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5895 return; 5896 5897 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5898 S = SA->getOperand(1); 5899 } 5900 5901 // Peel off a cast operation 5902 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5903 CastOp = SCast->getSCEVType(); 5904 S = SCast->getOperand(); 5905 } 5906 5907 using namespace llvm::PatternMatch; 5908 5909 auto *SU = dyn_cast<SCEVUnknown>(S); 5910 const APInt *TrueVal, *FalseVal; 5911 if (!SU || 5912 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5913 m_APInt(FalseVal)))) { 5914 Condition = nullptr; 5915 return; 5916 } 5917 5918 TrueValue = *TrueVal; 5919 FalseValue = *FalseVal; 5920 5921 // Re-apply the cast we peeled off earlier 5922 if (CastOp.hasValue()) 5923 switch (*CastOp) { 5924 default: 5925 llvm_unreachable("Unknown SCEV cast type!"); 5926 5927 case scTruncate: 5928 TrueValue = TrueValue.trunc(BitWidth); 5929 FalseValue = FalseValue.trunc(BitWidth); 5930 break; 5931 case scZeroExtend: 5932 TrueValue = TrueValue.zext(BitWidth); 5933 FalseValue = FalseValue.zext(BitWidth); 5934 break; 5935 case scSignExtend: 5936 TrueValue = TrueValue.sext(BitWidth); 5937 FalseValue = FalseValue.sext(BitWidth); 5938 break; 5939 } 5940 5941 // Re-apply the constant offset we peeled off earlier 5942 TrueValue += Offset; 5943 FalseValue += Offset; 5944 } 5945 5946 bool isRecognized() { return Condition != nullptr; } 5947 }; 5948 5949 SelectPattern StartPattern(*this, BitWidth, Start); 5950 if (!StartPattern.isRecognized()) 5951 return ConstantRange::getFull(BitWidth); 5952 5953 SelectPattern StepPattern(*this, BitWidth, Step); 5954 if (!StepPattern.isRecognized()) 5955 return ConstantRange::getFull(BitWidth); 5956 5957 if (StartPattern.Condition != StepPattern.Condition) { 5958 // We don't handle this case today; but we could, by considering four 5959 // possibilities below instead of two. I'm not sure if there are cases where 5960 // that will help over what getRange already does, though. 5961 return ConstantRange::getFull(BitWidth); 5962 } 5963 5964 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5965 // construct arbitrary general SCEV expressions here. This function is called 5966 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5967 // say) can end up caching a suboptimal value. 5968 5969 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5970 // C2352 and C2512 (otherwise it isn't needed). 5971 5972 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5973 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5974 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5975 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5976 5977 ConstantRange TrueRange = 5978 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5979 ConstantRange FalseRange = 5980 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5981 5982 return TrueRange.unionWith(FalseRange); 5983 } 5984 5985 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5986 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5987 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5988 5989 // Return early if there are no flags to propagate to the SCEV. 5990 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5991 if (BinOp->hasNoUnsignedWrap()) 5992 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5993 if (BinOp->hasNoSignedWrap()) 5994 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5995 if (Flags == SCEV::FlagAnyWrap) 5996 return SCEV::FlagAnyWrap; 5997 5998 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5999 } 6000 6001 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6002 // Here we check that I is in the header of the innermost loop containing I, 6003 // since we only deal with instructions in the loop header. The actual loop we 6004 // need to check later will come from an add recurrence, but getting that 6005 // requires computing the SCEV of the operands, which can be expensive. This 6006 // check we can do cheaply to rule out some cases early. 6007 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6008 if (InnermostContainingLoop == nullptr || 6009 InnermostContainingLoop->getHeader() != I->getParent()) 6010 return false; 6011 6012 // Only proceed if we can prove that I does not yield poison. 6013 if (!programUndefinedIfFullPoison(I)) 6014 return false; 6015 6016 // At this point we know that if I is executed, then it does not wrap 6017 // according to at least one of NSW or NUW. If I is not executed, then we do 6018 // not know if the calculation that I represents would wrap. Multiple 6019 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6020 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6021 // derived from other instructions that map to the same SCEV. We cannot make 6022 // that guarantee for cases where I is not executed. So we need to find the 6023 // loop that I is considered in relation to and prove that I is executed for 6024 // every iteration of that loop. That implies that the value that I 6025 // calculates does not wrap anywhere in the loop, so then we can apply the 6026 // flags to the SCEV. 6027 // 6028 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6029 // from different loops, so that we know which loop to prove that I is 6030 // executed in. 6031 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6032 // I could be an extractvalue from a call to an overflow intrinsic. 6033 // TODO: We can do better here in some cases. 6034 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6035 return false; 6036 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6037 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6038 bool AllOtherOpsLoopInvariant = true; 6039 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6040 ++OtherOpIndex) { 6041 if (OtherOpIndex != OpIndex) { 6042 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6043 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6044 AllOtherOpsLoopInvariant = false; 6045 break; 6046 } 6047 } 6048 } 6049 if (AllOtherOpsLoopInvariant && 6050 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6051 return true; 6052 } 6053 } 6054 return false; 6055 } 6056 6057 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6058 // If we know that \c I can never be poison period, then that's enough. 6059 if (isSCEVExprNeverPoison(I)) 6060 return true; 6061 6062 // For an add recurrence specifically, we assume that infinite loops without 6063 // side effects are undefined behavior, and then reason as follows: 6064 // 6065 // If the add recurrence is poison in any iteration, it is poison on all 6066 // future iterations (since incrementing poison yields poison). If the result 6067 // of the add recurrence is fed into the loop latch condition and the loop 6068 // does not contain any throws or exiting blocks other than the latch, we now 6069 // have the ability to "choose" whether the backedge is taken or not (by 6070 // choosing a sufficiently evil value for the poison feeding into the branch) 6071 // for every iteration including and after the one in which \p I first became 6072 // poison. There are two possibilities (let's call the iteration in which \p 6073 // I first became poison as K): 6074 // 6075 // 1. In the set of iterations including and after K, the loop body executes 6076 // no side effects. In this case executing the backege an infinte number 6077 // of times will yield undefined behavior. 6078 // 6079 // 2. In the set of iterations including and after K, the loop body executes 6080 // at least one side effect. In this case, that specific instance of side 6081 // effect is control dependent on poison, which also yields undefined 6082 // behavior. 6083 6084 auto *ExitingBB = L->getExitingBlock(); 6085 auto *LatchBB = L->getLoopLatch(); 6086 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6087 return false; 6088 6089 SmallPtrSet<const Instruction *, 16> Pushed; 6090 SmallVector<const Instruction *, 8> PoisonStack; 6091 6092 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6093 // things that are known to be fully poison under that assumption go on the 6094 // PoisonStack. 6095 Pushed.insert(I); 6096 PoisonStack.push_back(I); 6097 6098 bool LatchControlDependentOnPoison = false; 6099 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6100 const Instruction *Poison = PoisonStack.pop_back_val(); 6101 6102 for (auto *PoisonUser : Poison->users()) { 6103 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6104 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6105 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6106 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6107 assert(BI->isConditional() && "Only possibility!"); 6108 if (BI->getParent() == LatchBB) { 6109 LatchControlDependentOnPoison = true; 6110 break; 6111 } 6112 } 6113 } 6114 } 6115 6116 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6117 } 6118 6119 ScalarEvolution::LoopProperties 6120 ScalarEvolution::getLoopProperties(const Loop *L) { 6121 using LoopProperties = ScalarEvolution::LoopProperties; 6122 6123 auto Itr = LoopPropertiesCache.find(L); 6124 if (Itr == LoopPropertiesCache.end()) { 6125 auto HasSideEffects = [](Instruction *I) { 6126 if (auto *SI = dyn_cast<StoreInst>(I)) 6127 return !SI->isSimple(); 6128 6129 return I->mayHaveSideEffects(); 6130 }; 6131 6132 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6133 /*HasNoSideEffects*/ true}; 6134 6135 for (auto *BB : L->getBlocks()) 6136 for (auto &I : *BB) { 6137 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6138 LP.HasNoAbnormalExits = false; 6139 if (HasSideEffects(&I)) 6140 LP.HasNoSideEffects = false; 6141 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6142 break; // We're already as pessimistic as we can get. 6143 } 6144 6145 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6146 assert(InsertPair.second && "We just checked!"); 6147 Itr = InsertPair.first; 6148 } 6149 6150 return Itr->second; 6151 } 6152 6153 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6154 if (!isSCEVable(V->getType())) 6155 return getUnknown(V); 6156 6157 if (Instruction *I = dyn_cast<Instruction>(V)) { 6158 // Don't attempt to analyze instructions in blocks that aren't 6159 // reachable. Such instructions don't matter, and they aren't required 6160 // to obey basic rules for definitions dominating uses which this 6161 // analysis depends on. 6162 if (!DT.isReachableFromEntry(I->getParent())) 6163 return getUnknown(UndefValue::get(V->getType())); 6164 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6165 return getConstant(CI); 6166 else if (isa<ConstantPointerNull>(V)) 6167 return getZero(V->getType()); 6168 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6169 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6170 else if (!isa<ConstantExpr>(V)) 6171 return getUnknown(V); 6172 6173 Operator *U = cast<Operator>(V); 6174 if (auto BO = MatchBinaryOp(U, DT)) { 6175 switch (BO->Opcode) { 6176 case Instruction::Add: { 6177 // The simple thing to do would be to just call getSCEV on both operands 6178 // and call getAddExpr with the result. However if we're looking at a 6179 // bunch of things all added together, this can be quite inefficient, 6180 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6181 // Instead, gather up all the operands and make a single getAddExpr call. 6182 // LLVM IR canonical form means we need only traverse the left operands. 6183 SmallVector<const SCEV *, 4> AddOps; 6184 do { 6185 if (BO->Op) { 6186 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6187 AddOps.push_back(OpSCEV); 6188 break; 6189 } 6190 6191 // If a NUW or NSW flag can be applied to the SCEV for this 6192 // addition, then compute the SCEV for this addition by itself 6193 // with a separate call to getAddExpr. We need to do that 6194 // instead of pushing the operands of the addition onto AddOps, 6195 // since the flags are only known to apply to this particular 6196 // addition - they may not apply to other additions that can be 6197 // formed with operands from AddOps. 6198 const SCEV *RHS = getSCEV(BO->RHS); 6199 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6200 if (Flags != SCEV::FlagAnyWrap) { 6201 const SCEV *LHS = getSCEV(BO->LHS); 6202 if (BO->Opcode == Instruction::Sub) 6203 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6204 else 6205 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6206 break; 6207 } 6208 } 6209 6210 if (BO->Opcode == Instruction::Sub) 6211 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6212 else 6213 AddOps.push_back(getSCEV(BO->RHS)); 6214 6215 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6216 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6217 NewBO->Opcode != Instruction::Sub)) { 6218 AddOps.push_back(getSCEV(BO->LHS)); 6219 break; 6220 } 6221 BO = NewBO; 6222 } while (true); 6223 6224 return getAddExpr(AddOps); 6225 } 6226 6227 case Instruction::Mul: { 6228 SmallVector<const SCEV *, 4> MulOps; 6229 do { 6230 if (BO->Op) { 6231 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6232 MulOps.push_back(OpSCEV); 6233 break; 6234 } 6235 6236 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6237 if (Flags != SCEV::FlagAnyWrap) { 6238 MulOps.push_back( 6239 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6240 break; 6241 } 6242 } 6243 6244 MulOps.push_back(getSCEV(BO->RHS)); 6245 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6246 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6247 MulOps.push_back(getSCEV(BO->LHS)); 6248 break; 6249 } 6250 BO = NewBO; 6251 } while (true); 6252 6253 return getMulExpr(MulOps); 6254 } 6255 case Instruction::UDiv: 6256 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6257 case Instruction::URem: 6258 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6259 case Instruction::Sub: { 6260 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6261 if (BO->Op) 6262 Flags = getNoWrapFlagsFromUB(BO->Op); 6263 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6264 } 6265 case Instruction::And: 6266 // For an expression like x&255 that merely masks off the high bits, 6267 // use zext(trunc(x)) as the SCEV expression. 6268 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6269 if (CI->isZero()) 6270 return getSCEV(BO->RHS); 6271 if (CI->isMinusOne()) 6272 return getSCEV(BO->LHS); 6273 const APInt &A = CI->getValue(); 6274 6275 // Instcombine's ShrinkDemandedConstant may strip bits out of 6276 // constants, obscuring what would otherwise be a low-bits mask. 6277 // Use computeKnownBits to compute what ShrinkDemandedConstant 6278 // knew about to reconstruct a low-bits mask value. 6279 unsigned LZ = A.countLeadingZeros(); 6280 unsigned TZ = A.countTrailingZeros(); 6281 unsigned BitWidth = A.getBitWidth(); 6282 KnownBits Known(BitWidth); 6283 computeKnownBits(BO->LHS, Known, getDataLayout(), 6284 0, &AC, nullptr, &DT); 6285 6286 APInt EffectiveMask = 6287 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6288 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6289 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6290 const SCEV *LHS = getSCEV(BO->LHS); 6291 const SCEV *ShiftedLHS = nullptr; 6292 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6293 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6294 // For an expression like (x * 8) & 8, simplify the multiply. 6295 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6296 unsigned GCD = std::min(MulZeros, TZ); 6297 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6298 SmallVector<const SCEV*, 4> MulOps; 6299 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6300 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6301 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6302 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6303 } 6304 } 6305 if (!ShiftedLHS) 6306 ShiftedLHS = getUDivExpr(LHS, MulCount); 6307 return getMulExpr( 6308 getZeroExtendExpr( 6309 getTruncateExpr(ShiftedLHS, 6310 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6311 BO->LHS->getType()), 6312 MulCount); 6313 } 6314 } 6315 break; 6316 6317 case Instruction::Or: 6318 // If the RHS of the Or is a constant, we may have something like: 6319 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6320 // optimizations will transparently handle this case. 6321 // 6322 // In order for this transformation to be safe, the LHS must be of the 6323 // form X*(2^n) and the Or constant must be less than 2^n. 6324 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6325 const SCEV *LHS = getSCEV(BO->LHS); 6326 const APInt &CIVal = CI->getValue(); 6327 if (GetMinTrailingZeros(LHS) >= 6328 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6329 // Build a plain add SCEV. 6330 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6331 // If the LHS of the add was an addrec and it has no-wrap flags, 6332 // transfer the no-wrap flags, since an or won't introduce a wrap. 6333 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6334 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6335 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6336 OldAR->getNoWrapFlags()); 6337 } 6338 return S; 6339 } 6340 } 6341 break; 6342 6343 case Instruction::Xor: 6344 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6345 // If the RHS of xor is -1, then this is a not operation. 6346 if (CI->isMinusOne()) 6347 return getNotSCEV(getSCEV(BO->LHS)); 6348 6349 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6350 // This is a variant of the check for xor with -1, and it handles 6351 // the case where instcombine has trimmed non-demanded bits out 6352 // of an xor with -1. 6353 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6354 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6355 if (LBO->getOpcode() == Instruction::And && 6356 LCI->getValue() == CI->getValue()) 6357 if (const SCEVZeroExtendExpr *Z = 6358 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6359 Type *UTy = BO->LHS->getType(); 6360 const SCEV *Z0 = Z->getOperand(); 6361 Type *Z0Ty = Z0->getType(); 6362 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6363 6364 // If C is a low-bits mask, the zero extend is serving to 6365 // mask off the high bits. Complement the operand and 6366 // re-apply the zext. 6367 if (CI->getValue().isMask(Z0TySize)) 6368 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6369 6370 // If C is a single bit, it may be in the sign-bit position 6371 // before the zero-extend. In this case, represent the xor 6372 // using an add, which is equivalent, and re-apply the zext. 6373 APInt Trunc = CI->getValue().trunc(Z0TySize); 6374 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6375 Trunc.isSignMask()) 6376 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6377 UTy); 6378 } 6379 } 6380 break; 6381 6382 case Instruction::Shl: 6383 // Turn shift left of a constant amount into a multiply. 6384 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6385 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6386 6387 // If the shift count is not less than the bitwidth, the result of 6388 // the shift is undefined. Don't try to analyze it, because the 6389 // resolution chosen here may differ from the resolution chosen in 6390 // other parts of the compiler. 6391 if (SA->getValue().uge(BitWidth)) 6392 break; 6393 6394 // It is currently not resolved how to interpret NSW for left 6395 // shift by BitWidth - 1, so we avoid applying flags in that 6396 // case. Remove this check (or this comment) once the situation 6397 // is resolved. See 6398 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6399 // and http://reviews.llvm.org/D8890 . 6400 auto Flags = SCEV::FlagAnyWrap; 6401 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6402 Flags = getNoWrapFlagsFromUB(BO->Op); 6403 6404 Constant *X = ConstantInt::get( 6405 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6406 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6407 } 6408 break; 6409 6410 case Instruction::AShr: { 6411 // AShr X, C, where C is a constant. 6412 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6413 if (!CI) 6414 break; 6415 6416 Type *OuterTy = BO->LHS->getType(); 6417 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6418 // If the shift count is not less than the bitwidth, the result of 6419 // the shift is undefined. Don't try to analyze it, because the 6420 // resolution chosen here may differ from the resolution chosen in 6421 // other parts of the compiler. 6422 if (CI->getValue().uge(BitWidth)) 6423 break; 6424 6425 if (CI->isZero()) 6426 return getSCEV(BO->LHS); // shift by zero --> noop 6427 6428 uint64_t AShrAmt = CI->getZExtValue(); 6429 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6430 6431 Operator *L = dyn_cast<Operator>(BO->LHS); 6432 if (L && L->getOpcode() == Instruction::Shl) { 6433 // X = Shl A, n 6434 // Y = AShr X, m 6435 // Both n and m are constant. 6436 6437 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6438 if (L->getOperand(1) == BO->RHS) 6439 // For a two-shift sext-inreg, i.e. n = m, 6440 // use sext(trunc(x)) as the SCEV expression. 6441 return getSignExtendExpr( 6442 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6443 6444 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6445 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6446 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6447 if (ShlAmt > AShrAmt) { 6448 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6449 // expression. We already checked that ShlAmt < BitWidth, so 6450 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6451 // ShlAmt - AShrAmt < Amt. 6452 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6453 ShlAmt - AShrAmt); 6454 return getSignExtendExpr( 6455 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6456 getConstant(Mul)), OuterTy); 6457 } 6458 } 6459 } 6460 break; 6461 } 6462 } 6463 } 6464 6465 switch (U->getOpcode()) { 6466 case Instruction::Trunc: 6467 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6468 6469 case Instruction::ZExt: 6470 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6471 6472 case Instruction::SExt: 6473 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6474 // The NSW flag of a subtract does not always survive the conversion to 6475 // A + (-1)*B. By pushing sign extension onto its operands we are much 6476 // more likely to preserve NSW and allow later AddRec optimisations. 6477 // 6478 // NOTE: This is effectively duplicating this logic from getSignExtend: 6479 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6480 // but by that point the NSW information has potentially been lost. 6481 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6482 Type *Ty = U->getType(); 6483 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6484 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6485 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6486 } 6487 } 6488 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6489 6490 case Instruction::BitCast: 6491 // BitCasts are no-op casts so we just eliminate the cast. 6492 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6493 return getSCEV(U->getOperand(0)); 6494 break; 6495 6496 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6497 // lead to pointer expressions which cannot safely be expanded to GEPs, 6498 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6499 // simplifying integer expressions. 6500 6501 case Instruction::GetElementPtr: 6502 return createNodeForGEP(cast<GEPOperator>(U)); 6503 6504 case Instruction::PHI: 6505 return createNodeForPHI(cast<PHINode>(U)); 6506 6507 case Instruction::Select: 6508 // U can also be a select constant expr, which let fall through. Since 6509 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6510 // constant expressions cannot have instructions as operands, we'd have 6511 // returned getUnknown for a select constant expressions anyway. 6512 if (isa<Instruction>(U)) 6513 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6514 U->getOperand(1), U->getOperand(2)); 6515 break; 6516 6517 case Instruction::Call: 6518 case Instruction::Invoke: 6519 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6520 return getSCEV(RV); 6521 break; 6522 } 6523 6524 return getUnknown(V); 6525 } 6526 6527 //===----------------------------------------------------------------------===// 6528 // Iteration Count Computation Code 6529 // 6530 6531 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6532 if (!ExitCount) 6533 return 0; 6534 6535 ConstantInt *ExitConst = ExitCount->getValue(); 6536 6537 // Guard against huge trip counts. 6538 if (ExitConst->getValue().getActiveBits() > 32) 6539 return 0; 6540 6541 // In case of integer overflow, this returns 0, which is correct. 6542 return ((unsigned)ExitConst->getZExtValue()) + 1; 6543 } 6544 6545 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6546 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6547 return getSmallConstantTripCount(L, ExitingBB); 6548 6549 // No trip count information for multiple exits. 6550 return 0; 6551 } 6552 6553 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6554 BasicBlock *ExitingBlock) { 6555 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6556 assert(L->isLoopExiting(ExitingBlock) && 6557 "Exiting block must actually branch out of the loop!"); 6558 const SCEVConstant *ExitCount = 6559 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6560 return getConstantTripCount(ExitCount); 6561 } 6562 6563 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6564 const auto *MaxExitCount = 6565 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6566 return getConstantTripCount(MaxExitCount); 6567 } 6568 6569 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6570 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6571 return getSmallConstantTripMultiple(L, ExitingBB); 6572 6573 // No trip multiple information for multiple exits. 6574 return 0; 6575 } 6576 6577 /// Returns the largest constant divisor of the trip count of this loop as a 6578 /// normal unsigned value, if possible. This means that the actual trip count is 6579 /// always a multiple of the returned value (don't forget the trip count could 6580 /// very well be zero as well!). 6581 /// 6582 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6583 /// multiple of a constant (which is also the case if the trip count is simply 6584 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6585 /// if the trip count is very large (>= 2^32). 6586 /// 6587 /// As explained in the comments for getSmallConstantTripCount, this assumes 6588 /// that control exits the loop via ExitingBlock. 6589 unsigned 6590 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6591 BasicBlock *ExitingBlock) { 6592 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6593 assert(L->isLoopExiting(ExitingBlock) && 6594 "Exiting block must actually branch out of the loop!"); 6595 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6596 if (ExitCount == getCouldNotCompute()) 6597 return 1; 6598 6599 // Get the trip count from the BE count by adding 1. 6600 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6601 6602 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6603 if (!TC) 6604 // Attempt to factor more general cases. Returns the greatest power of 6605 // two divisor. If overflow happens, the trip count expression is still 6606 // divisible by the greatest power of 2 divisor returned. 6607 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6608 6609 ConstantInt *Result = TC->getValue(); 6610 6611 // Guard against huge trip counts (this requires checking 6612 // for zero to handle the case where the trip count == -1 and the 6613 // addition wraps). 6614 if (!Result || Result->getValue().getActiveBits() > 32 || 6615 Result->getValue().getActiveBits() == 0) 6616 return 1; 6617 6618 return (unsigned)Result->getZExtValue(); 6619 } 6620 6621 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6622 BasicBlock *ExitingBlock, 6623 ExitCountKind Kind) { 6624 switch (Kind) { 6625 case Exact: 6626 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6627 case ConstantMaximum: 6628 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6629 }; 6630 llvm_unreachable("Invalid ExitCountKind!"); 6631 } 6632 6633 const SCEV * 6634 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6635 SCEVUnionPredicate &Preds) { 6636 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6637 } 6638 6639 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6640 ExitCountKind Kind) { 6641 switch (Kind) { 6642 case Exact: 6643 return getBackedgeTakenInfo(L).getExact(L, this); 6644 case ConstantMaximum: 6645 return getBackedgeTakenInfo(L).getMax(this); 6646 }; 6647 llvm_unreachable("Invalid ExitCountKind!"); 6648 } 6649 6650 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6651 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6652 } 6653 6654 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6655 static void 6656 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6657 BasicBlock *Header = L->getHeader(); 6658 6659 // Push all Loop-header PHIs onto the Worklist stack. 6660 for (PHINode &PN : Header->phis()) 6661 Worklist.push_back(&PN); 6662 } 6663 6664 const ScalarEvolution::BackedgeTakenInfo & 6665 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6666 auto &BTI = getBackedgeTakenInfo(L); 6667 if (BTI.hasFullInfo()) 6668 return BTI; 6669 6670 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6671 6672 if (!Pair.second) 6673 return Pair.first->second; 6674 6675 BackedgeTakenInfo Result = 6676 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6677 6678 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6679 } 6680 6681 const ScalarEvolution::BackedgeTakenInfo & 6682 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6683 // Initially insert an invalid entry for this loop. If the insertion 6684 // succeeds, proceed to actually compute a backedge-taken count and 6685 // update the value. The temporary CouldNotCompute value tells SCEV 6686 // code elsewhere that it shouldn't attempt to request a new 6687 // backedge-taken count, which could result in infinite recursion. 6688 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6689 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6690 if (!Pair.second) 6691 return Pair.first->second; 6692 6693 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6694 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6695 // must be cleared in this scope. 6696 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6697 6698 // In product build, there are no usage of statistic. 6699 (void)NumTripCountsComputed; 6700 (void)NumTripCountsNotComputed; 6701 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6702 const SCEV *BEExact = Result.getExact(L, this); 6703 if (BEExact != getCouldNotCompute()) { 6704 assert(isLoopInvariant(BEExact, L) && 6705 isLoopInvariant(Result.getMax(this), L) && 6706 "Computed backedge-taken count isn't loop invariant for loop!"); 6707 ++NumTripCountsComputed; 6708 } 6709 else if (Result.getMax(this) == getCouldNotCompute() && 6710 isa<PHINode>(L->getHeader()->begin())) { 6711 // Only count loops that have phi nodes as not being computable. 6712 ++NumTripCountsNotComputed; 6713 } 6714 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6715 6716 // Now that we know more about the trip count for this loop, forget any 6717 // existing SCEV values for PHI nodes in this loop since they are only 6718 // conservative estimates made without the benefit of trip count 6719 // information. This is similar to the code in forgetLoop, except that 6720 // it handles SCEVUnknown PHI nodes specially. 6721 if (Result.hasAnyInfo()) { 6722 SmallVector<Instruction *, 16> Worklist; 6723 PushLoopPHIs(L, Worklist); 6724 6725 SmallPtrSet<Instruction *, 8> Discovered; 6726 while (!Worklist.empty()) { 6727 Instruction *I = Worklist.pop_back_val(); 6728 6729 ValueExprMapType::iterator It = 6730 ValueExprMap.find_as(static_cast<Value *>(I)); 6731 if (It != ValueExprMap.end()) { 6732 const SCEV *Old = It->second; 6733 6734 // SCEVUnknown for a PHI either means that it has an unrecognized 6735 // structure, or it's a PHI that's in the progress of being computed 6736 // by createNodeForPHI. In the former case, additional loop trip 6737 // count information isn't going to change anything. In the later 6738 // case, createNodeForPHI will perform the necessary updates on its 6739 // own when it gets to that point. 6740 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6741 eraseValueFromMap(It->first); 6742 forgetMemoizedResults(Old); 6743 } 6744 if (PHINode *PN = dyn_cast<PHINode>(I)) 6745 ConstantEvolutionLoopExitValue.erase(PN); 6746 } 6747 6748 // Since we don't need to invalidate anything for correctness and we're 6749 // only invalidating to make SCEV's results more precise, we get to stop 6750 // early to avoid invalidating too much. This is especially important in 6751 // cases like: 6752 // 6753 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6754 // loop0: 6755 // %pn0 = phi 6756 // ... 6757 // loop1: 6758 // %pn1 = phi 6759 // ... 6760 // 6761 // where both loop0 and loop1's backedge taken count uses the SCEV 6762 // expression for %v. If we don't have the early stop below then in cases 6763 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6764 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6765 // count for loop1, effectively nullifying SCEV's trip count cache. 6766 for (auto *U : I->users()) 6767 if (auto *I = dyn_cast<Instruction>(U)) { 6768 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6769 if (LoopForUser && L->contains(LoopForUser) && 6770 Discovered.insert(I).second) 6771 Worklist.push_back(I); 6772 } 6773 } 6774 } 6775 6776 // Re-lookup the insert position, since the call to 6777 // computeBackedgeTakenCount above could result in a 6778 // recusive call to getBackedgeTakenInfo (on a different 6779 // loop), which would invalidate the iterator computed 6780 // earlier. 6781 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6782 } 6783 6784 void ScalarEvolution::forgetAllLoops() { 6785 // This method is intended to forget all info about loops. It should 6786 // invalidate caches as if the following happened: 6787 // - The trip counts of all loops have changed arbitrarily 6788 // - Every llvm::Value has been updated in place to produce a different 6789 // result. 6790 BackedgeTakenCounts.clear(); 6791 PredicatedBackedgeTakenCounts.clear(); 6792 LoopPropertiesCache.clear(); 6793 ConstantEvolutionLoopExitValue.clear(); 6794 ValueExprMap.clear(); 6795 ValuesAtScopes.clear(); 6796 LoopDispositions.clear(); 6797 BlockDispositions.clear(); 6798 UnsignedRanges.clear(); 6799 SignedRanges.clear(); 6800 ExprValueMap.clear(); 6801 HasRecMap.clear(); 6802 MinTrailingZerosCache.clear(); 6803 PredicatedSCEVRewrites.clear(); 6804 } 6805 6806 void ScalarEvolution::forgetLoop(const Loop *L) { 6807 // Drop any stored trip count value. 6808 auto RemoveLoopFromBackedgeMap = 6809 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6810 auto BTCPos = Map.find(L); 6811 if (BTCPos != Map.end()) { 6812 BTCPos->second.clear(); 6813 Map.erase(BTCPos); 6814 } 6815 }; 6816 6817 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6818 SmallVector<Instruction *, 32> Worklist; 6819 SmallPtrSet<Instruction *, 16> Visited; 6820 6821 // Iterate over all the loops and sub-loops to drop SCEV information. 6822 while (!LoopWorklist.empty()) { 6823 auto *CurrL = LoopWorklist.pop_back_val(); 6824 6825 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6826 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6827 6828 // Drop information about predicated SCEV rewrites for this loop. 6829 for (auto I = PredicatedSCEVRewrites.begin(); 6830 I != PredicatedSCEVRewrites.end();) { 6831 std::pair<const SCEV *, const Loop *> Entry = I->first; 6832 if (Entry.second == CurrL) 6833 PredicatedSCEVRewrites.erase(I++); 6834 else 6835 ++I; 6836 } 6837 6838 auto LoopUsersItr = LoopUsers.find(CurrL); 6839 if (LoopUsersItr != LoopUsers.end()) { 6840 for (auto *S : LoopUsersItr->second) 6841 forgetMemoizedResults(S); 6842 LoopUsers.erase(LoopUsersItr); 6843 } 6844 6845 // Drop information about expressions based on loop-header PHIs. 6846 PushLoopPHIs(CurrL, Worklist); 6847 6848 while (!Worklist.empty()) { 6849 Instruction *I = Worklist.pop_back_val(); 6850 if (!Visited.insert(I).second) 6851 continue; 6852 6853 ValueExprMapType::iterator It = 6854 ValueExprMap.find_as(static_cast<Value *>(I)); 6855 if (It != ValueExprMap.end()) { 6856 eraseValueFromMap(It->first); 6857 forgetMemoizedResults(It->second); 6858 if (PHINode *PN = dyn_cast<PHINode>(I)) 6859 ConstantEvolutionLoopExitValue.erase(PN); 6860 } 6861 6862 PushDefUseChildren(I, Worklist); 6863 } 6864 6865 LoopPropertiesCache.erase(CurrL); 6866 // Forget all contained loops too, to avoid dangling entries in the 6867 // ValuesAtScopes map. 6868 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6869 } 6870 } 6871 6872 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6873 while (Loop *Parent = L->getParentLoop()) 6874 L = Parent; 6875 forgetLoop(L); 6876 } 6877 6878 void ScalarEvolution::forgetValue(Value *V) { 6879 Instruction *I = dyn_cast<Instruction>(V); 6880 if (!I) return; 6881 6882 // Drop information about expressions based on loop-header PHIs. 6883 SmallVector<Instruction *, 16> Worklist; 6884 Worklist.push_back(I); 6885 6886 SmallPtrSet<Instruction *, 8> Visited; 6887 while (!Worklist.empty()) { 6888 I = Worklist.pop_back_val(); 6889 if (!Visited.insert(I).second) 6890 continue; 6891 6892 ValueExprMapType::iterator It = 6893 ValueExprMap.find_as(static_cast<Value *>(I)); 6894 if (It != ValueExprMap.end()) { 6895 eraseValueFromMap(It->first); 6896 forgetMemoizedResults(It->second); 6897 if (PHINode *PN = dyn_cast<PHINode>(I)) 6898 ConstantEvolutionLoopExitValue.erase(PN); 6899 } 6900 6901 PushDefUseChildren(I, Worklist); 6902 } 6903 } 6904 6905 /// Get the exact loop backedge taken count considering all loop exits. A 6906 /// computable result can only be returned for loops with all exiting blocks 6907 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6908 /// is never skipped. This is a valid assumption as long as the loop exits via 6909 /// that test. For precise results, it is the caller's responsibility to specify 6910 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6911 const SCEV * 6912 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6913 SCEVUnionPredicate *Preds) const { 6914 // If any exits were not computable, the loop is not computable. 6915 if (!isComplete() || ExitNotTaken.empty()) 6916 return SE->getCouldNotCompute(); 6917 6918 const BasicBlock *Latch = L->getLoopLatch(); 6919 // All exiting blocks we have collected must dominate the only backedge. 6920 if (!Latch) 6921 return SE->getCouldNotCompute(); 6922 6923 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6924 // count is simply a minimum out of all these calculated exit counts. 6925 SmallVector<const SCEV *, 2> Ops; 6926 for (auto &ENT : ExitNotTaken) { 6927 const SCEV *BECount = ENT.ExactNotTaken; 6928 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6929 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6930 "We should only have known counts for exiting blocks that dominate " 6931 "latch!"); 6932 6933 Ops.push_back(BECount); 6934 6935 if (Preds && !ENT.hasAlwaysTruePredicate()) 6936 Preds->add(ENT.Predicate.get()); 6937 6938 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6939 "Predicate should be always true!"); 6940 } 6941 6942 return SE->getUMinFromMismatchedTypes(Ops); 6943 } 6944 6945 /// Get the exact not taken count for this loop exit. 6946 const SCEV * 6947 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6948 ScalarEvolution *SE) const { 6949 for (auto &ENT : ExitNotTaken) 6950 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6951 return ENT.ExactNotTaken; 6952 6953 return SE->getCouldNotCompute(); 6954 } 6955 6956 const SCEV * 6957 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 6958 ScalarEvolution *SE) const { 6959 for (auto &ENT : ExitNotTaken) 6960 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6961 return ENT.MaxNotTaken; 6962 6963 return SE->getCouldNotCompute(); 6964 } 6965 6966 /// getMax - Get the max backedge taken count for the loop. 6967 const SCEV * 6968 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6969 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6970 return !ENT.hasAlwaysTruePredicate(); 6971 }; 6972 6973 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6974 return SE->getCouldNotCompute(); 6975 6976 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6977 "No point in having a non-constant max backedge taken count!"); 6978 return getMax(); 6979 } 6980 6981 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6982 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6983 return !ENT.hasAlwaysTruePredicate(); 6984 }; 6985 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6986 } 6987 6988 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6989 ScalarEvolution *SE) const { 6990 if (getMax() && getMax() != SE->getCouldNotCompute() && 6991 SE->hasOperand(getMax(), S)) 6992 return true; 6993 6994 for (auto &ENT : ExitNotTaken) 6995 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6996 SE->hasOperand(ENT.ExactNotTaken, S)) 6997 return true; 6998 6999 return false; 7000 } 7001 7002 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7003 : ExactNotTaken(E), MaxNotTaken(E) { 7004 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7005 isa<SCEVConstant>(MaxNotTaken)) && 7006 "No point in having a non-constant max backedge taken count!"); 7007 } 7008 7009 ScalarEvolution::ExitLimit::ExitLimit( 7010 const SCEV *E, const SCEV *M, bool MaxOrZero, 7011 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7012 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7013 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7014 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7015 "Exact is not allowed to be less precise than Max"); 7016 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7017 isa<SCEVConstant>(MaxNotTaken)) && 7018 "No point in having a non-constant max backedge taken count!"); 7019 for (auto *PredSet : PredSetList) 7020 for (auto *P : *PredSet) 7021 addPredicate(P); 7022 } 7023 7024 ScalarEvolution::ExitLimit::ExitLimit( 7025 const SCEV *E, const SCEV *M, bool MaxOrZero, 7026 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7027 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7028 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7029 isa<SCEVConstant>(MaxNotTaken)) && 7030 "No point in having a non-constant max backedge taken count!"); 7031 } 7032 7033 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7034 bool MaxOrZero) 7035 : ExitLimit(E, M, MaxOrZero, None) { 7036 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7037 isa<SCEVConstant>(MaxNotTaken)) && 7038 "No point in having a non-constant max backedge taken count!"); 7039 } 7040 7041 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7042 /// computable exit into a persistent ExitNotTakenInfo array. 7043 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7044 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7045 ExitCounts, 7046 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7047 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7048 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7049 7050 ExitNotTaken.reserve(ExitCounts.size()); 7051 std::transform( 7052 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7053 [&](const EdgeExitInfo &EEI) { 7054 BasicBlock *ExitBB = EEI.first; 7055 const ExitLimit &EL = EEI.second; 7056 if (EL.Predicates.empty()) 7057 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7058 nullptr); 7059 7060 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7061 for (auto *Pred : EL.Predicates) 7062 Predicate->add(Pred); 7063 7064 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7065 std::move(Predicate)); 7066 }); 7067 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7068 "No point in having a non-constant max backedge taken count!"); 7069 } 7070 7071 /// Invalidate this result and free the ExitNotTakenInfo array. 7072 void ScalarEvolution::BackedgeTakenInfo::clear() { 7073 ExitNotTaken.clear(); 7074 } 7075 7076 /// Compute the number of times the backedge of the specified loop will execute. 7077 ScalarEvolution::BackedgeTakenInfo 7078 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7079 bool AllowPredicates) { 7080 SmallVector<BasicBlock *, 8> ExitingBlocks; 7081 L->getExitingBlocks(ExitingBlocks); 7082 7083 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7084 7085 SmallVector<EdgeExitInfo, 4> ExitCounts; 7086 bool CouldComputeBECount = true; 7087 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7088 const SCEV *MustExitMaxBECount = nullptr; 7089 const SCEV *MayExitMaxBECount = nullptr; 7090 bool MustExitMaxOrZero = false; 7091 7092 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7093 // and compute maxBECount. 7094 // Do a union of all the predicates here. 7095 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7096 BasicBlock *ExitBB = ExitingBlocks[i]; 7097 7098 // We canonicalize untaken exits to br (constant), ignore them so that 7099 // proving an exit untaken doesn't negatively impact our ability to reason 7100 // about the loop as whole. 7101 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7102 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7103 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7104 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7105 continue; 7106 } 7107 7108 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7109 7110 assert((AllowPredicates || EL.Predicates.empty()) && 7111 "Predicated exit limit when predicates are not allowed!"); 7112 7113 // 1. For each exit that can be computed, add an entry to ExitCounts. 7114 // CouldComputeBECount is true only if all exits can be computed. 7115 if (EL.ExactNotTaken == getCouldNotCompute()) 7116 // We couldn't compute an exact value for this exit, so 7117 // we won't be able to compute an exact value for the loop. 7118 CouldComputeBECount = false; 7119 else 7120 ExitCounts.emplace_back(ExitBB, EL); 7121 7122 // 2. Derive the loop's MaxBECount from each exit's max number of 7123 // non-exiting iterations. Partition the loop exits into two kinds: 7124 // LoopMustExits and LoopMayExits. 7125 // 7126 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7127 // is a LoopMayExit. If any computable LoopMustExit is found, then 7128 // MaxBECount is the minimum EL.MaxNotTaken of computable 7129 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7130 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7131 // computable EL.MaxNotTaken. 7132 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7133 DT.dominates(ExitBB, Latch)) { 7134 if (!MustExitMaxBECount) { 7135 MustExitMaxBECount = EL.MaxNotTaken; 7136 MustExitMaxOrZero = EL.MaxOrZero; 7137 } else { 7138 MustExitMaxBECount = 7139 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7140 } 7141 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7142 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7143 MayExitMaxBECount = EL.MaxNotTaken; 7144 else { 7145 MayExitMaxBECount = 7146 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7147 } 7148 } 7149 } 7150 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7151 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7152 // The loop backedge will be taken the maximum or zero times if there's 7153 // a single exit that must be taken the maximum or zero times. 7154 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7155 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7156 MaxBECount, MaxOrZero); 7157 } 7158 7159 ScalarEvolution::ExitLimit 7160 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7161 bool AllowPredicates) { 7162 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7163 // If our exiting block does not dominate the latch, then its connection with 7164 // loop's exit limit may be far from trivial. 7165 const BasicBlock *Latch = L->getLoopLatch(); 7166 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7167 return getCouldNotCompute(); 7168 7169 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7170 Instruction *Term = ExitingBlock->getTerminator(); 7171 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7172 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7173 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7174 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7175 "It should have one successor in loop and one exit block!"); 7176 // Proceed to the next level to examine the exit condition expression. 7177 return computeExitLimitFromCond( 7178 L, BI->getCondition(), ExitIfTrue, 7179 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7180 } 7181 7182 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7183 // For switch, make sure that there is a single exit from the loop. 7184 BasicBlock *Exit = nullptr; 7185 for (auto *SBB : successors(ExitingBlock)) 7186 if (!L->contains(SBB)) { 7187 if (Exit) // Multiple exit successors. 7188 return getCouldNotCompute(); 7189 Exit = SBB; 7190 } 7191 assert(Exit && "Exiting block must have at least one exit"); 7192 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7193 /*ControlsExit=*/IsOnlyExit); 7194 } 7195 7196 return getCouldNotCompute(); 7197 } 7198 7199 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7200 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7201 bool ControlsExit, bool AllowPredicates) { 7202 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7203 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7204 ControlsExit, AllowPredicates); 7205 } 7206 7207 Optional<ScalarEvolution::ExitLimit> 7208 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7209 bool ExitIfTrue, bool ControlsExit, 7210 bool AllowPredicates) { 7211 (void)this->L; 7212 (void)this->ExitIfTrue; 7213 (void)this->AllowPredicates; 7214 7215 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7216 this->AllowPredicates == AllowPredicates && 7217 "Variance in assumed invariant key components!"); 7218 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7219 if (Itr == TripCountMap.end()) 7220 return None; 7221 return Itr->second; 7222 } 7223 7224 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7225 bool ExitIfTrue, 7226 bool ControlsExit, 7227 bool AllowPredicates, 7228 const ExitLimit &EL) { 7229 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7230 this->AllowPredicates == AllowPredicates && 7231 "Variance in assumed invariant key components!"); 7232 7233 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7234 assert(InsertResult.second && "Expected successful insertion!"); 7235 (void)InsertResult; 7236 (void)ExitIfTrue; 7237 } 7238 7239 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7240 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7241 bool ControlsExit, bool AllowPredicates) { 7242 7243 if (auto MaybeEL = 7244 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7245 return *MaybeEL; 7246 7247 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7248 ControlsExit, AllowPredicates); 7249 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7250 return EL; 7251 } 7252 7253 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7254 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7255 bool ControlsExit, bool AllowPredicates) { 7256 // Check if the controlling expression for this loop is an And or Or. 7257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7258 if (BO->getOpcode() == Instruction::And) { 7259 // Recurse on the operands of the and. 7260 bool EitherMayExit = !ExitIfTrue; 7261 ExitLimit EL0 = computeExitLimitFromCondCached( 7262 Cache, L, BO->getOperand(0), ExitIfTrue, 7263 ControlsExit && !EitherMayExit, AllowPredicates); 7264 ExitLimit EL1 = computeExitLimitFromCondCached( 7265 Cache, L, BO->getOperand(1), ExitIfTrue, 7266 ControlsExit && !EitherMayExit, AllowPredicates); 7267 // Be robust against unsimplified IR for the form "and i1 X, true" 7268 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7269 return CI->isOne() ? EL0 : EL1; 7270 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7271 return CI->isOne() ? EL1 : EL0; 7272 const SCEV *BECount = getCouldNotCompute(); 7273 const SCEV *MaxBECount = getCouldNotCompute(); 7274 if (EitherMayExit) { 7275 // Both conditions must be true for the loop to continue executing. 7276 // Choose the less conservative count. 7277 if (EL0.ExactNotTaken == getCouldNotCompute() || 7278 EL1.ExactNotTaken == getCouldNotCompute()) 7279 BECount = getCouldNotCompute(); 7280 else 7281 BECount = 7282 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7283 if (EL0.MaxNotTaken == getCouldNotCompute()) 7284 MaxBECount = EL1.MaxNotTaken; 7285 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7286 MaxBECount = EL0.MaxNotTaken; 7287 else 7288 MaxBECount = 7289 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7290 } else { 7291 // Both conditions must be true at the same time for the loop to exit. 7292 // For now, be conservative. 7293 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7294 MaxBECount = EL0.MaxNotTaken; 7295 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7296 BECount = EL0.ExactNotTaken; 7297 } 7298 7299 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7300 // to be more aggressive when computing BECount than when computing 7301 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7302 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7303 // to not. 7304 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7305 !isa<SCEVCouldNotCompute>(BECount)) 7306 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7307 7308 return ExitLimit(BECount, MaxBECount, false, 7309 {&EL0.Predicates, &EL1.Predicates}); 7310 } 7311 if (BO->getOpcode() == Instruction::Or) { 7312 // Recurse on the operands of the or. 7313 bool EitherMayExit = ExitIfTrue; 7314 ExitLimit EL0 = computeExitLimitFromCondCached( 7315 Cache, L, BO->getOperand(0), ExitIfTrue, 7316 ControlsExit && !EitherMayExit, AllowPredicates); 7317 ExitLimit EL1 = computeExitLimitFromCondCached( 7318 Cache, L, BO->getOperand(1), ExitIfTrue, 7319 ControlsExit && !EitherMayExit, AllowPredicates); 7320 // Be robust against unsimplified IR for the form "or i1 X, true" 7321 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7322 return CI->isZero() ? EL0 : EL1; 7323 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7324 return CI->isZero() ? EL1 : EL0; 7325 const SCEV *BECount = getCouldNotCompute(); 7326 const SCEV *MaxBECount = getCouldNotCompute(); 7327 if (EitherMayExit) { 7328 // Both conditions must be false for the loop to continue executing. 7329 // Choose the less conservative count. 7330 if (EL0.ExactNotTaken == getCouldNotCompute() || 7331 EL1.ExactNotTaken == getCouldNotCompute()) 7332 BECount = getCouldNotCompute(); 7333 else 7334 BECount = 7335 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7336 if (EL0.MaxNotTaken == getCouldNotCompute()) 7337 MaxBECount = EL1.MaxNotTaken; 7338 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7339 MaxBECount = EL0.MaxNotTaken; 7340 else 7341 MaxBECount = 7342 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7343 } else { 7344 // Both conditions must be false at the same time for the loop to exit. 7345 // For now, be conservative. 7346 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7347 MaxBECount = EL0.MaxNotTaken; 7348 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7349 BECount = EL0.ExactNotTaken; 7350 } 7351 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7352 // to be more aggressive when computing BECount than when computing 7353 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7354 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7355 // to not. 7356 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7357 !isa<SCEVCouldNotCompute>(BECount)) 7358 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7359 7360 return ExitLimit(BECount, MaxBECount, false, 7361 {&EL0.Predicates, &EL1.Predicates}); 7362 } 7363 } 7364 7365 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7366 // Proceed to the next level to examine the icmp. 7367 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7368 ExitLimit EL = 7369 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7370 if (EL.hasFullInfo() || !AllowPredicates) 7371 return EL; 7372 7373 // Try again, but use SCEV predicates this time. 7374 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7375 /*AllowPredicates=*/true); 7376 } 7377 7378 // Check for a constant condition. These are normally stripped out by 7379 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7380 // preserve the CFG and is temporarily leaving constant conditions 7381 // in place. 7382 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7383 if (ExitIfTrue == !CI->getZExtValue()) 7384 // The backedge is always taken. 7385 return getCouldNotCompute(); 7386 else 7387 // The backedge is never taken. 7388 return getZero(CI->getType()); 7389 } 7390 7391 // If it's not an integer or pointer comparison then compute it the hard way. 7392 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7393 } 7394 7395 ScalarEvolution::ExitLimit 7396 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7397 ICmpInst *ExitCond, 7398 bool ExitIfTrue, 7399 bool ControlsExit, 7400 bool AllowPredicates) { 7401 // If the condition was exit on true, convert the condition to exit on false 7402 ICmpInst::Predicate Pred; 7403 if (!ExitIfTrue) 7404 Pred = ExitCond->getPredicate(); 7405 else 7406 Pred = ExitCond->getInversePredicate(); 7407 const ICmpInst::Predicate OriginalPred = Pred; 7408 7409 // Handle common loops like: for (X = "string"; *X; ++X) 7410 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7411 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7412 ExitLimit ItCnt = 7413 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7414 if (ItCnt.hasAnyInfo()) 7415 return ItCnt; 7416 } 7417 7418 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7419 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7420 7421 // Try to evaluate any dependencies out of the loop. 7422 LHS = getSCEVAtScope(LHS, L); 7423 RHS = getSCEVAtScope(RHS, L); 7424 7425 // At this point, we would like to compute how many iterations of the 7426 // loop the predicate will return true for these inputs. 7427 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7428 // If there is a loop-invariant, force it into the RHS. 7429 std::swap(LHS, RHS); 7430 Pred = ICmpInst::getSwappedPredicate(Pred); 7431 } 7432 7433 // Simplify the operands before analyzing them. 7434 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7435 7436 // If we have a comparison of a chrec against a constant, try to use value 7437 // ranges to answer this query. 7438 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7439 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7440 if (AddRec->getLoop() == L) { 7441 // Form the constant range. 7442 ConstantRange CompRange = 7443 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7444 7445 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7446 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7447 } 7448 7449 switch (Pred) { 7450 case ICmpInst::ICMP_NE: { // while (X != Y) 7451 // Convert to: while (X-Y != 0) 7452 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7453 AllowPredicates); 7454 if (EL.hasAnyInfo()) return EL; 7455 break; 7456 } 7457 case ICmpInst::ICMP_EQ: { // while (X == Y) 7458 // Convert to: while (X-Y == 0) 7459 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7460 if (EL.hasAnyInfo()) return EL; 7461 break; 7462 } 7463 case ICmpInst::ICMP_SLT: 7464 case ICmpInst::ICMP_ULT: { // while (X < Y) 7465 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7466 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7467 AllowPredicates); 7468 if (EL.hasAnyInfo()) return EL; 7469 break; 7470 } 7471 case ICmpInst::ICMP_SGT: 7472 case ICmpInst::ICMP_UGT: { // while (X > Y) 7473 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7474 ExitLimit EL = 7475 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7476 AllowPredicates); 7477 if (EL.hasAnyInfo()) return EL; 7478 break; 7479 } 7480 default: 7481 break; 7482 } 7483 7484 auto *ExhaustiveCount = 7485 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7486 7487 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7488 return ExhaustiveCount; 7489 7490 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7491 ExitCond->getOperand(1), L, OriginalPred); 7492 } 7493 7494 ScalarEvolution::ExitLimit 7495 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7496 SwitchInst *Switch, 7497 BasicBlock *ExitingBlock, 7498 bool ControlsExit) { 7499 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7500 7501 // Give up if the exit is the default dest of a switch. 7502 if (Switch->getDefaultDest() == ExitingBlock) 7503 return getCouldNotCompute(); 7504 7505 assert(L->contains(Switch->getDefaultDest()) && 7506 "Default case must not exit the loop!"); 7507 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7508 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7509 7510 // while (X != Y) --> while (X-Y != 0) 7511 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7512 if (EL.hasAnyInfo()) 7513 return EL; 7514 7515 return getCouldNotCompute(); 7516 } 7517 7518 static ConstantInt * 7519 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7520 ScalarEvolution &SE) { 7521 const SCEV *InVal = SE.getConstant(C); 7522 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7523 assert(isa<SCEVConstant>(Val) && 7524 "Evaluation of SCEV at constant didn't fold correctly?"); 7525 return cast<SCEVConstant>(Val)->getValue(); 7526 } 7527 7528 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7529 /// compute the backedge execution count. 7530 ScalarEvolution::ExitLimit 7531 ScalarEvolution::computeLoadConstantCompareExitLimit( 7532 LoadInst *LI, 7533 Constant *RHS, 7534 const Loop *L, 7535 ICmpInst::Predicate predicate) { 7536 if (LI->isVolatile()) return getCouldNotCompute(); 7537 7538 // Check to see if the loaded pointer is a getelementptr of a global. 7539 // TODO: Use SCEV instead of manually grubbing with GEPs. 7540 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7541 if (!GEP) return getCouldNotCompute(); 7542 7543 // Make sure that it is really a constant global we are gepping, with an 7544 // initializer, and make sure the first IDX is really 0. 7545 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7546 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7547 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7548 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7549 return getCouldNotCompute(); 7550 7551 // Okay, we allow one non-constant index into the GEP instruction. 7552 Value *VarIdx = nullptr; 7553 std::vector<Constant*> Indexes; 7554 unsigned VarIdxNum = 0; 7555 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7556 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7557 Indexes.push_back(CI); 7558 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7559 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7560 VarIdx = GEP->getOperand(i); 7561 VarIdxNum = i-2; 7562 Indexes.push_back(nullptr); 7563 } 7564 7565 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7566 if (!VarIdx) 7567 return getCouldNotCompute(); 7568 7569 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7570 // Check to see if X is a loop variant variable value now. 7571 const SCEV *Idx = getSCEV(VarIdx); 7572 Idx = getSCEVAtScope(Idx, L); 7573 7574 // We can only recognize very limited forms of loop index expressions, in 7575 // particular, only affine AddRec's like {C1,+,C2}. 7576 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7577 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7578 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7579 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7580 return getCouldNotCompute(); 7581 7582 unsigned MaxSteps = MaxBruteForceIterations; 7583 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7584 ConstantInt *ItCst = ConstantInt::get( 7585 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7586 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7587 7588 // Form the GEP offset. 7589 Indexes[VarIdxNum] = Val; 7590 7591 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7592 Indexes); 7593 if (!Result) break; // Cannot compute! 7594 7595 // Evaluate the condition for this iteration. 7596 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7597 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7598 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7599 ++NumArrayLenItCounts; 7600 return getConstant(ItCst); // Found terminating iteration! 7601 } 7602 } 7603 return getCouldNotCompute(); 7604 } 7605 7606 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7607 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7608 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7609 if (!RHS) 7610 return getCouldNotCompute(); 7611 7612 const BasicBlock *Latch = L->getLoopLatch(); 7613 if (!Latch) 7614 return getCouldNotCompute(); 7615 7616 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7617 if (!Predecessor) 7618 return getCouldNotCompute(); 7619 7620 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7621 // Return LHS in OutLHS and shift_opt in OutOpCode. 7622 auto MatchPositiveShift = 7623 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7624 7625 using namespace PatternMatch; 7626 7627 ConstantInt *ShiftAmt; 7628 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7629 OutOpCode = Instruction::LShr; 7630 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7631 OutOpCode = Instruction::AShr; 7632 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7633 OutOpCode = Instruction::Shl; 7634 else 7635 return false; 7636 7637 return ShiftAmt->getValue().isStrictlyPositive(); 7638 }; 7639 7640 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7641 // 7642 // loop: 7643 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7644 // %iv.shifted = lshr i32 %iv, <positive constant> 7645 // 7646 // Return true on a successful match. Return the corresponding PHI node (%iv 7647 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7648 auto MatchShiftRecurrence = 7649 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7650 Optional<Instruction::BinaryOps> PostShiftOpCode; 7651 7652 { 7653 Instruction::BinaryOps OpC; 7654 Value *V; 7655 7656 // If we encounter a shift instruction, "peel off" the shift operation, 7657 // and remember that we did so. Later when we inspect %iv's backedge 7658 // value, we will make sure that the backedge value uses the same 7659 // operation. 7660 // 7661 // Note: the peeled shift operation does not have to be the same 7662 // instruction as the one feeding into the PHI's backedge value. We only 7663 // really care about it being the same *kind* of shift instruction -- 7664 // that's all that is required for our later inferences to hold. 7665 if (MatchPositiveShift(LHS, V, OpC)) { 7666 PostShiftOpCode = OpC; 7667 LHS = V; 7668 } 7669 } 7670 7671 PNOut = dyn_cast<PHINode>(LHS); 7672 if (!PNOut || PNOut->getParent() != L->getHeader()) 7673 return false; 7674 7675 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7676 Value *OpLHS; 7677 7678 return 7679 // The backedge value for the PHI node must be a shift by a positive 7680 // amount 7681 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7682 7683 // of the PHI node itself 7684 OpLHS == PNOut && 7685 7686 // and the kind of shift should be match the kind of shift we peeled 7687 // off, if any. 7688 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7689 }; 7690 7691 PHINode *PN; 7692 Instruction::BinaryOps OpCode; 7693 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7694 return getCouldNotCompute(); 7695 7696 const DataLayout &DL = getDataLayout(); 7697 7698 // The key rationale for this optimization is that for some kinds of shift 7699 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7700 // within a finite number of iterations. If the condition guarding the 7701 // backedge (in the sense that the backedge is taken if the condition is true) 7702 // is false for the value the shift recurrence stabilizes to, then we know 7703 // that the backedge is taken only a finite number of times. 7704 7705 ConstantInt *StableValue = nullptr; 7706 switch (OpCode) { 7707 default: 7708 llvm_unreachable("Impossible case!"); 7709 7710 case Instruction::AShr: { 7711 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7712 // bitwidth(K) iterations. 7713 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7714 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7715 Predecessor->getTerminator(), &DT); 7716 auto *Ty = cast<IntegerType>(RHS->getType()); 7717 if (Known.isNonNegative()) 7718 StableValue = ConstantInt::get(Ty, 0); 7719 else if (Known.isNegative()) 7720 StableValue = ConstantInt::get(Ty, -1, true); 7721 else 7722 return getCouldNotCompute(); 7723 7724 break; 7725 } 7726 case Instruction::LShr: 7727 case Instruction::Shl: 7728 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7729 // stabilize to 0 in at most bitwidth(K) iterations. 7730 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7731 break; 7732 } 7733 7734 auto *Result = 7735 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7736 assert(Result->getType()->isIntegerTy(1) && 7737 "Otherwise cannot be an operand to a branch instruction"); 7738 7739 if (Result->isZeroValue()) { 7740 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7741 const SCEV *UpperBound = 7742 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7743 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7744 } 7745 7746 return getCouldNotCompute(); 7747 } 7748 7749 /// Return true if we can constant fold an instruction of the specified type, 7750 /// assuming that all operands were constants. 7751 static bool CanConstantFold(const Instruction *I) { 7752 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7753 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7754 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7755 return true; 7756 7757 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7758 if (const Function *F = CI->getCalledFunction()) 7759 return canConstantFoldCallTo(CI, F); 7760 return false; 7761 } 7762 7763 /// Determine whether this instruction can constant evolve within this loop 7764 /// assuming its operands can all constant evolve. 7765 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7766 // An instruction outside of the loop can't be derived from a loop PHI. 7767 if (!L->contains(I)) return false; 7768 7769 if (isa<PHINode>(I)) { 7770 // We don't currently keep track of the control flow needed to evaluate 7771 // PHIs, so we cannot handle PHIs inside of loops. 7772 return L->getHeader() == I->getParent(); 7773 } 7774 7775 // If we won't be able to constant fold this expression even if the operands 7776 // are constants, bail early. 7777 return CanConstantFold(I); 7778 } 7779 7780 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7781 /// recursing through each instruction operand until reaching a loop header phi. 7782 static PHINode * 7783 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7784 DenseMap<Instruction *, PHINode *> &PHIMap, 7785 unsigned Depth) { 7786 if (Depth > MaxConstantEvolvingDepth) 7787 return nullptr; 7788 7789 // Otherwise, we can evaluate this instruction if all of its operands are 7790 // constant or derived from a PHI node themselves. 7791 PHINode *PHI = nullptr; 7792 for (Value *Op : UseInst->operands()) { 7793 if (isa<Constant>(Op)) continue; 7794 7795 Instruction *OpInst = dyn_cast<Instruction>(Op); 7796 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7797 7798 PHINode *P = dyn_cast<PHINode>(OpInst); 7799 if (!P) 7800 // If this operand is already visited, reuse the prior result. 7801 // We may have P != PHI if this is the deepest point at which the 7802 // inconsistent paths meet. 7803 P = PHIMap.lookup(OpInst); 7804 if (!P) { 7805 // Recurse and memoize the results, whether a phi is found or not. 7806 // This recursive call invalidates pointers into PHIMap. 7807 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7808 PHIMap[OpInst] = P; 7809 } 7810 if (!P) 7811 return nullptr; // Not evolving from PHI 7812 if (PHI && PHI != P) 7813 return nullptr; // Evolving from multiple different PHIs. 7814 PHI = P; 7815 } 7816 // This is a expression evolving from a constant PHI! 7817 return PHI; 7818 } 7819 7820 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7821 /// in the loop that V is derived from. We allow arbitrary operations along the 7822 /// way, but the operands of an operation must either be constants or a value 7823 /// derived from a constant PHI. If this expression does not fit with these 7824 /// constraints, return null. 7825 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7826 Instruction *I = dyn_cast<Instruction>(V); 7827 if (!I || !canConstantEvolve(I, L)) return nullptr; 7828 7829 if (PHINode *PN = dyn_cast<PHINode>(I)) 7830 return PN; 7831 7832 // Record non-constant instructions contained by the loop. 7833 DenseMap<Instruction *, PHINode *> PHIMap; 7834 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7835 } 7836 7837 /// EvaluateExpression - Given an expression that passes the 7838 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7839 /// in the loop has the value PHIVal. If we can't fold this expression for some 7840 /// reason, return null. 7841 static Constant *EvaluateExpression(Value *V, const Loop *L, 7842 DenseMap<Instruction *, Constant *> &Vals, 7843 const DataLayout &DL, 7844 const TargetLibraryInfo *TLI) { 7845 // Convenient constant check, but redundant for recursive calls. 7846 if (Constant *C = dyn_cast<Constant>(V)) return C; 7847 Instruction *I = dyn_cast<Instruction>(V); 7848 if (!I) return nullptr; 7849 7850 if (Constant *C = Vals.lookup(I)) return C; 7851 7852 // An instruction inside the loop depends on a value outside the loop that we 7853 // weren't given a mapping for, or a value such as a call inside the loop. 7854 if (!canConstantEvolve(I, L)) return nullptr; 7855 7856 // An unmapped PHI can be due to a branch or another loop inside this loop, 7857 // or due to this not being the initial iteration through a loop where we 7858 // couldn't compute the evolution of this particular PHI last time. 7859 if (isa<PHINode>(I)) return nullptr; 7860 7861 std::vector<Constant*> Operands(I->getNumOperands()); 7862 7863 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7864 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7865 if (!Operand) { 7866 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7867 if (!Operands[i]) return nullptr; 7868 continue; 7869 } 7870 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7871 Vals[Operand] = C; 7872 if (!C) return nullptr; 7873 Operands[i] = C; 7874 } 7875 7876 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7877 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7878 Operands[1], DL, TLI); 7879 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7880 if (!LI->isVolatile()) 7881 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7882 } 7883 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7884 } 7885 7886 7887 // If every incoming value to PN except the one for BB is a specific Constant, 7888 // return that, else return nullptr. 7889 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7890 Constant *IncomingVal = nullptr; 7891 7892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7893 if (PN->getIncomingBlock(i) == BB) 7894 continue; 7895 7896 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7897 if (!CurrentVal) 7898 return nullptr; 7899 7900 if (IncomingVal != CurrentVal) { 7901 if (IncomingVal) 7902 return nullptr; 7903 IncomingVal = CurrentVal; 7904 } 7905 } 7906 7907 return IncomingVal; 7908 } 7909 7910 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7911 /// in the header of its containing loop, we know the loop executes a 7912 /// constant number of times, and the PHI node is just a recurrence 7913 /// involving constants, fold it. 7914 Constant * 7915 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7916 const APInt &BEs, 7917 const Loop *L) { 7918 auto I = ConstantEvolutionLoopExitValue.find(PN); 7919 if (I != ConstantEvolutionLoopExitValue.end()) 7920 return I->second; 7921 7922 if (BEs.ugt(MaxBruteForceIterations)) 7923 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7924 7925 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7926 7927 DenseMap<Instruction *, Constant *> CurrentIterVals; 7928 BasicBlock *Header = L->getHeader(); 7929 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7930 7931 BasicBlock *Latch = L->getLoopLatch(); 7932 if (!Latch) 7933 return nullptr; 7934 7935 for (PHINode &PHI : Header->phis()) { 7936 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7937 CurrentIterVals[&PHI] = StartCST; 7938 } 7939 if (!CurrentIterVals.count(PN)) 7940 return RetVal = nullptr; 7941 7942 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7943 7944 // Execute the loop symbolically to determine the exit value. 7945 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7946 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7947 7948 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7949 unsigned IterationNum = 0; 7950 const DataLayout &DL = getDataLayout(); 7951 for (; ; ++IterationNum) { 7952 if (IterationNum == NumIterations) 7953 return RetVal = CurrentIterVals[PN]; // Got exit value! 7954 7955 // Compute the value of the PHIs for the next iteration. 7956 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7957 DenseMap<Instruction *, Constant *> NextIterVals; 7958 Constant *NextPHI = 7959 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7960 if (!NextPHI) 7961 return nullptr; // Couldn't evaluate! 7962 NextIterVals[PN] = NextPHI; 7963 7964 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7965 7966 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7967 // cease to be able to evaluate one of them or if they stop evolving, 7968 // because that doesn't necessarily prevent us from computing PN. 7969 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7970 for (const auto &I : CurrentIterVals) { 7971 PHINode *PHI = dyn_cast<PHINode>(I.first); 7972 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7973 PHIsToCompute.emplace_back(PHI, I.second); 7974 } 7975 // We use two distinct loops because EvaluateExpression may invalidate any 7976 // iterators into CurrentIterVals. 7977 for (const auto &I : PHIsToCompute) { 7978 PHINode *PHI = I.first; 7979 Constant *&NextPHI = NextIterVals[PHI]; 7980 if (!NextPHI) { // Not already computed. 7981 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7982 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7983 } 7984 if (NextPHI != I.second) 7985 StoppedEvolving = false; 7986 } 7987 7988 // If all entries in CurrentIterVals == NextIterVals then we can stop 7989 // iterating, the loop can't continue to change. 7990 if (StoppedEvolving) 7991 return RetVal = CurrentIterVals[PN]; 7992 7993 CurrentIterVals.swap(NextIterVals); 7994 } 7995 } 7996 7997 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7998 Value *Cond, 7999 bool ExitWhen) { 8000 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8001 if (!PN) return getCouldNotCompute(); 8002 8003 // If the loop is canonicalized, the PHI will have exactly two entries. 8004 // That's the only form we support here. 8005 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8006 8007 DenseMap<Instruction *, Constant *> CurrentIterVals; 8008 BasicBlock *Header = L->getHeader(); 8009 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8010 8011 BasicBlock *Latch = L->getLoopLatch(); 8012 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8013 8014 for (PHINode &PHI : Header->phis()) { 8015 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8016 CurrentIterVals[&PHI] = StartCST; 8017 } 8018 if (!CurrentIterVals.count(PN)) 8019 return getCouldNotCompute(); 8020 8021 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8022 // the loop symbolically to determine when the condition gets a value of 8023 // "ExitWhen". 8024 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8025 const DataLayout &DL = getDataLayout(); 8026 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8027 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8028 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8029 8030 // Couldn't symbolically evaluate. 8031 if (!CondVal) return getCouldNotCompute(); 8032 8033 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8034 ++NumBruteForceTripCountsComputed; 8035 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8036 } 8037 8038 // Update all the PHI nodes for the next iteration. 8039 DenseMap<Instruction *, Constant *> NextIterVals; 8040 8041 // Create a list of which PHIs we need to compute. We want to do this before 8042 // calling EvaluateExpression on them because that may invalidate iterators 8043 // into CurrentIterVals. 8044 SmallVector<PHINode *, 8> PHIsToCompute; 8045 for (const auto &I : CurrentIterVals) { 8046 PHINode *PHI = dyn_cast<PHINode>(I.first); 8047 if (!PHI || PHI->getParent() != Header) continue; 8048 PHIsToCompute.push_back(PHI); 8049 } 8050 for (PHINode *PHI : PHIsToCompute) { 8051 Constant *&NextPHI = NextIterVals[PHI]; 8052 if (NextPHI) continue; // Already computed! 8053 8054 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8055 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8056 } 8057 CurrentIterVals.swap(NextIterVals); 8058 } 8059 8060 // Too many iterations were needed to evaluate. 8061 return getCouldNotCompute(); 8062 } 8063 8064 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8065 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8066 ValuesAtScopes[V]; 8067 // Check to see if we've folded this expression at this loop before. 8068 for (auto &LS : Values) 8069 if (LS.first == L) 8070 return LS.second ? LS.second : V; 8071 8072 Values.emplace_back(L, nullptr); 8073 8074 // Otherwise compute it. 8075 const SCEV *C = computeSCEVAtScope(V, L); 8076 for (auto &LS : reverse(ValuesAtScopes[V])) 8077 if (LS.first == L) { 8078 LS.second = C; 8079 break; 8080 } 8081 return C; 8082 } 8083 8084 /// This builds up a Constant using the ConstantExpr interface. That way, we 8085 /// will return Constants for objects which aren't represented by a 8086 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8087 /// Returns NULL if the SCEV isn't representable as a Constant. 8088 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8089 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8090 case scCouldNotCompute: 8091 case scAddRecExpr: 8092 break; 8093 case scConstant: 8094 return cast<SCEVConstant>(V)->getValue(); 8095 case scUnknown: 8096 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8097 case scSignExtend: { 8098 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8099 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8100 return ConstantExpr::getSExt(CastOp, SS->getType()); 8101 break; 8102 } 8103 case scZeroExtend: { 8104 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8105 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8106 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8107 break; 8108 } 8109 case scTruncate: { 8110 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8111 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8112 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8113 break; 8114 } 8115 case scAddExpr: { 8116 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8117 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8118 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8119 unsigned AS = PTy->getAddressSpace(); 8120 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8121 C = ConstantExpr::getBitCast(C, DestPtrTy); 8122 } 8123 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8124 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8125 if (!C2) return nullptr; 8126 8127 // First pointer! 8128 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8129 unsigned AS = C2->getType()->getPointerAddressSpace(); 8130 std::swap(C, C2); 8131 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8132 // The offsets have been converted to bytes. We can add bytes to an 8133 // i8* by GEP with the byte count in the first index. 8134 C = ConstantExpr::getBitCast(C, DestPtrTy); 8135 } 8136 8137 // Don't bother trying to sum two pointers. We probably can't 8138 // statically compute a load that results from it anyway. 8139 if (C2->getType()->isPointerTy()) 8140 return nullptr; 8141 8142 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8143 if (PTy->getElementType()->isStructTy()) 8144 C2 = ConstantExpr::getIntegerCast( 8145 C2, Type::getInt32Ty(C->getContext()), true); 8146 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8147 } else 8148 C = ConstantExpr::getAdd(C, C2); 8149 } 8150 return C; 8151 } 8152 break; 8153 } 8154 case scMulExpr: { 8155 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8156 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8157 // Don't bother with pointers at all. 8158 if (C->getType()->isPointerTy()) return nullptr; 8159 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8160 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8161 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8162 C = ConstantExpr::getMul(C, C2); 8163 } 8164 return C; 8165 } 8166 break; 8167 } 8168 case scUDivExpr: { 8169 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8170 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8171 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8172 if (LHS->getType() == RHS->getType()) 8173 return ConstantExpr::getUDiv(LHS, RHS); 8174 break; 8175 } 8176 case scSMaxExpr: 8177 case scUMaxExpr: 8178 case scSMinExpr: 8179 case scUMinExpr: 8180 break; // TODO: smax, umax, smin, umax. 8181 } 8182 return nullptr; 8183 } 8184 8185 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8186 if (isa<SCEVConstant>(V)) return V; 8187 8188 // If this instruction is evolved from a constant-evolving PHI, compute the 8189 // exit value from the loop without using SCEVs. 8190 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8191 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8192 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8193 const Loop *LI = this->LI[I->getParent()]; 8194 // Looking for loop exit value. 8195 if (LI && LI->getParentLoop() == L && 8196 PN->getParent() == LI->getHeader()) { 8197 // Okay, there is no closed form solution for the PHI node. Check 8198 // to see if the loop that contains it has a known backedge-taken 8199 // count. If so, we may be able to force computation of the exit 8200 // value. 8201 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8202 // This trivial case can show up in some degenerate cases where 8203 // the incoming IR has not yet been fully simplified. 8204 if (BackedgeTakenCount->isZero()) { 8205 Value *InitValue = nullptr; 8206 bool MultipleInitValues = false; 8207 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8208 if (!LI->contains(PN->getIncomingBlock(i))) { 8209 if (!InitValue) 8210 InitValue = PN->getIncomingValue(i); 8211 else if (InitValue != PN->getIncomingValue(i)) { 8212 MultipleInitValues = true; 8213 break; 8214 } 8215 } 8216 } 8217 if (!MultipleInitValues && InitValue) 8218 return getSCEV(InitValue); 8219 } 8220 // Do we have a loop invariant value flowing around the backedge 8221 // for a loop which must execute the backedge? 8222 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8223 isKnownPositive(BackedgeTakenCount) && 8224 PN->getNumIncomingValues() == 2) { 8225 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8226 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8227 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8228 return OnBackedge; 8229 } 8230 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8231 // Okay, we know how many times the containing loop executes. If 8232 // this is a constant evolving PHI node, get the final value at 8233 // the specified iteration number. 8234 Constant *RV = 8235 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8236 if (RV) return getSCEV(RV); 8237 } 8238 } 8239 8240 // If there is a single-input Phi, evaluate it at our scope. If we can 8241 // prove that this replacement does not break LCSSA form, use new value. 8242 if (PN->getNumOperands() == 1) { 8243 const SCEV *Input = getSCEV(PN->getOperand(0)); 8244 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8245 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8246 // for the simplest case just support constants. 8247 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8248 } 8249 } 8250 8251 // Okay, this is an expression that we cannot symbolically evaluate 8252 // into a SCEV. Check to see if it's possible to symbolically evaluate 8253 // the arguments into constants, and if so, try to constant propagate the 8254 // result. This is particularly useful for computing loop exit values. 8255 if (CanConstantFold(I)) { 8256 SmallVector<Constant *, 4> Operands; 8257 bool MadeImprovement = false; 8258 for (Value *Op : I->operands()) { 8259 if (Constant *C = dyn_cast<Constant>(Op)) { 8260 Operands.push_back(C); 8261 continue; 8262 } 8263 8264 // If any of the operands is non-constant and if they are 8265 // non-integer and non-pointer, don't even try to analyze them 8266 // with scev techniques. 8267 if (!isSCEVable(Op->getType())) 8268 return V; 8269 8270 const SCEV *OrigV = getSCEV(Op); 8271 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8272 MadeImprovement |= OrigV != OpV; 8273 8274 Constant *C = BuildConstantFromSCEV(OpV); 8275 if (!C) return V; 8276 if (C->getType() != Op->getType()) 8277 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8278 Op->getType(), 8279 false), 8280 C, Op->getType()); 8281 Operands.push_back(C); 8282 } 8283 8284 // Check to see if getSCEVAtScope actually made an improvement. 8285 if (MadeImprovement) { 8286 Constant *C = nullptr; 8287 const DataLayout &DL = getDataLayout(); 8288 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8289 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8290 Operands[1], DL, &TLI); 8291 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8292 if (!LI->isVolatile()) 8293 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8294 } else 8295 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8296 if (!C) return V; 8297 return getSCEV(C); 8298 } 8299 } 8300 } 8301 8302 // This is some other type of SCEVUnknown, just return it. 8303 return V; 8304 } 8305 8306 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8307 // Avoid performing the look-up in the common case where the specified 8308 // expression has no loop-variant portions. 8309 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8310 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8311 if (OpAtScope != Comm->getOperand(i)) { 8312 // Okay, at least one of these operands is loop variant but might be 8313 // foldable. Build a new instance of the folded commutative expression. 8314 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8315 Comm->op_begin()+i); 8316 NewOps.push_back(OpAtScope); 8317 8318 for (++i; i != e; ++i) { 8319 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8320 NewOps.push_back(OpAtScope); 8321 } 8322 if (isa<SCEVAddExpr>(Comm)) 8323 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8324 if (isa<SCEVMulExpr>(Comm)) 8325 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8326 if (isa<SCEVMinMaxExpr>(Comm)) 8327 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8328 llvm_unreachable("Unknown commutative SCEV type!"); 8329 } 8330 } 8331 // If we got here, all operands are loop invariant. 8332 return Comm; 8333 } 8334 8335 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8336 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8337 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8338 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8339 return Div; // must be loop invariant 8340 return getUDivExpr(LHS, RHS); 8341 } 8342 8343 // If this is a loop recurrence for a loop that does not contain L, then we 8344 // are dealing with the final value computed by the loop. 8345 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8346 // First, attempt to evaluate each operand. 8347 // Avoid performing the look-up in the common case where the specified 8348 // expression has no loop-variant portions. 8349 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8350 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8351 if (OpAtScope == AddRec->getOperand(i)) 8352 continue; 8353 8354 // Okay, at least one of these operands is loop variant but might be 8355 // foldable. Build a new instance of the folded commutative expression. 8356 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8357 AddRec->op_begin()+i); 8358 NewOps.push_back(OpAtScope); 8359 for (++i; i != e; ++i) 8360 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8361 8362 const SCEV *FoldedRec = 8363 getAddRecExpr(NewOps, AddRec->getLoop(), 8364 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8365 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8366 // The addrec may be folded to a nonrecurrence, for example, if the 8367 // induction variable is multiplied by zero after constant folding. Go 8368 // ahead and return the folded value. 8369 if (!AddRec) 8370 return FoldedRec; 8371 break; 8372 } 8373 8374 // If the scope is outside the addrec's loop, evaluate it by using the 8375 // loop exit value of the addrec. 8376 if (!AddRec->getLoop()->contains(L)) { 8377 // To evaluate this recurrence, we need to know how many times the AddRec 8378 // loop iterates. Compute this now. 8379 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8380 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8381 8382 // Then, evaluate the AddRec. 8383 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8384 } 8385 8386 return AddRec; 8387 } 8388 8389 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8390 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8391 if (Op == Cast->getOperand()) 8392 return Cast; // must be loop invariant 8393 return getZeroExtendExpr(Op, Cast->getType()); 8394 } 8395 8396 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8397 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8398 if (Op == Cast->getOperand()) 8399 return Cast; // must be loop invariant 8400 return getSignExtendExpr(Op, Cast->getType()); 8401 } 8402 8403 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8404 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8405 if (Op == Cast->getOperand()) 8406 return Cast; // must be loop invariant 8407 return getTruncateExpr(Op, Cast->getType()); 8408 } 8409 8410 llvm_unreachable("Unknown SCEV type!"); 8411 } 8412 8413 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8414 return getSCEVAtScope(getSCEV(V), L); 8415 } 8416 8417 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8418 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8419 return stripInjectiveFunctions(ZExt->getOperand()); 8420 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8421 return stripInjectiveFunctions(SExt->getOperand()); 8422 return S; 8423 } 8424 8425 /// Finds the minimum unsigned root of the following equation: 8426 /// 8427 /// A * X = B (mod N) 8428 /// 8429 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8430 /// A and B isn't important. 8431 /// 8432 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8433 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8434 ScalarEvolution &SE) { 8435 uint32_t BW = A.getBitWidth(); 8436 assert(BW == SE.getTypeSizeInBits(B->getType())); 8437 assert(A != 0 && "A must be non-zero."); 8438 8439 // 1. D = gcd(A, N) 8440 // 8441 // The gcd of A and N may have only one prime factor: 2. The number of 8442 // trailing zeros in A is its multiplicity 8443 uint32_t Mult2 = A.countTrailingZeros(); 8444 // D = 2^Mult2 8445 8446 // 2. Check if B is divisible by D. 8447 // 8448 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8449 // is not less than multiplicity of this prime factor for D. 8450 if (SE.GetMinTrailingZeros(B) < Mult2) 8451 return SE.getCouldNotCompute(); 8452 8453 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8454 // modulo (N / D). 8455 // 8456 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8457 // (N / D) in general. The inverse itself always fits into BW bits, though, 8458 // so we immediately truncate it. 8459 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8460 APInt Mod(BW + 1, 0); 8461 Mod.setBit(BW - Mult2); // Mod = N / D 8462 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8463 8464 // 4. Compute the minimum unsigned root of the equation: 8465 // I * (B / D) mod (N / D) 8466 // To simplify the computation, we factor out the divide by D: 8467 // (I * B mod N) / D 8468 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8469 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8470 } 8471 8472 /// For a given quadratic addrec, generate coefficients of the corresponding 8473 /// quadratic equation, multiplied by a common value to ensure that they are 8474 /// integers. 8475 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8476 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8477 /// were multiplied by, and BitWidth is the bit width of the original addrec 8478 /// coefficients. 8479 /// This function returns None if the addrec coefficients are not compile- 8480 /// time constants. 8481 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8482 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8483 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8484 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8485 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8486 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8487 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8488 << *AddRec << '\n'); 8489 8490 // We currently can only solve this if the coefficients are constants. 8491 if (!LC || !MC || !NC) { 8492 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8493 return None; 8494 } 8495 8496 APInt L = LC->getAPInt(); 8497 APInt M = MC->getAPInt(); 8498 APInt N = NC->getAPInt(); 8499 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8500 8501 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8502 unsigned NewWidth = BitWidth + 1; 8503 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8504 << BitWidth << '\n'); 8505 // The sign-extension (as opposed to a zero-extension) here matches the 8506 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8507 N = N.sext(NewWidth); 8508 M = M.sext(NewWidth); 8509 L = L.sext(NewWidth); 8510 8511 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8512 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8513 // L+M, L+2M+N, L+3M+3N, ... 8514 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8515 // 8516 // The equation Acc = 0 is then 8517 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8518 // In a quadratic form it becomes: 8519 // N n^2 + (2M-N) n + 2L = 0. 8520 8521 APInt A = N; 8522 APInt B = 2 * M - A; 8523 APInt C = 2 * L; 8524 APInt T = APInt(NewWidth, 2); 8525 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8526 << "x + " << C << ", coeff bw: " << NewWidth 8527 << ", multiplied by " << T << '\n'); 8528 return std::make_tuple(A, B, C, T, BitWidth); 8529 } 8530 8531 /// Helper function to compare optional APInts: 8532 /// (a) if X and Y both exist, return min(X, Y), 8533 /// (b) if neither X nor Y exist, return None, 8534 /// (c) if exactly one of X and Y exists, return that value. 8535 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8536 if (X.hasValue() && Y.hasValue()) { 8537 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8538 APInt XW = X->sextOrSelf(W); 8539 APInt YW = Y->sextOrSelf(W); 8540 return XW.slt(YW) ? *X : *Y; 8541 } 8542 if (!X.hasValue() && !Y.hasValue()) 8543 return None; 8544 return X.hasValue() ? *X : *Y; 8545 } 8546 8547 /// Helper function to truncate an optional APInt to a given BitWidth. 8548 /// When solving addrec-related equations, it is preferable to return a value 8549 /// that has the same bit width as the original addrec's coefficients. If the 8550 /// solution fits in the original bit width, truncate it (except for i1). 8551 /// Returning a value of a different bit width may inhibit some optimizations. 8552 /// 8553 /// In general, a solution to a quadratic equation generated from an addrec 8554 /// may require BW+1 bits, where BW is the bit width of the addrec's 8555 /// coefficients. The reason is that the coefficients of the quadratic 8556 /// equation are BW+1 bits wide (to avoid truncation when converting from 8557 /// the addrec to the equation). 8558 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8559 if (!X.hasValue()) 8560 return None; 8561 unsigned W = X->getBitWidth(); 8562 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8563 return X->trunc(BitWidth); 8564 return X; 8565 } 8566 8567 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8568 /// iterations. The values L, M, N are assumed to be signed, and they 8569 /// should all have the same bit widths. 8570 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8571 /// where BW is the bit width of the addrec's coefficients. 8572 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8573 /// returned as such, otherwise the bit width of the returned value may 8574 /// be greater than BW. 8575 /// 8576 /// This function returns None if 8577 /// (a) the addrec coefficients are not constant, or 8578 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8579 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8580 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8581 static Optional<APInt> 8582 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8583 APInt A, B, C, M; 8584 unsigned BitWidth; 8585 auto T = GetQuadraticEquation(AddRec); 8586 if (!T.hasValue()) 8587 return None; 8588 8589 std::tie(A, B, C, M, BitWidth) = *T; 8590 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8591 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8592 if (!X.hasValue()) 8593 return None; 8594 8595 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8596 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8597 if (!V->isZero()) 8598 return None; 8599 8600 return TruncIfPossible(X, BitWidth); 8601 } 8602 8603 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8604 /// iterations. The values M, N are assumed to be signed, and they 8605 /// should all have the same bit widths. 8606 /// Find the least n such that c(n) does not belong to the given range, 8607 /// while c(n-1) does. 8608 /// 8609 /// This function returns None if 8610 /// (a) the addrec coefficients are not constant, or 8611 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8612 /// bounds of the range. 8613 static Optional<APInt> 8614 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8615 const ConstantRange &Range, ScalarEvolution &SE) { 8616 assert(AddRec->getOperand(0)->isZero() && 8617 "Starting value of addrec should be 0"); 8618 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8619 << Range << ", addrec " << *AddRec << '\n'); 8620 // This case is handled in getNumIterationsInRange. Here we can assume that 8621 // we start in the range. 8622 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8623 "Addrec's initial value should be in range"); 8624 8625 APInt A, B, C, M; 8626 unsigned BitWidth; 8627 auto T = GetQuadraticEquation(AddRec); 8628 if (!T.hasValue()) 8629 return None; 8630 8631 // Be careful about the return value: there can be two reasons for not 8632 // returning an actual number. First, if no solutions to the equations 8633 // were found, and second, if the solutions don't leave the given range. 8634 // The first case means that the actual solution is "unknown", the second 8635 // means that it's known, but not valid. If the solution is unknown, we 8636 // cannot make any conclusions. 8637 // Return a pair: the optional solution and a flag indicating if the 8638 // solution was found. 8639 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8640 // Solve for signed overflow and unsigned overflow, pick the lower 8641 // solution. 8642 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8643 << Bound << " (before multiplying by " << M << ")\n"); 8644 Bound *= M; // The quadratic equation multiplier. 8645 8646 Optional<APInt> SO = None; 8647 if (BitWidth > 1) { 8648 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8649 "signed overflow\n"); 8650 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8651 } 8652 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8653 "unsigned overflow\n"); 8654 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8655 BitWidth+1); 8656 8657 auto LeavesRange = [&] (const APInt &X) { 8658 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8659 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8660 if (Range.contains(V0->getValue())) 8661 return false; 8662 // X should be at least 1, so X-1 is non-negative. 8663 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8664 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8665 if (Range.contains(V1->getValue())) 8666 return true; 8667 return false; 8668 }; 8669 8670 // If SolveQuadraticEquationWrap returns None, it means that there can 8671 // be a solution, but the function failed to find it. We cannot treat it 8672 // as "no solution". 8673 if (!SO.hasValue() || !UO.hasValue()) 8674 return { None, false }; 8675 8676 // Check the smaller value first to see if it leaves the range. 8677 // At this point, both SO and UO must have values. 8678 Optional<APInt> Min = MinOptional(SO, UO); 8679 if (LeavesRange(*Min)) 8680 return { Min, true }; 8681 Optional<APInt> Max = Min == SO ? UO : SO; 8682 if (LeavesRange(*Max)) 8683 return { Max, true }; 8684 8685 // Solutions were found, but were eliminated, hence the "true". 8686 return { None, true }; 8687 }; 8688 8689 std::tie(A, B, C, M, BitWidth) = *T; 8690 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8691 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8692 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8693 auto SL = SolveForBoundary(Lower); 8694 auto SU = SolveForBoundary(Upper); 8695 // If any of the solutions was unknown, no meaninigful conclusions can 8696 // be made. 8697 if (!SL.second || !SU.second) 8698 return None; 8699 8700 // Claim: The correct solution is not some value between Min and Max. 8701 // 8702 // Justification: Assuming that Min and Max are different values, one of 8703 // them is when the first signed overflow happens, the other is when the 8704 // first unsigned overflow happens. Crossing the range boundary is only 8705 // possible via an overflow (treating 0 as a special case of it, modeling 8706 // an overflow as crossing k*2^W for some k). 8707 // 8708 // The interesting case here is when Min was eliminated as an invalid 8709 // solution, but Max was not. The argument is that if there was another 8710 // overflow between Min and Max, it would also have been eliminated if 8711 // it was considered. 8712 // 8713 // For a given boundary, it is possible to have two overflows of the same 8714 // type (signed/unsigned) without having the other type in between: this 8715 // can happen when the vertex of the parabola is between the iterations 8716 // corresponding to the overflows. This is only possible when the two 8717 // overflows cross k*2^W for the same k. In such case, if the second one 8718 // left the range (and was the first one to do so), the first overflow 8719 // would have to enter the range, which would mean that either we had left 8720 // the range before or that we started outside of it. Both of these cases 8721 // are contradictions. 8722 // 8723 // Claim: In the case where SolveForBoundary returns None, the correct 8724 // solution is not some value between the Max for this boundary and the 8725 // Min of the other boundary. 8726 // 8727 // Justification: Assume that we had such Max_A and Min_B corresponding 8728 // to range boundaries A and B and such that Max_A < Min_B. If there was 8729 // a solution between Max_A and Min_B, it would have to be caused by an 8730 // overflow corresponding to either A or B. It cannot correspond to B, 8731 // since Min_B is the first occurrence of such an overflow. If it 8732 // corresponded to A, it would have to be either a signed or an unsigned 8733 // overflow that is larger than both eliminated overflows for A. But 8734 // between the eliminated overflows and this overflow, the values would 8735 // cover the entire value space, thus crossing the other boundary, which 8736 // is a contradiction. 8737 8738 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8739 } 8740 8741 ScalarEvolution::ExitLimit 8742 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8743 bool AllowPredicates) { 8744 8745 // This is only used for loops with a "x != y" exit test. The exit condition 8746 // is now expressed as a single expression, V = x-y. So the exit test is 8747 // effectively V != 0. We know and take advantage of the fact that this 8748 // expression only being used in a comparison by zero context. 8749 8750 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8751 // If the value is a constant 8752 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8753 // If the value is already zero, the branch will execute zero times. 8754 if (C->getValue()->isZero()) return C; 8755 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8756 } 8757 8758 const SCEVAddRecExpr *AddRec = 8759 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8760 8761 if (!AddRec && AllowPredicates) 8762 // Try to make this an AddRec using runtime tests, in the first X 8763 // iterations of this loop, where X is the SCEV expression found by the 8764 // algorithm below. 8765 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8766 8767 if (!AddRec || AddRec->getLoop() != L) 8768 return getCouldNotCompute(); 8769 8770 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8771 // the quadratic equation to solve it. 8772 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8773 // We can only use this value if the chrec ends up with an exact zero 8774 // value at this index. When solving for "X*X != 5", for example, we 8775 // should not accept a root of 2. 8776 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8777 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8778 return ExitLimit(R, R, false, Predicates); 8779 } 8780 return getCouldNotCompute(); 8781 } 8782 8783 // Otherwise we can only handle this if it is affine. 8784 if (!AddRec->isAffine()) 8785 return getCouldNotCompute(); 8786 8787 // If this is an affine expression, the execution count of this branch is 8788 // the minimum unsigned root of the following equation: 8789 // 8790 // Start + Step*N = 0 (mod 2^BW) 8791 // 8792 // equivalent to: 8793 // 8794 // Step*N = -Start (mod 2^BW) 8795 // 8796 // where BW is the common bit width of Start and Step. 8797 8798 // Get the initial value for the loop. 8799 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8800 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8801 8802 // For now we handle only constant steps. 8803 // 8804 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8805 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8806 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8807 // We have not yet seen any such cases. 8808 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8809 if (!StepC || StepC->getValue()->isZero()) 8810 return getCouldNotCompute(); 8811 8812 // For positive steps (counting up until unsigned overflow): 8813 // N = -Start/Step (as unsigned) 8814 // For negative steps (counting down to zero): 8815 // N = Start/-Step 8816 // First compute the unsigned distance from zero in the direction of Step. 8817 bool CountDown = StepC->getAPInt().isNegative(); 8818 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8819 8820 // Handle unitary steps, which cannot wraparound. 8821 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8822 // N = Distance (as unsigned) 8823 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8824 APInt MaxBECount = getUnsignedRangeMax(Distance); 8825 8826 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8827 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8828 // case, and see if we can improve the bound. 8829 // 8830 // Explicitly handling this here is necessary because getUnsignedRange 8831 // isn't context-sensitive; it doesn't know that we only care about the 8832 // range inside the loop. 8833 const SCEV *Zero = getZero(Distance->getType()); 8834 const SCEV *One = getOne(Distance->getType()); 8835 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8836 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8837 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8838 // as "unsigned_max(Distance + 1) - 1". 8839 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8840 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8841 } 8842 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8843 } 8844 8845 // If the condition controls loop exit (the loop exits only if the expression 8846 // is true) and the addition is no-wrap we can use unsigned divide to 8847 // compute the backedge count. In this case, the step may not divide the 8848 // distance, but we don't care because if the condition is "missed" the loop 8849 // will have undefined behavior due to wrapping. 8850 if (ControlsExit && AddRec->hasNoSelfWrap() && 8851 loopHasNoAbnormalExits(AddRec->getLoop())) { 8852 const SCEV *Exact = 8853 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8854 const SCEV *Max = 8855 Exact == getCouldNotCompute() 8856 ? Exact 8857 : getConstant(getUnsignedRangeMax(Exact)); 8858 return ExitLimit(Exact, Max, false, Predicates); 8859 } 8860 8861 // Solve the general equation. 8862 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8863 getNegativeSCEV(Start), *this); 8864 const SCEV *M = E == getCouldNotCompute() 8865 ? E 8866 : getConstant(getUnsignedRangeMax(E)); 8867 return ExitLimit(E, M, false, Predicates); 8868 } 8869 8870 ScalarEvolution::ExitLimit 8871 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8872 // Loops that look like: while (X == 0) are very strange indeed. We don't 8873 // handle them yet except for the trivial case. This could be expanded in the 8874 // future as needed. 8875 8876 // If the value is a constant, check to see if it is known to be non-zero 8877 // already. If so, the backedge will execute zero times. 8878 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8879 if (!C->getValue()->isZero()) 8880 return getZero(C->getType()); 8881 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8882 } 8883 8884 // We could implement others, but I really doubt anyone writes loops like 8885 // this, and if they did, they would already be constant folded. 8886 return getCouldNotCompute(); 8887 } 8888 8889 std::pair<BasicBlock *, BasicBlock *> 8890 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8891 // If the block has a unique predecessor, then there is no path from the 8892 // predecessor to the block that does not go through the direct edge 8893 // from the predecessor to the block. 8894 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8895 return {Pred, BB}; 8896 8897 // A loop's header is defined to be a block that dominates the loop. 8898 // If the header has a unique predecessor outside the loop, it must be 8899 // a block that has exactly one successor that can reach the loop. 8900 if (Loop *L = LI.getLoopFor(BB)) 8901 return {L->getLoopPredecessor(), L->getHeader()}; 8902 8903 return {nullptr, nullptr}; 8904 } 8905 8906 /// SCEV structural equivalence is usually sufficient for testing whether two 8907 /// expressions are equal, however for the purposes of looking for a condition 8908 /// guarding a loop, it can be useful to be a little more general, since a 8909 /// front-end may have replicated the controlling expression. 8910 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8911 // Quick check to see if they are the same SCEV. 8912 if (A == B) return true; 8913 8914 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8915 // Not all instructions that are "identical" compute the same value. For 8916 // instance, two distinct alloca instructions allocating the same type are 8917 // identical and do not read memory; but compute distinct values. 8918 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8919 }; 8920 8921 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8922 // two different instructions with the same value. Check for this case. 8923 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8924 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8925 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8926 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8927 if (ComputesEqualValues(AI, BI)) 8928 return true; 8929 8930 // Otherwise assume they may have a different value. 8931 return false; 8932 } 8933 8934 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8935 const SCEV *&LHS, const SCEV *&RHS, 8936 unsigned Depth) { 8937 bool Changed = false; 8938 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8939 // '0 != 0'. 8940 auto TrivialCase = [&](bool TriviallyTrue) { 8941 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8942 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8943 return true; 8944 }; 8945 // If we hit the max recursion limit bail out. 8946 if (Depth >= 3) 8947 return false; 8948 8949 // Canonicalize a constant to the right side. 8950 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8951 // Check for both operands constant. 8952 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8953 if (ConstantExpr::getICmp(Pred, 8954 LHSC->getValue(), 8955 RHSC->getValue())->isNullValue()) 8956 return TrivialCase(false); 8957 else 8958 return TrivialCase(true); 8959 } 8960 // Otherwise swap the operands to put the constant on the right. 8961 std::swap(LHS, RHS); 8962 Pred = ICmpInst::getSwappedPredicate(Pred); 8963 Changed = true; 8964 } 8965 8966 // If we're comparing an addrec with a value which is loop-invariant in the 8967 // addrec's loop, put the addrec on the left. Also make a dominance check, 8968 // as both operands could be addrecs loop-invariant in each other's loop. 8969 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8970 const Loop *L = AR->getLoop(); 8971 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8972 std::swap(LHS, RHS); 8973 Pred = ICmpInst::getSwappedPredicate(Pred); 8974 Changed = true; 8975 } 8976 } 8977 8978 // If there's a constant operand, canonicalize comparisons with boundary 8979 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8980 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8981 const APInt &RA = RC->getAPInt(); 8982 8983 bool SimplifiedByConstantRange = false; 8984 8985 if (!ICmpInst::isEquality(Pred)) { 8986 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8987 if (ExactCR.isFullSet()) 8988 return TrivialCase(true); 8989 else if (ExactCR.isEmptySet()) 8990 return TrivialCase(false); 8991 8992 APInt NewRHS; 8993 CmpInst::Predicate NewPred; 8994 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8995 ICmpInst::isEquality(NewPred)) { 8996 // We were able to convert an inequality to an equality. 8997 Pred = NewPred; 8998 RHS = getConstant(NewRHS); 8999 Changed = SimplifiedByConstantRange = true; 9000 } 9001 } 9002 9003 if (!SimplifiedByConstantRange) { 9004 switch (Pred) { 9005 default: 9006 break; 9007 case ICmpInst::ICMP_EQ: 9008 case ICmpInst::ICMP_NE: 9009 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9010 if (!RA) 9011 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9012 if (const SCEVMulExpr *ME = 9013 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9014 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9015 ME->getOperand(0)->isAllOnesValue()) { 9016 RHS = AE->getOperand(1); 9017 LHS = ME->getOperand(1); 9018 Changed = true; 9019 } 9020 break; 9021 9022 9023 // The "Should have been caught earlier!" messages refer to the fact 9024 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9025 // should have fired on the corresponding cases, and canonicalized the 9026 // check to trivial case. 9027 9028 case ICmpInst::ICMP_UGE: 9029 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9030 Pred = ICmpInst::ICMP_UGT; 9031 RHS = getConstant(RA - 1); 9032 Changed = true; 9033 break; 9034 case ICmpInst::ICMP_ULE: 9035 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9036 Pred = ICmpInst::ICMP_ULT; 9037 RHS = getConstant(RA + 1); 9038 Changed = true; 9039 break; 9040 case ICmpInst::ICMP_SGE: 9041 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9042 Pred = ICmpInst::ICMP_SGT; 9043 RHS = getConstant(RA - 1); 9044 Changed = true; 9045 break; 9046 case ICmpInst::ICMP_SLE: 9047 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9048 Pred = ICmpInst::ICMP_SLT; 9049 RHS = getConstant(RA + 1); 9050 Changed = true; 9051 break; 9052 } 9053 } 9054 } 9055 9056 // Check for obvious equality. 9057 if (HasSameValue(LHS, RHS)) { 9058 if (ICmpInst::isTrueWhenEqual(Pred)) 9059 return TrivialCase(true); 9060 if (ICmpInst::isFalseWhenEqual(Pred)) 9061 return TrivialCase(false); 9062 } 9063 9064 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9065 // adding or subtracting 1 from one of the operands. 9066 switch (Pred) { 9067 case ICmpInst::ICMP_SLE: 9068 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9069 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9070 SCEV::FlagNSW); 9071 Pred = ICmpInst::ICMP_SLT; 9072 Changed = true; 9073 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9074 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9075 SCEV::FlagNSW); 9076 Pred = ICmpInst::ICMP_SLT; 9077 Changed = true; 9078 } 9079 break; 9080 case ICmpInst::ICMP_SGE: 9081 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9082 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9083 SCEV::FlagNSW); 9084 Pred = ICmpInst::ICMP_SGT; 9085 Changed = true; 9086 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9087 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9088 SCEV::FlagNSW); 9089 Pred = ICmpInst::ICMP_SGT; 9090 Changed = true; 9091 } 9092 break; 9093 case ICmpInst::ICMP_ULE: 9094 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9095 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9096 SCEV::FlagNUW); 9097 Pred = ICmpInst::ICMP_ULT; 9098 Changed = true; 9099 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9100 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9101 Pred = ICmpInst::ICMP_ULT; 9102 Changed = true; 9103 } 9104 break; 9105 case ICmpInst::ICMP_UGE: 9106 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9107 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9108 Pred = ICmpInst::ICMP_UGT; 9109 Changed = true; 9110 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9111 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9112 SCEV::FlagNUW); 9113 Pred = ICmpInst::ICMP_UGT; 9114 Changed = true; 9115 } 9116 break; 9117 default: 9118 break; 9119 } 9120 9121 // TODO: More simplifications are possible here. 9122 9123 // Recursively simplify until we either hit a recursion limit or nothing 9124 // changes. 9125 if (Changed) 9126 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9127 9128 return Changed; 9129 } 9130 9131 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9132 return getSignedRangeMax(S).isNegative(); 9133 } 9134 9135 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9136 return getSignedRangeMin(S).isStrictlyPositive(); 9137 } 9138 9139 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9140 return !getSignedRangeMin(S).isNegative(); 9141 } 9142 9143 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9144 return !getSignedRangeMax(S).isStrictlyPositive(); 9145 } 9146 9147 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9148 return isKnownNegative(S) || isKnownPositive(S); 9149 } 9150 9151 std::pair<const SCEV *, const SCEV *> 9152 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9153 // Compute SCEV on entry of loop L. 9154 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9155 if (Start == getCouldNotCompute()) 9156 return { Start, Start }; 9157 // Compute post increment SCEV for loop L. 9158 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9159 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9160 return { Start, PostInc }; 9161 } 9162 9163 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9164 const SCEV *LHS, const SCEV *RHS) { 9165 // First collect all loops. 9166 SmallPtrSet<const Loop *, 8> LoopsUsed; 9167 getUsedLoops(LHS, LoopsUsed); 9168 getUsedLoops(RHS, LoopsUsed); 9169 9170 if (LoopsUsed.empty()) 9171 return false; 9172 9173 // Domination relationship must be a linear order on collected loops. 9174 #ifndef NDEBUG 9175 for (auto *L1 : LoopsUsed) 9176 for (auto *L2 : LoopsUsed) 9177 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9178 DT.dominates(L2->getHeader(), L1->getHeader())) && 9179 "Domination relationship is not a linear order"); 9180 #endif 9181 9182 const Loop *MDL = 9183 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9184 [&](const Loop *L1, const Loop *L2) { 9185 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9186 }); 9187 9188 // Get init and post increment value for LHS. 9189 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9190 // if LHS contains unknown non-invariant SCEV then bail out. 9191 if (SplitLHS.first == getCouldNotCompute()) 9192 return false; 9193 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9194 // Get init and post increment value for RHS. 9195 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9196 // if RHS contains unknown non-invariant SCEV then bail out. 9197 if (SplitRHS.first == getCouldNotCompute()) 9198 return false; 9199 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9200 // It is possible that init SCEV contains an invariant load but it does 9201 // not dominate MDL and is not available at MDL loop entry, so we should 9202 // check it here. 9203 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9204 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9205 return false; 9206 9207 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9208 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9209 SplitRHS.second); 9210 } 9211 9212 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9213 const SCEV *LHS, const SCEV *RHS) { 9214 // Canonicalize the inputs first. 9215 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9216 9217 if (isKnownViaInduction(Pred, LHS, RHS)) 9218 return true; 9219 9220 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9221 return true; 9222 9223 // Otherwise see what can be done with some simple reasoning. 9224 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9225 } 9226 9227 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9228 const SCEVAddRecExpr *LHS, 9229 const SCEV *RHS) { 9230 const Loop *L = LHS->getLoop(); 9231 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9232 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9233 } 9234 9235 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9236 ICmpInst::Predicate Pred, 9237 bool &Increasing) { 9238 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9239 9240 #ifndef NDEBUG 9241 // Verify an invariant: inverting the predicate should turn a monotonically 9242 // increasing change to a monotonically decreasing one, and vice versa. 9243 bool IncreasingSwapped; 9244 bool ResultSwapped = isMonotonicPredicateImpl( 9245 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9246 9247 assert(Result == ResultSwapped && "should be able to analyze both!"); 9248 if (ResultSwapped) 9249 assert(Increasing == !IncreasingSwapped && 9250 "monotonicity should flip as we flip the predicate"); 9251 #endif 9252 9253 return Result; 9254 } 9255 9256 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9257 ICmpInst::Predicate Pred, 9258 bool &Increasing) { 9259 9260 // A zero step value for LHS means the induction variable is essentially a 9261 // loop invariant value. We don't really depend on the predicate actually 9262 // flipping from false to true (for increasing predicates, and the other way 9263 // around for decreasing predicates), all we care about is that *if* the 9264 // predicate changes then it only changes from false to true. 9265 // 9266 // A zero step value in itself is not very useful, but there may be places 9267 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9268 // as general as possible. 9269 9270 switch (Pred) { 9271 default: 9272 return false; // Conservative answer 9273 9274 case ICmpInst::ICMP_UGT: 9275 case ICmpInst::ICMP_UGE: 9276 case ICmpInst::ICMP_ULT: 9277 case ICmpInst::ICMP_ULE: 9278 if (!LHS->hasNoUnsignedWrap()) 9279 return false; 9280 9281 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9282 return true; 9283 9284 case ICmpInst::ICMP_SGT: 9285 case ICmpInst::ICMP_SGE: 9286 case ICmpInst::ICMP_SLT: 9287 case ICmpInst::ICMP_SLE: { 9288 if (!LHS->hasNoSignedWrap()) 9289 return false; 9290 9291 const SCEV *Step = LHS->getStepRecurrence(*this); 9292 9293 if (isKnownNonNegative(Step)) { 9294 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9295 return true; 9296 } 9297 9298 if (isKnownNonPositive(Step)) { 9299 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9300 return true; 9301 } 9302 9303 return false; 9304 } 9305 9306 } 9307 9308 llvm_unreachable("switch has default clause!"); 9309 } 9310 9311 bool ScalarEvolution::isLoopInvariantPredicate( 9312 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9313 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9314 const SCEV *&InvariantRHS) { 9315 9316 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9317 if (!isLoopInvariant(RHS, L)) { 9318 if (!isLoopInvariant(LHS, L)) 9319 return false; 9320 9321 std::swap(LHS, RHS); 9322 Pred = ICmpInst::getSwappedPredicate(Pred); 9323 } 9324 9325 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9326 if (!ArLHS || ArLHS->getLoop() != L) 9327 return false; 9328 9329 bool Increasing; 9330 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9331 return false; 9332 9333 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9334 // true as the loop iterates, and the backedge is control dependent on 9335 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9336 // 9337 // * if the predicate was false in the first iteration then the predicate 9338 // is never evaluated again, since the loop exits without taking the 9339 // backedge. 9340 // * if the predicate was true in the first iteration then it will 9341 // continue to be true for all future iterations since it is 9342 // monotonically increasing. 9343 // 9344 // For both the above possibilities, we can replace the loop varying 9345 // predicate with its value on the first iteration of the loop (which is 9346 // loop invariant). 9347 // 9348 // A similar reasoning applies for a monotonically decreasing predicate, by 9349 // replacing true with false and false with true in the above two bullets. 9350 9351 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9352 9353 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9354 return false; 9355 9356 InvariantPred = Pred; 9357 InvariantLHS = ArLHS->getStart(); 9358 InvariantRHS = RHS; 9359 return true; 9360 } 9361 9362 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9363 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9364 if (HasSameValue(LHS, RHS)) 9365 return ICmpInst::isTrueWhenEqual(Pred); 9366 9367 // This code is split out from isKnownPredicate because it is called from 9368 // within isLoopEntryGuardedByCond. 9369 9370 auto CheckRanges = 9371 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9372 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9373 .contains(RangeLHS); 9374 }; 9375 9376 // The check at the top of the function catches the case where the values are 9377 // known to be equal. 9378 if (Pred == CmpInst::ICMP_EQ) 9379 return false; 9380 9381 if (Pred == CmpInst::ICMP_NE) 9382 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9383 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9384 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9385 9386 if (CmpInst::isSigned(Pred)) 9387 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9388 9389 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9390 } 9391 9392 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9393 const SCEV *LHS, 9394 const SCEV *RHS) { 9395 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9396 // Return Y via OutY. 9397 auto MatchBinaryAddToConst = 9398 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9399 SCEV::NoWrapFlags ExpectedFlags) { 9400 const SCEV *NonConstOp, *ConstOp; 9401 SCEV::NoWrapFlags FlagsPresent; 9402 9403 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9404 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9405 return false; 9406 9407 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9408 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9409 }; 9410 9411 APInt C; 9412 9413 switch (Pred) { 9414 default: 9415 break; 9416 9417 case ICmpInst::ICMP_SGE: 9418 std::swap(LHS, RHS); 9419 LLVM_FALLTHROUGH; 9420 case ICmpInst::ICMP_SLE: 9421 // X s<= (X + C)<nsw> if C >= 0 9422 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9423 return true; 9424 9425 // (X + C)<nsw> s<= X if C <= 0 9426 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9427 !C.isStrictlyPositive()) 9428 return true; 9429 break; 9430 9431 case ICmpInst::ICMP_SGT: 9432 std::swap(LHS, RHS); 9433 LLVM_FALLTHROUGH; 9434 case ICmpInst::ICMP_SLT: 9435 // X s< (X + C)<nsw> if C > 0 9436 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9437 C.isStrictlyPositive()) 9438 return true; 9439 9440 // (X + C)<nsw> s< X if C < 0 9441 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9442 return true; 9443 break; 9444 } 9445 9446 return false; 9447 } 9448 9449 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9450 const SCEV *LHS, 9451 const SCEV *RHS) { 9452 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9453 return false; 9454 9455 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9456 // the stack can result in exponential time complexity. 9457 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9458 9459 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9460 // 9461 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9462 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9463 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9464 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9465 // use isKnownPredicate later if needed. 9466 return isKnownNonNegative(RHS) && 9467 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9468 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9469 } 9470 9471 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9472 ICmpInst::Predicate Pred, 9473 const SCEV *LHS, const SCEV *RHS) { 9474 // No need to even try if we know the module has no guards. 9475 if (!HasGuards) 9476 return false; 9477 9478 return any_of(*BB, [&](Instruction &I) { 9479 using namespace llvm::PatternMatch; 9480 9481 Value *Condition; 9482 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9483 m_Value(Condition))) && 9484 isImpliedCond(Pred, LHS, RHS, Condition, false); 9485 }); 9486 } 9487 9488 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9489 /// protected by a conditional between LHS and RHS. This is used to 9490 /// to eliminate casts. 9491 bool 9492 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9493 ICmpInst::Predicate Pred, 9494 const SCEV *LHS, const SCEV *RHS) { 9495 // Interpret a null as meaning no loop, where there is obviously no guard 9496 // (interprocedural conditions notwithstanding). 9497 if (!L) return true; 9498 9499 if (VerifyIR) 9500 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9501 "This cannot be done on broken IR!"); 9502 9503 9504 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9505 return true; 9506 9507 BasicBlock *Latch = L->getLoopLatch(); 9508 if (!Latch) 9509 return false; 9510 9511 BranchInst *LoopContinuePredicate = 9512 dyn_cast<BranchInst>(Latch->getTerminator()); 9513 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9514 isImpliedCond(Pred, LHS, RHS, 9515 LoopContinuePredicate->getCondition(), 9516 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9517 return true; 9518 9519 // We don't want more than one activation of the following loops on the stack 9520 // -- that can lead to O(n!) time complexity. 9521 if (WalkingBEDominatingConds) 9522 return false; 9523 9524 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9525 9526 // See if we can exploit a trip count to prove the predicate. 9527 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9528 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9529 if (LatchBECount != getCouldNotCompute()) { 9530 // We know that Latch branches back to the loop header exactly 9531 // LatchBECount times. This means the backdege condition at Latch is 9532 // equivalent to "{0,+,1} u< LatchBECount". 9533 Type *Ty = LatchBECount->getType(); 9534 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9535 const SCEV *LoopCounter = 9536 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9537 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9538 LatchBECount)) 9539 return true; 9540 } 9541 9542 // Check conditions due to any @llvm.assume intrinsics. 9543 for (auto &AssumeVH : AC.assumptions()) { 9544 if (!AssumeVH) 9545 continue; 9546 auto *CI = cast<CallInst>(AssumeVH); 9547 if (!DT.dominates(CI, Latch->getTerminator())) 9548 continue; 9549 9550 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9551 return true; 9552 } 9553 9554 // If the loop is not reachable from the entry block, we risk running into an 9555 // infinite loop as we walk up into the dom tree. These loops do not matter 9556 // anyway, so we just return a conservative answer when we see them. 9557 if (!DT.isReachableFromEntry(L->getHeader())) 9558 return false; 9559 9560 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9561 return true; 9562 9563 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9564 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9565 assert(DTN && "should reach the loop header before reaching the root!"); 9566 9567 BasicBlock *BB = DTN->getBlock(); 9568 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9569 return true; 9570 9571 BasicBlock *PBB = BB->getSinglePredecessor(); 9572 if (!PBB) 9573 continue; 9574 9575 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9576 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9577 continue; 9578 9579 Value *Condition = ContinuePredicate->getCondition(); 9580 9581 // If we have an edge `E` within the loop body that dominates the only 9582 // latch, the condition guarding `E` also guards the backedge. This 9583 // reasoning works only for loops with a single latch. 9584 9585 BasicBlockEdge DominatingEdge(PBB, BB); 9586 if (DominatingEdge.isSingleEdge()) { 9587 // We're constructively (and conservatively) enumerating edges within the 9588 // loop body that dominate the latch. The dominator tree better agree 9589 // with us on this: 9590 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9591 9592 if (isImpliedCond(Pred, LHS, RHS, Condition, 9593 BB != ContinuePredicate->getSuccessor(0))) 9594 return true; 9595 } 9596 } 9597 9598 return false; 9599 } 9600 9601 bool 9602 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9603 ICmpInst::Predicate Pred, 9604 const SCEV *LHS, const SCEV *RHS) { 9605 // Interpret a null as meaning no loop, where there is obviously no guard 9606 // (interprocedural conditions notwithstanding). 9607 if (!L) return false; 9608 9609 if (VerifyIR) 9610 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9611 "This cannot be done on broken IR!"); 9612 9613 // Both LHS and RHS must be available at loop entry. 9614 assert(isAvailableAtLoopEntry(LHS, L) && 9615 "LHS is not available at Loop Entry"); 9616 assert(isAvailableAtLoopEntry(RHS, L) && 9617 "RHS is not available at Loop Entry"); 9618 9619 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9620 return true; 9621 9622 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9623 // the facts (a >= b && a != b) separately. A typical situation is when the 9624 // non-strict comparison is known from ranges and non-equality is known from 9625 // dominating predicates. If we are proving strict comparison, we always try 9626 // to prove non-equality and non-strict comparison separately. 9627 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9628 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9629 bool ProvedNonStrictComparison = false; 9630 bool ProvedNonEquality = false; 9631 9632 if (ProvingStrictComparison) { 9633 ProvedNonStrictComparison = 9634 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9635 ProvedNonEquality = 9636 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9637 if (ProvedNonStrictComparison && ProvedNonEquality) 9638 return true; 9639 } 9640 9641 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9642 auto ProveViaGuard = [&](BasicBlock *Block) { 9643 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9644 return true; 9645 if (ProvingStrictComparison) { 9646 if (!ProvedNonStrictComparison) 9647 ProvedNonStrictComparison = 9648 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9649 if (!ProvedNonEquality) 9650 ProvedNonEquality = 9651 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9652 if (ProvedNonStrictComparison && ProvedNonEquality) 9653 return true; 9654 } 9655 return false; 9656 }; 9657 9658 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9659 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9660 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9661 return true; 9662 if (ProvingStrictComparison) { 9663 if (!ProvedNonStrictComparison) 9664 ProvedNonStrictComparison = 9665 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9666 if (!ProvedNonEquality) 9667 ProvedNonEquality = 9668 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9669 if (ProvedNonStrictComparison && ProvedNonEquality) 9670 return true; 9671 } 9672 return false; 9673 }; 9674 9675 // Starting at the loop predecessor, climb up the predecessor chain, as long 9676 // as there are predecessors that can be found that have unique successors 9677 // leading to the original header. 9678 for (std::pair<BasicBlock *, BasicBlock *> 9679 Pair(L->getLoopPredecessor(), L->getHeader()); 9680 Pair.first; 9681 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9682 9683 if (ProveViaGuard(Pair.first)) 9684 return true; 9685 9686 BranchInst *LoopEntryPredicate = 9687 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9688 if (!LoopEntryPredicate || 9689 LoopEntryPredicate->isUnconditional()) 9690 continue; 9691 9692 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9693 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9694 return true; 9695 } 9696 9697 // Check conditions due to any @llvm.assume intrinsics. 9698 for (auto &AssumeVH : AC.assumptions()) { 9699 if (!AssumeVH) 9700 continue; 9701 auto *CI = cast<CallInst>(AssumeVH); 9702 if (!DT.dominates(CI, L->getHeader())) 9703 continue; 9704 9705 if (ProveViaCond(CI->getArgOperand(0), false)) 9706 return true; 9707 } 9708 9709 return false; 9710 } 9711 9712 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9713 const SCEV *LHS, const SCEV *RHS, 9714 Value *FoundCondValue, 9715 bool Inverse) { 9716 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9717 return false; 9718 9719 auto ClearOnExit = 9720 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9721 9722 // Recursively handle And and Or conditions. 9723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9724 if (BO->getOpcode() == Instruction::And) { 9725 if (!Inverse) 9726 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9727 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9728 } else if (BO->getOpcode() == Instruction::Or) { 9729 if (Inverse) 9730 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9731 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9732 } 9733 } 9734 9735 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9736 if (!ICI) return false; 9737 9738 // Now that we found a conditional branch that dominates the loop or controls 9739 // the loop latch. Check to see if it is the comparison we are looking for. 9740 ICmpInst::Predicate FoundPred; 9741 if (Inverse) 9742 FoundPred = ICI->getInversePredicate(); 9743 else 9744 FoundPred = ICI->getPredicate(); 9745 9746 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9747 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9748 9749 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9750 } 9751 9752 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9753 const SCEV *RHS, 9754 ICmpInst::Predicate FoundPred, 9755 const SCEV *FoundLHS, 9756 const SCEV *FoundRHS) { 9757 // Balance the types. 9758 if (getTypeSizeInBits(LHS->getType()) < 9759 getTypeSizeInBits(FoundLHS->getType())) { 9760 if (CmpInst::isSigned(Pred)) { 9761 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9762 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9763 } else { 9764 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9765 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9766 } 9767 } else if (getTypeSizeInBits(LHS->getType()) > 9768 getTypeSizeInBits(FoundLHS->getType())) { 9769 if (CmpInst::isSigned(FoundPred)) { 9770 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9771 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9772 } else { 9773 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9774 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9775 } 9776 } 9777 9778 // Canonicalize the query to match the way instcombine will have 9779 // canonicalized the comparison. 9780 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9781 if (LHS == RHS) 9782 return CmpInst::isTrueWhenEqual(Pred); 9783 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9784 if (FoundLHS == FoundRHS) 9785 return CmpInst::isFalseWhenEqual(FoundPred); 9786 9787 // Check to see if we can make the LHS or RHS match. 9788 if (LHS == FoundRHS || RHS == FoundLHS) { 9789 if (isa<SCEVConstant>(RHS)) { 9790 std::swap(FoundLHS, FoundRHS); 9791 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9792 } else { 9793 std::swap(LHS, RHS); 9794 Pred = ICmpInst::getSwappedPredicate(Pred); 9795 } 9796 } 9797 9798 // Check whether the found predicate is the same as the desired predicate. 9799 if (FoundPred == Pred) 9800 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9801 9802 // Check whether swapping the found predicate makes it the same as the 9803 // desired predicate. 9804 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9805 if (isa<SCEVConstant>(RHS)) 9806 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9807 else 9808 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9809 RHS, LHS, FoundLHS, FoundRHS); 9810 } 9811 9812 // Unsigned comparison is the same as signed comparison when both the operands 9813 // are non-negative. 9814 if (CmpInst::isUnsigned(FoundPred) && 9815 CmpInst::getSignedPredicate(FoundPred) == Pred && 9816 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9817 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9818 9819 // Check if we can make progress by sharpening ranges. 9820 if (FoundPred == ICmpInst::ICMP_NE && 9821 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9822 9823 const SCEVConstant *C = nullptr; 9824 const SCEV *V = nullptr; 9825 9826 if (isa<SCEVConstant>(FoundLHS)) { 9827 C = cast<SCEVConstant>(FoundLHS); 9828 V = FoundRHS; 9829 } else { 9830 C = cast<SCEVConstant>(FoundRHS); 9831 V = FoundLHS; 9832 } 9833 9834 // The guarding predicate tells us that C != V. If the known range 9835 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9836 // range we consider has to correspond to same signedness as the 9837 // predicate we're interested in folding. 9838 9839 APInt Min = ICmpInst::isSigned(Pred) ? 9840 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9841 9842 if (Min == C->getAPInt()) { 9843 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9844 // This is true even if (Min + 1) wraps around -- in case of 9845 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9846 9847 APInt SharperMin = Min + 1; 9848 9849 switch (Pred) { 9850 case ICmpInst::ICMP_SGE: 9851 case ICmpInst::ICMP_UGE: 9852 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9853 // RHS, we're done. 9854 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9855 getConstant(SharperMin))) 9856 return true; 9857 LLVM_FALLTHROUGH; 9858 9859 case ICmpInst::ICMP_SGT: 9860 case ICmpInst::ICMP_UGT: 9861 // We know from the range information that (V `Pred` Min || 9862 // V == Min). We know from the guarding condition that !(V 9863 // == Min). This gives us 9864 // 9865 // V `Pred` Min || V == Min && !(V == Min) 9866 // => V `Pred` Min 9867 // 9868 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9869 9870 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9871 return true; 9872 LLVM_FALLTHROUGH; 9873 9874 default: 9875 // No change 9876 break; 9877 } 9878 } 9879 } 9880 9881 // Check whether the actual condition is beyond sufficient. 9882 if (FoundPred == ICmpInst::ICMP_EQ) 9883 if (ICmpInst::isTrueWhenEqual(Pred)) 9884 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9885 return true; 9886 if (Pred == ICmpInst::ICMP_NE) 9887 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9888 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9889 return true; 9890 9891 // Otherwise assume the worst. 9892 return false; 9893 } 9894 9895 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9896 const SCEV *&L, const SCEV *&R, 9897 SCEV::NoWrapFlags &Flags) { 9898 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9899 if (!AE || AE->getNumOperands() != 2) 9900 return false; 9901 9902 L = AE->getOperand(0); 9903 R = AE->getOperand(1); 9904 Flags = AE->getNoWrapFlags(); 9905 return true; 9906 } 9907 9908 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9909 const SCEV *Less) { 9910 // We avoid subtracting expressions here because this function is usually 9911 // fairly deep in the call stack (i.e. is called many times). 9912 9913 // X - X = 0. 9914 if (More == Less) 9915 return APInt(getTypeSizeInBits(More->getType()), 0); 9916 9917 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9918 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9919 const auto *MAR = cast<SCEVAddRecExpr>(More); 9920 9921 if (LAR->getLoop() != MAR->getLoop()) 9922 return None; 9923 9924 // We look at affine expressions only; not for correctness but to keep 9925 // getStepRecurrence cheap. 9926 if (!LAR->isAffine() || !MAR->isAffine()) 9927 return None; 9928 9929 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9930 return None; 9931 9932 Less = LAR->getStart(); 9933 More = MAR->getStart(); 9934 9935 // fall through 9936 } 9937 9938 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9939 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9940 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9941 return M - L; 9942 } 9943 9944 SCEV::NoWrapFlags Flags; 9945 const SCEV *LLess = nullptr, *RLess = nullptr; 9946 const SCEV *LMore = nullptr, *RMore = nullptr; 9947 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9948 // Compare (X + C1) vs X. 9949 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9950 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9951 if (RLess == More) 9952 return -(C1->getAPInt()); 9953 9954 // Compare X vs (X + C2). 9955 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9956 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9957 if (RMore == Less) 9958 return C2->getAPInt(); 9959 9960 // Compare (X + C1) vs (X + C2). 9961 if (C1 && C2 && RLess == RMore) 9962 return C2->getAPInt() - C1->getAPInt(); 9963 9964 return None; 9965 } 9966 9967 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9968 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9969 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9970 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9971 return false; 9972 9973 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9974 if (!AddRecLHS) 9975 return false; 9976 9977 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9978 if (!AddRecFoundLHS) 9979 return false; 9980 9981 // We'd like to let SCEV reason about control dependencies, so we constrain 9982 // both the inequalities to be about add recurrences on the same loop. This 9983 // way we can use isLoopEntryGuardedByCond later. 9984 9985 const Loop *L = AddRecFoundLHS->getLoop(); 9986 if (L != AddRecLHS->getLoop()) 9987 return false; 9988 9989 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9990 // 9991 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9992 // ... (2) 9993 // 9994 // Informal proof for (2), assuming (1) [*]: 9995 // 9996 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9997 // 9998 // Then 9999 // 10000 // FoundLHS s< FoundRHS s< INT_MIN - C 10001 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10002 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10003 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10004 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10005 // <=> FoundLHS + C s< FoundRHS + C 10006 // 10007 // [*]: (1) can be proved by ruling out overflow. 10008 // 10009 // [**]: This can be proved by analyzing all the four possibilities: 10010 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10011 // (A s>= 0, B s>= 0). 10012 // 10013 // Note: 10014 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10015 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10016 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10017 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10018 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10019 // C)". 10020 10021 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10022 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10023 if (!LDiff || !RDiff || *LDiff != *RDiff) 10024 return false; 10025 10026 if (LDiff->isMinValue()) 10027 return true; 10028 10029 APInt FoundRHSLimit; 10030 10031 if (Pred == CmpInst::ICMP_ULT) { 10032 FoundRHSLimit = -(*RDiff); 10033 } else { 10034 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10035 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10036 } 10037 10038 // Try to prove (1) or (2), as needed. 10039 return isAvailableAtLoopEntry(FoundRHS, L) && 10040 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10041 getConstant(FoundRHSLimit)); 10042 } 10043 10044 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10045 const SCEV *LHS, const SCEV *RHS, 10046 const SCEV *FoundLHS, 10047 const SCEV *FoundRHS, unsigned Depth) { 10048 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10049 10050 auto ClearOnExit = make_scope_exit([&]() { 10051 if (LPhi) { 10052 bool Erased = PendingMerges.erase(LPhi); 10053 assert(Erased && "Failed to erase LPhi!"); 10054 (void)Erased; 10055 } 10056 if (RPhi) { 10057 bool Erased = PendingMerges.erase(RPhi); 10058 assert(Erased && "Failed to erase RPhi!"); 10059 (void)Erased; 10060 } 10061 }); 10062 10063 // Find respective Phis and check that they are not being pending. 10064 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10065 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10066 if (!PendingMerges.insert(Phi).second) 10067 return false; 10068 LPhi = Phi; 10069 } 10070 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10071 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10072 // If we detect a loop of Phi nodes being processed by this method, for 10073 // example: 10074 // 10075 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10076 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10077 // 10078 // we don't want to deal with a case that complex, so return conservative 10079 // answer false. 10080 if (!PendingMerges.insert(Phi).second) 10081 return false; 10082 RPhi = Phi; 10083 } 10084 10085 // If none of LHS, RHS is a Phi, nothing to do here. 10086 if (!LPhi && !RPhi) 10087 return false; 10088 10089 // If there is a SCEVUnknown Phi we are interested in, make it left. 10090 if (!LPhi) { 10091 std::swap(LHS, RHS); 10092 std::swap(FoundLHS, FoundRHS); 10093 std::swap(LPhi, RPhi); 10094 Pred = ICmpInst::getSwappedPredicate(Pred); 10095 } 10096 10097 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10098 const BasicBlock *LBB = LPhi->getParent(); 10099 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10100 10101 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10102 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10103 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10104 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10105 }; 10106 10107 if (RPhi && RPhi->getParent() == LBB) { 10108 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10109 // If we compare two Phis from the same block, and for each entry block 10110 // the predicate is true for incoming values from this block, then the 10111 // predicate is also true for the Phis. 10112 for (const BasicBlock *IncBB : predecessors(LBB)) { 10113 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10114 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10115 if (!ProvedEasily(L, R)) 10116 return false; 10117 } 10118 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10119 // Case two: RHS is also a Phi from the same basic block, and it is an 10120 // AddRec. It means that there is a loop which has both AddRec and Unknown 10121 // PHIs, for it we can compare incoming values of AddRec from above the loop 10122 // and latch with their respective incoming values of LPhi. 10123 // TODO: Generalize to handle loops with many inputs in a header. 10124 if (LPhi->getNumIncomingValues() != 2) return false; 10125 10126 auto *RLoop = RAR->getLoop(); 10127 auto *Predecessor = RLoop->getLoopPredecessor(); 10128 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10129 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10130 if (!ProvedEasily(L1, RAR->getStart())) 10131 return false; 10132 auto *Latch = RLoop->getLoopLatch(); 10133 assert(Latch && "Loop with AddRec with no latch?"); 10134 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10135 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10136 return false; 10137 } else { 10138 // In all other cases go over inputs of LHS and compare each of them to RHS, 10139 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10140 // At this point RHS is either a non-Phi, or it is a Phi from some block 10141 // different from LBB. 10142 for (const BasicBlock *IncBB : predecessors(LBB)) { 10143 // Check that RHS is available in this block. 10144 if (!dominates(RHS, IncBB)) 10145 return false; 10146 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10147 if (!ProvedEasily(L, RHS)) 10148 return false; 10149 } 10150 } 10151 return true; 10152 } 10153 10154 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10155 const SCEV *LHS, const SCEV *RHS, 10156 const SCEV *FoundLHS, 10157 const SCEV *FoundRHS) { 10158 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10159 return true; 10160 10161 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10162 return true; 10163 10164 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10165 FoundLHS, FoundRHS) || 10166 // ~x < ~y --> x > y 10167 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10168 getNotSCEV(FoundRHS), 10169 getNotSCEV(FoundLHS)); 10170 } 10171 10172 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10173 template <typename MinMaxExprType> 10174 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10175 const SCEV *Candidate) { 10176 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10177 if (!MinMaxExpr) 10178 return false; 10179 10180 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10181 } 10182 10183 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10184 ICmpInst::Predicate Pred, 10185 const SCEV *LHS, const SCEV *RHS) { 10186 // If both sides are affine addrecs for the same loop, with equal 10187 // steps, and we know the recurrences don't wrap, then we only 10188 // need to check the predicate on the starting values. 10189 10190 if (!ICmpInst::isRelational(Pred)) 10191 return false; 10192 10193 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10194 if (!LAR) 10195 return false; 10196 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10197 if (!RAR) 10198 return false; 10199 if (LAR->getLoop() != RAR->getLoop()) 10200 return false; 10201 if (!LAR->isAffine() || !RAR->isAffine()) 10202 return false; 10203 10204 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10205 return false; 10206 10207 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10208 SCEV::FlagNSW : SCEV::FlagNUW; 10209 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10210 return false; 10211 10212 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10213 } 10214 10215 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10216 /// expression? 10217 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10218 ICmpInst::Predicate Pred, 10219 const SCEV *LHS, const SCEV *RHS) { 10220 switch (Pred) { 10221 default: 10222 return false; 10223 10224 case ICmpInst::ICMP_SGE: 10225 std::swap(LHS, RHS); 10226 LLVM_FALLTHROUGH; 10227 case ICmpInst::ICMP_SLE: 10228 return 10229 // min(A, ...) <= A 10230 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10231 // A <= max(A, ...) 10232 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10233 10234 case ICmpInst::ICMP_UGE: 10235 std::swap(LHS, RHS); 10236 LLVM_FALLTHROUGH; 10237 case ICmpInst::ICMP_ULE: 10238 return 10239 // min(A, ...) <= A 10240 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10241 // A <= max(A, ...) 10242 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10243 } 10244 10245 llvm_unreachable("covered switch fell through?!"); 10246 } 10247 10248 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10249 const SCEV *LHS, const SCEV *RHS, 10250 const SCEV *FoundLHS, 10251 const SCEV *FoundRHS, 10252 unsigned Depth) { 10253 assert(getTypeSizeInBits(LHS->getType()) == 10254 getTypeSizeInBits(RHS->getType()) && 10255 "LHS and RHS have different sizes?"); 10256 assert(getTypeSizeInBits(FoundLHS->getType()) == 10257 getTypeSizeInBits(FoundRHS->getType()) && 10258 "FoundLHS and FoundRHS have different sizes?"); 10259 // We want to avoid hurting the compile time with analysis of too big trees. 10260 if (Depth > MaxSCEVOperationsImplicationDepth) 10261 return false; 10262 // We only want to work with ICMP_SGT comparison so far. 10263 // TODO: Extend to ICMP_UGT? 10264 if (Pred == ICmpInst::ICMP_SLT) { 10265 Pred = ICmpInst::ICMP_SGT; 10266 std::swap(LHS, RHS); 10267 std::swap(FoundLHS, FoundRHS); 10268 } 10269 if (Pred != ICmpInst::ICMP_SGT) 10270 return false; 10271 10272 auto GetOpFromSExt = [&](const SCEV *S) { 10273 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10274 return Ext->getOperand(); 10275 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10276 // the constant in some cases. 10277 return S; 10278 }; 10279 10280 // Acquire values from extensions. 10281 auto *OrigLHS = LHS; 10282 auto *OrigFoundLHS = FoundLHS; 10283 LHS = GetOpFromSExt(LHS); 10284 FoundLHS = GetOpFromSExt(FoundLHS); 10285 10286 // Is the SGT predicate can be proved trivially or using the found context. 10287 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10288 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10289 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10290 FoundRHS, Depth + 1); 10291 }; 10292 10293 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10294 // We want to avoid creation of any new non-constant SCEV. Since we are 10295 // going to compare the operands to RHS, we should be certain that we don't 10296 // need any size extensions for this. So let's decline all cases when the 10297 // sizes of types of LHS and RHS do not match. 10298 // TODO: Maybe try to get RHS from sext to catch more cases? 10299 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10300 return false; 10301 10302 // Should not overflow. 10303 if (!LHSAddExpr->hasNoSignedWrap()) 10304 return false; 10305 10306 auto *LL = LHSAddExpr->getOperand(0); 10307 auto *LR = LHSAddExpr->getOperand(1); 10308 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10309 10310 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10311 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10312 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10313 }; 10314 // Try to prove the following rule: 10315 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10316 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10317 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10318 return true; 10319 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10320 Value *LL, *LR; 10321 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10322 10323 using namespace llvm::PatternMatch; 10324 10325 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10326 // Rules for division. 10327 // We are going to perform some comparisons with Denominator and its 10328 // derivative expressions. In general case, creating a SCEV for it may 10329 // lead to a complex analysis of the entire graph, and in particular it 10330 // can request trip count recalculation for the same loop. This would 10331 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10332 // this, we only want to create SCEVs that are constants in this section. 10333 // So we bail if Denominator is not a constant. 10334 if (!isa<ConstantInt>(LR)) 10335 return false; 10336 10337 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10338 10339 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10340 // then a SCEV for the numerator already exists and matches with FoundLHS. 10341 auto *Numerator = getExistingSCEV(LL); 10342 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10343 return false; 10344 10345 // Make sure that the numerator matches with FoundLHS and the denominator 10346 // is positive. 10347 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10348 return false; 10349 10350 auto *DTy = Denominator->getType(); 10351 auto *FRHSTy = FoundRHS->getType(); 10352 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10353 // One of types is a pointer and another one is not. We cannot extend 10354 // them properly to a wider type, so let us just reject this case. 10355 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10356 // to avoid this check. 10357 return false; 10358 10359 // Given that: 10360 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10361 auto *WTy = getWiderType(DTy, FRHSTy); 10362 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10363 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10364 10365 // Try to prove the following rule: 10366 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10367 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10368 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10369 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10370 if (isKnownNonPositive(RHS) && 10371 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10372 return true; 10373 10374 // Try to prove the following rule: 10375 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10376 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10377 // If we divide it by Denominator > 2, then: 10378 // 1. If FoundLHS is negative, then the result is 0. 10379 // 2. If FoundLHS is non-negative, then the result is non-negative. 10380 // Anyways, the result is non-negative. 10381 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10382 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10383 if (isKnownNegative(RHS) && 10384 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10385 return true; 10386 } 10387 } 10388 10389 // If our expression contained SCEVUnknown Phis, and we split it down and now 10390 // need to prove something for them, try to prove the predicate for every 10391 // possible incoming values of those Phis. 10392 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10393 return true; 10394 10395 return false; 10396 } 10397 10398 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10399 const SCEV *LHS, const SCEV *RHS) { 10400 // zext x u<= sext x, sext x s<= zext x 10401 switch (Pred) { 10402 case ICmpInst::ICMP_SGE: 10403 std::swap(LHS, RHS); 10404 LLVM_FALLTHROUGH; 10405 case ICmpInst::ICMP_SLE: { 10406 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10407 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10408 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10409 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10410 return true; 10411 break; 10412 } 10413 case ICmpInst::ICMP_UGE: 10414 std::swap(LHS, RHS); 10415 LLVM_FALLTHROUGH; 10416 case ICmpInst::ICMP_ULE: { 10417 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10418 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10419 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10420 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10421 return true; 10422 break; 10423 } 10424 default: 10425 break; 10426 }; 10427 return false; 10428 } 10429 10430 bool 10431 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10432 const SCEV *LHS, const SCEV *RHS) { 10433 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10434 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10435 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10436 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10437 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10438 } 10439 10440 bool 10441 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10442 const SCEV *LHS, const SCEV *RHS, 10443 const SCEV *FoundLHS, 10444 const SCEV *FoundRHS) { 10445 switch (Pred) { 10446 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10447 case ICmpInst::ICMP_EQ: 10448 case ICmpInst::ICMP_NE: 10449 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10450 return true; 10451 break; 10452 case ICmpInst::ICMP_SLT: 10453 case ICmpInst::ICMP_SLE: 10454 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10455 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10456 return true; 10457 break; 10458 case ICmpInst::ICMP_SGT: 10459 case ICmpInst::ICMP_SGE: 10460 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10461 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10462 return true; 10463 break; 10464 case ICmpInst::ICMP_ULT: 10465 case ICmpInst::ICMP_ULE: 10466 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10467 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10468 return true; 10469 break; 10470 case ICmpInst::ICMP_UGT: 10471 case ICmpInst::ICMP_UGE: 10472 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10473 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10474 return true; 10475 break; 10476 } 10477 10478 // Maybe it can be proved via operations? 10479 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10480 return true; 10481 10482 return false; 10483 } 10484 10485 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10486 const SCEV *LHS, 10487 const SCEV *RHS, 10488 const SCEV *FoundLHS, 10489 const SCEV *FoundRHS) { 10490 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10491 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10492 // reduce the compile time impact of this optimization. 10493 return false; 10494 10495 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10496 if (!Addend) 10497 return false; 10498 10499 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10500 10501 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10502 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10503 ConstantRange FoundLHSRange = 10504 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10505 10506 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10507 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10508 10509 // We can also compute the range of values for `LHS` that satisfy the 10510 // consequent, "`LHS` `Pred` `RHS`": 10511 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10512 ConstantRange SatisfyingLHSRange = 10513 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10514 10515 // The antecedent implies the consequent if every value of `LHS` that 10516 // satisfies the antecedent also satisfies the consequent. 10517 return SatisfyingLHSRange.contains(LHSRange); 10518 } 10519 10520 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10521 bool IsSigned, bool NoWrap) { 10522 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10523 10524 if (NoWrap) return false; 10525 10526 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10527 const SCEV *One = getOne(Stride->getType()); 10528 10529 if (IsSigned) { 10530 APInt MaxRHS = getSignedRangeMax(RHS); 10531 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10532 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10533 10534 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10535 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10536 } 10537 10538 APInt MaxRHS = getUnsignedRangeMax(RHS); 10539 APInt MaxValue = APInt::getMaxValue(BitWidth); 10540 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10541 10542 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10543 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10544 } 10545 10546 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10547 bool IsSigned, bool NoWrap) { 10548 if (NoWrap) return false; 10549 10550 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10551 const SCEV *One = getOne(Stride->getType()); 10552 10553 if (IsSigned) { 10554 APInt MinRHS = getSignedRangeMin(RHS); 10555 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10556 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10557 10558 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10559 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10560 } 10561 10562 APInt MinRHS = getUnsignedRangeMin(RHS); 10563 APInt MinValue = APInt::getMinValue(BitWidth); 10564 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10565 10566 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10567 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10568 } 10569 10570 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10571 bool Equality) { 10572 const SCEV *One = getOne(Step->getType()); 10573 Delta = Equality ? getAddExpr(Delta, Step) 10574 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10575 return getUDivExpr(Delta, Step); 10576 } 10577 10578 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10579 const SCEV *Stride, 10580 const SCEV *End, 10581 unsigned BitWidth, 10582 bool IsSigned) { 10583 10584 assert(!isKnownNonPositive(Stride) && 10585 "Stride is expected strictly positive!"); 10586 // Calculate the maximum backedge count based on the range of values 10587 // permitted by Start, End, and Stride. 10588 const SCEV *MaxBECount; 10589 APInt MinStart = 10590 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10591 10592 APInt StrideForMaxBECount = 10593 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10594 10595 // We already know that the stride is positive, so we paper over conservatism 10596 // in our range computation by forcing StrideForMaxBECount to be at least one. 10597 // In theory this is unnecessary, but we expect MaxBECount to be a 10598 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10599 // is nothing to constant fold it to). 10600 APInt One(BitWidth, 1, IsSigned); 10601 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10602 10603 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10604 : APInt::getMaxValue(BitWidth); 10605 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10606 10607 // Although End can be a MAX expression we estimate MaxEnd considering only 10608 // the case End = RHS of the loop termination condition. This is safe because 10609 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10610 // taken count. 10611 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10612 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10613 10614 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10615 getConstant(StrideForMaxBECount) /* Step */, 10616 false /* Equality */); 10617 10618 return MaxBECount; 10619 } 10620 10621 ScalarEvolution::ExitLimit 10622 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10623 const Loop *L, bool IsSigned, 10624 bool ControlsExit, bool AllowPredicates) { 10625 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10626 10627 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10628 bool PredicatedIV = false; 10629 10630 if (!IV && AllowPredicates) { 10631 // Try to make this an AddRec using runtime tests, in the first X 10632 // iterations of this loop, where X is the SCEV expression found by the 10633 // algorithm below. 10634 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10635 PredicatedIV = true; 10636 } 10637 10638 // Avoid weird loops 10639 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10640 return getCouldNotCompute(); 10641 10642 bool NoWrap = ControlsExit && 10643 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10644 10645 const SCEV *Stride = IV->getStepRecurrence(*this); 10646 10647 bool PositiveStride = isKnownPositive(Stride); 10648 10649 // Avoid negative or zero stride values. 10650 if (!PositiveStride) { 10651 // We can compute the correct backedge taken count for loops with unknown 10652 // strides if we can prove that the loop is not an infinite loop with side 10653 // effects. Here's the loop structure we are trying to handle - 10654 // 10655 // i = start 10656 // do { 10657 // A[i] = i; 10658 // i += s; 10659 // } while (i < end); 10660 // 10661 // The backedge taken count for such loops is evaluated as - 10662 // (max(end, start + stride) - start - 1) /u stride 10663 // 10664 // The additional preconditions that we need to check to prove correctness 10665 // of the above formula is as follows - 10666 // 10667 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10668 // NoWrap flag). 10669 // b) loop is single exit with no side effects. 10670 // 10671 // 10672 // Precondition a) implies that if the stride is negative, this is a single 10673 // trip loop. The backedge taken count formula reduces to zero in this case. 10674 // 10675 // Precondition b) implies that the unknown stride cannot be zero otherwise 10676 // we have UB. 10677 // 10678 // The positive stride case is the same as isKnownPositive(Stride) returning 10679 // true (original behavior of the function). 10680 // 10681 // We want to make sure that the stride is truly unknown as there are edge 10682 // cases where ScalarEvolution propagates no wrap flags to the 10683 // post-increment/decrement IV even though the increment/decrement operation 10684 // itself is wrapping. The computed backedge taken count may be wrong in 10685 // such cases. This is prevented by checking that the stride is not known to 10686 // be either positive or non-positive. For example, no wrap flags are 10687 // propagated to the post-increment IV of this loop with a trip count of 2 - 10688 // 10689 // unsigned char i; 10690 // for(i=127; i<128; i+=129) 10691 // A[i] = i; 10692 // 10693 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10694 !loopHasNoSideEffects(L)) 10695 return getCouldNotCompute(); 10696 } else if (!Stride->isOne() && 10697 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10698 // Avoid proven overflow cases: this will ensure that the backedge taken 10699 // count will not generate any unsigned overflow. Relaxed no-overflow 10700 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10701 // undefined behaviors like the case of C language. 10702 return getCouldNotCompute(); 10703 10704 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10705 : ICmpInst::ICMP_ULT; 10706 const SCEV *Start = IV->getStart(); 10707 const SCEV *End = RHS; 10708 // When the RHS is not invariant, we do not know the end bound of the loop and 10709 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10710 // calculate the MaxBECount, given the start, stride and max value for the end 10711 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10712 // checked above). 10713 if (!isLoopInvariant(RHS, L)) { 10714 const SCEV *MaxBECount = computeMaxBECountForLT( 10715 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10716 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10717 false /*MaxOrZero*/, Predicates); 10718 } 10719 // If the backedge is taken at least once, then it will be taken 10720 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10721 // is the LHS value of the less-than comparison the first time it is evaluated 10722 // and End is the RHS. 10723 const SCEV *BECountIfBackedgeTaken = 10724 computeBECount(getMinusSCEV(End, Start), Stride, false); 10725 // If the loop entry is guarded by the result of the backedge test of the 10726 // first loop iteration, then we know the backedge will be taken at least 10727 // once and so the backedge taken count is as above. If not then we use the 10728 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10729 // as if the backedge is taken at least once max(End,Start) is End and so the 10730 // result is as above, and if not max(End,Start) is Start so we get a backedge 10731 // count of zero. 10732 const SCEV *BECount; 10733 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10734 BECount = BECountIfBackedgeTaken; 10735 else { 10736 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10737 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10738 } 10739 10740 const SCEV *MaxBECount; 10741 bool MaxOrZero = false; 10742 if (isa<SCEVConstant>(BECount)) 10743 MaxBECount = BECount; 10744 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10745 // If we know exactly how many times the backedge will be taken if it's 10746 // taken at least once, then the backedge count will either be that or 10747 // zero. 10748 MaxBECount = BECountIfBackedgeTaken; 10749 MaxOrZero = true; 10750 } else { 10751 MaxBECount = computeMaxBECountForLT( 10752 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10753 } 10754 10755 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10756 !isa<SCEVCouldNotCompute>(BECount)) 10757 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10758 10759 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10760 } 10761 10762 ScalarEvolution::ExitLimit 10763 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10764 const Loop *L, bool IsSigned, 10765 bool ControlsExit, bool AllowPredicates) { 10766 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10767 // We handle only IV > Invariant 10768 if (!isLoopInvariant(RHS, L)) 10769 return getCouldNotCompute(); 10770 10771 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10772 if (!IV && AllowPredicates) 10773 // Try to make this an AddRec using runtime tests, in the first X 10774 // iterations of this loop, where X is the SCEV expression found by the 10775 // algorithm below. 10776 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10777 10778 // Avoid weird loops 10779 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10780 return getCouldNotCompute(); 10781 10782 bool NoWrap = ControlsExit && 10783 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10784 10785 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10786 10787 // Avoid negative or zero stride values 10788 if (!isKnownPositive(Stride)) 10789 return getCouldNotCompute(); 10790 10791 // Avoid proven overflow cases: this will ensure that the backedge taken count 10792 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10793 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10794 // behaviors like the case of C language. 10795 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10796 return getCouldNotCompute(); 10797 10798 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10799 : ICmpInst::ICMP_UGT; 10800 10801 const SCEV *Start = IV->getStart(); 10802 const SCEV *End = RHS; 10803 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10804 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10805 10806 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10807 10808 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10809 : getUnsignedRangeMax(Start); 10810 10811 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10812 : getUnsignedRangeMin(Stride); 10813 10814 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10815 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10816 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10817 10818 // Although End can be a MIN expression we estimate MinEnd considering only 10819 // the case End = RHS. This is safe because in the other case (Start - End) 10820 // is zero, leading to a zero maximum backedge taken count. 10821 APInt MinEnd = 10822 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10823 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10824 10825 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10826 ? BECount 10827 : computeBECount(getConstant(MaxStart - MinEnd), 10828 getConstant(MinStride), false); 10829 10830 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10831 MaxBECount = BECount; 10832 10833 return ExitLimit(BECount, MaxBECount, false, Predicates); 10834 } 10835 10836 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10837 ScalarEvolution &SE) const { 10838 if (Range.isFullSet()) // Infinite loop. 10839 return SE.getCouldNotCompute(); 10840 10841 // If the start is a non-zero constant, shift the range to simplify things. 10842 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10843 if (!SC->getValue()->isZero()) { 10844 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10845 Operands[0] = SE.getZero(SC->getType()); 10846 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10847 getNoWrapFlags(FlagNW)); 10848 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10849 return ShiftedAddRec->getNumIterationsInRange( 10850 Range.subtract(SC->getAPInt()), SE); 10851 // This is strange and shouldn't happen. 10852 return SE.getCouldNotCompute(); 10853 } 10854 10855 // The only time we can solve this is when we have all constant indices. 10856 // Otherwise, we cannot determine the overflow conditions. 10857 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10858 return SE.getCouldNotCompute(); 10859 10860 // Okay at this point we know that all elements of the chrec are constants and 10861 // that the start element is zero. 10862 10863 // First check to see if the range contains zero. If not, the first 10864 // iteration exits. 10865 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10866 if (!Range.contains(APInt(BitWidth, 0))) 10867 return SE.getZero(getType()); 10868 10869 if (isAffine()) { 10870 // If this is an affine expression then we have this situation: 10871 // Solve {0,+,A} in Range === Ax in Range 10872 10873 // We know that zero is in the range. If A is positive then we know that 10874 // the upper value of the range must be the first possible exit value. 10875 // If A is negative then the lower of the range is the last possible loop 10876 // value. Also note that we already checked for a full range. 10877 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10878 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10879 10880 // The exit value should be (End+A)/A. 10881 APInt ExitVal = (End + A).udiv(A); 10882 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10883 10884 // Evaluate at the exit value. If we really did fall out of the valid 10885 // range, then we computed our trip count, otherwise wrap around or other 10886 // things must have happened. 10887 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10888 if (Range.contains(Val->getValue())) 10889 return SE.getCouldNotCompute(); // Something strange happened 10890 10891 // Ensure that the previous value is in the range. This is a sanity check. 10892 assert(Range.contains( 10893 EvaluateConstantChrecAtConstant(this, 10894 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10895 "Linear scev computation is off in a bad way!"); 10896 return SE.getConstant(ExitValue); 10897 } 10898 10899 if (isQuadratic()) { 10900 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10901 return SE.getConstant(S.getValue()); 10902 } 10903 10904 return SE.getCouldNotCompute(); 10905 } 10906 10907 const SCEVAddRecExpr * 10908 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10909 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10910 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10911 // but in this case we cannot guarantee that the value returned will be an 10912 // AddRec because SCEV does not have a fixed point where it stops 10913 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10914 // may happen if we reach arithmetic depth limit while simplifying. So we 10915 // construct the returned value explicitly. 10916 SmallVector<const SCEV *, 3> Ops; 10917 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10918 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10919 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10920 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10921 // We know that the last operand is not a constant zero (otherwise it would 10922 // have been popped out earlier). This guarantees us that if the result has 10923 // the same last operand, then it will also not be popped out, meaning that 10924 // the returned value will be an AddRec. 10925 const SCEV *Last = getOperand(getNumOperands() - 1); 10926 assert(!Last->isZero() && "Recurrency with zero step?"); 10927 Ops.push_back(Last); 10928 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10929 SCEV::FlagAnyWrap)); 10930 } 10931 10932 // Return true when S contains at least an undef value. 10933 static inline bool containsUndefs(const SCEV *S) { 10934 return SCEVExprContains(S, [](const SCEV *S) { 10935 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10936 return isa<UndefValue>(SU->getValue()); 10937 return false; 10938 }); 10939 } 10940 10941 namespace { 10942 10943 // Collect all steps of SCEV expressions. 10944 struct SCEVCollectStrides { 10945 ScalarEvolution &SE; 10946 SmallVectorImpl<const SCEV *> &Strides; 10947 10948 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10949 : SE(SE), Strides(S) {} 10950 10951 bool follow(const SCEV *S) { 10952 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10953 Strides.push_back(AR->getStepRecurrence(SE)); 10954 return true; 10955 } 10956 10957 bool isDone() const { return false; } 10958 }; 10959 10960 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10961 struct SCEVCollectTerms { 10962 SmallVectorImpl<const SCEV *> &Terms; 10963 10964 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10965 10966 bool follow(const SCEV *S) { 10967 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10968 isa<SCEVSignExtendExpr>(S)) { 10969 if (!containsUndefs(S)) 10970 Terms.push_back(S); 10971 10972 // Stop recursion: once we collected a term, do not walk its operands. 10973 return false; 10974 } 10975 10976 // Keep looking. 10977 return true; 10978 } 10979 10980 bool isDone() const { return false; } 10981 }; 10982 10983 // Check if a SCEV contains an AddRecExpr. 10984 struct SCEVHasAddRec { 10985 bool &ContainsAddRec; 10986 10987 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10988 ContainsAddRec = false; 10989 } 10990 10991 bool follow(const SCEV *S) { 10992 if (isa<SCEVAddRecExpr>(S)) { 10993 ContainsAddRec = true; 10994 10995 // Stop recursion: once we collected a term, do not walk its operands. 10996 return false; 10997 } 10998 10999 // Keep looking. 11000 return true; 11001 } 11002 11003 bool isDone() const { return false; } 11004 }; 11005 11006 // Find factors that are multiplied with an expression that (possibly as a 11007 // subexpression) contains an AddRecExpr. In the expression: 11008 // 11009 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11010 // 11011 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11012 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11013 // parameters as they form a product with an induction variable. 11014 // 11015 // This collector expects all array size parameters to be in the same MulExpr. 11016 // It might be necessary to later add support for collecting parameters that are 11017 // spread over different nested MulExpr. 11018 struct SCEVCollectAddRecMultiplies { 11019 SmallVectorImpl<const SCEV *> &Terms; 11020 ScalarEvolution &SE; 11021 11022 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11023 : Terms(T), SE(SE) {} 11024 11025 bool follow(const SCEV *S) { 11026 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11027 bool HasAddRec = false; 11028 SmallVector<const SCEV *, 0> Operands; 11029 for (auto Op : Mul->operands()) { 11030 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11031 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11032 Operands.push_back(Op); 11033 } else if (Unknown) { 11034 HasAddRec = true; 11035 } else { 11036 bool ContainsAddRec = false; 11037 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11038 visitAll(Op, ContiansAddRec); 11039 HasAddRec |= ContainsAddRec; 11040 } 11041 } 11042 if (Operands.size() == 0) 11043 return true; 11044 11045 if (!HasAddRec) 11046 return false; 11047 11048 Terms.push_back(SE.getMulExpr(Operands)); 11049 // Stop recursion: once we collected a term, do not walk its operands. 11050 return false; 11051 } 11052 11053 // Keep looking. 11054 return true; 11055 } 11056 11057 bool isDone() const { return false; } 11058 }; 11059 11060 } // end anonymous namespace 11061 11062 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11063 /// two places: 11064 /// 1) The strides of AddRec expressions. 11065 /// 2) Unknowns that are multiplied with AddRec expressions. 11066 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11067 SmallVectorImpl<const SCEV *> &Terms) { 11068 SmallVector<const SCEV *, 4> Strides; 11069 SCEVCollectStrides StrideCollector(*this, Strides); 11070 visitAll(Expr, StrideCollector); 11071 11072 LLVM_DEBUG({ 11073 dbgs() << "Strides:\n"; 11074 for (const SCEV *S : Strides) 11075 dbgs() << *S << "\n"; 11076 }); 11077 11078 for (const SCEV *S : Strides) { 11079 SCEVCollectTerms TermCollector(Terms); 11080 visitAll(S, TermCollector); 11081 } 11082 11083 LLVM_DEBUG({ 11084 dbgs() << "Terms:\n"; 11085 for (const SCEV *T : Terms) 11086 dbgs() << *T << "\n"; 11087 }); 11088 11089 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11090 visitAll(Expr, MulCollector); 11091 } 11092 11093 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11094 SmallVectorImpl<const SCEV *> &Terms, 11095 SmallVectorImpl<const SCEV *> &Sizes) { 11096 int Last = Terms.size() - 1; 11097 const SCEV *Step = Terms[Last]; 11098 11099 // End of recursion. 11100 if (Last == 0) { 11101 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11102 SmallVector<const SCEV *, 2> Qs; 11103 for (const SCEV *Op : M->operands()) 11104 if (!isa<SCEVConstant>(Op)) 11105 Qs.push_back(Op); 11106 11107 Step = SE.getMulExpr(Qs); 11108 } 11109 11110 Sizes.push_back(Step); 11111 return true; 11112 } 11113 11114 for (const SCEV *&Term : Terms) { 11115 // Normalize the terms before the next call to findArrayDimensionsRec. 11116 const SCEV *Q, *R; 11117 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11118 11119 // Bail out when GCD does not evenly divide one of the terms. 11120 if (!R->isZero()) 11121 return false; 11122 11123 Term = Q; 11124 } 11125 11126 // Remove all SCEVConstants. 11127 Terms.erase( 11128 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11129 Terms.end()); 11130 11131 if (Terms.size() > 0) 11132 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11133 return false; 11134 11135 Sizes.push_back(Step); 11136 return true; 11137 } 11138 11139 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11140 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11141 for (const SCEV *T : Terms) 11142 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11143 return true; 11144 return false; 11145 } 11146 11147 // Return the number of product terms in S. 11148 static inline int numberOfTerms(const SCEV *S) { 11149 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11150 return Expr->getNumOperands(); 11151 return 1; 11152 } 11153 11154 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11155 if (isa<SCEVConstant>(T)) 11156 return nullptr; 11157 11158 if (isa<SCEVUnknown>(T)) 11159 return T; 11160 11161 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11162 SmallVector<const SCEV *, 2> Factors; 11163 for (const SCEV *Op : M->operands()) 11164 if (!isa<SCEVConstant>(Op)) 11165 Factors.push_back(Op); 11166 11167 return SE.getMulExpr(Factors); 11168 } 11169 11170 return T; 11171 } 11172 11173 /// Return the size of an element read or written by Inst. 11174 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11175 Type *Ty; 11176 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11177 Ty = Store->getValueOperand()->getType(); 11178 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11179 Ty = Load->getType(); 11180 else 11181 return nullptr; 11182 11183 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11184 return getSizeOfExpr(ETy, Ty); 11185 } 11186 11187 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11188 SmallVectorImpl<const SCEV *> &Sizes, 11189 const SCEV *ElementSize) { 11190 if (Terms.size() < 1 || !ElementSize) 11191 return; 11192 11193 // Early return when Terms do not contain parameters: we do not delinearize 11194 // non parametric SCEVs. 11195 if (!containsParameters(Terms)) 11196 return; 11197 11198 LLVM_DEBUG({ 11199 dbgs() << "Terms:\n"; 11200 for (const SCEV *T : Terms) 11201 dbgs() << *T << "\n"; 11202 }); 11203 11204 // Remove duplicates. 11205 array_pod_sort(Terms.begin(), Terms.end()); 11206 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11207 11208 // Put larger terms first. 11209 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11210 return numberOfTerms(LHS) > numberOfTerms(RHS); 11211 }); 11212 11213 // Try to divide all terms by the element size. If term is not divisible by 11214 // element size, proceed with the original term. 11215 for (const SCEV *&Term : Terms) { 11216 const SCEV *Q, *R; 11217 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11218 if (!Q->isZero()) 11219 Term = Q; 11220 } 11221 11222 SmallVector<const SCEV *, 4> NewTerms; 11223 11224 // Remove constant factors. 11225 for (const SCEV *T : Terms) 11226 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11227 NewTerms.push_back(NewT); 11228 11229 LLVM_DEBUG({ 11230 dbgs() << "Terms after sorting:\n"; 11231 for (const SCEV *T : NewTerms) 11232 dbgs() << *T << "\n"; 11233 }); 11234 11235 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11236 Sizes.clear(); 11237 return; 11238 } 11239 11240 // The last element to be pushed into Sizes is the size of an element. 11241 Sizes.push_back(ElementSize); 11242 11243 LLVM_DEBUG({ 11244 dbgs() << "Sizes:\n"; 11245 for (const SCEV *S : Sizes) 11246 dbgs() << *S << "\n"; 11247 }); 11248 } 11249 11250 void ScalarEvolution::computeAccessFunctions( 11251 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11252 SmallVectorImpl<const SCEV *> &Sizes) { 11253 // Early exit in case this SCEV is not an affine multivariate function. 11254 if (Sizes.empty()) 11255 return; 11256 11257 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11258 if (!AR->isAffine()) 11259 return; 11260 11261 const SCEV *Res = Expr; 11262 int Last = Sizes.size() - 1; 11263 for (int i = Last; i >= 0; i--) { 11264 const SCEV *Q, *R; 11265 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11266 11267 LLVM_DEBUG({ 11268 dbgs() << "Res: " << *Res << "\n"; 11269 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11270 dbgs() << "Res divided by Sizes[i]:\n"; 11271 dbgs() << "Quotient: " << *Q << "\n"; 11272 dbgs() << "Remainder: " << *R << "\n"; 11273 }); 11274 11275 Res = Q; 11276 11277 // Do not record the last subscript corresponding to the size of elements in 11278 // the array. 11279 if (i == Last) { 11280 11281 // Bail out if the remainder is too complex. 11282 if (isa<SCEVAddRecExpr>(R)) { 11283 Subscripts.clear(); 11284 Sizes.clear(); 11285 return; 11286 } 11287 11288 continue; 11289 } 11290 11291 // Record the access function for the current subscript. 11292 Subscripts.push_back(R); 11293 } 11294 11295 // Also push in last position the remainder of the last division: it will be 11296 // the access function of the innermost dimension. 11297 Subscripts.push_back(Res); 11298 11299 std::reverse(Subscripts.begin(), Subscripts.end()); 11300 11301 LLVM_DEBUG({ 11302 dbgs() << "Subscripts:\n"; 11303 for (const SCEV *S : Subscripts) 11304 dbgs() << *S << "\n"; 11305 }); 11306 } 11307 11308 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11309 /// sizes of an array access. Returns the remainder of the delinearization that 11310 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11311 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11312 /// expressions in the stride and base of a SCEV corresponding to the 11313 /// computation of a GCD (greatest common divisor) of base and stride. When 11314 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11315 /// 11316 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11317 /// 11318 /// void foo(long n, long m, long o, double A[n][m][o]) { 11319 /// 11320 /// for (long i = 0; i < n; i++) 11321 /// for (long j = 0; j < m; j++) 11322 /// for (long k = 0; k < o; k++) 11323 /// A[i][j][k] = 1.0; 11324 /// } 11325 /// 11326 /// the delinearization input is the following AddRec SCEV: 11327 /// 11328 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11329 /// 11330 /// From this SCEV, we are able to say that the base offset of the access is %A 11331 /// because it appears as an offset that does not divide any of the strides in 11332 /// the loops: 11333 /// 11334 /// CHECK: Base offset: %A 11335 /// 11336 /// and then SCEV->delinearize determines the size of some of the dimensions of 11337 /// the array as these are the multiples by which the strides are happening: 11338 /// 11339 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11340 /// 11341 /// Note that the outermost dimension remains of UnknownSize because there are 11342 /// no strides that would help identifying the size of the last dimension: when 11343 /// the array has been statically allocated, one could compute the size of that 11344 /// dimension by dividing the overall size of the array by the size of the known 11345 /// dimensions: %m * %o * 8. 11346 /// 11347 /// Finally delinearize provides the access functions for the array reference 11348 /// that does correspond to A[i][j][k] of the above C testcase: 11349 /// 11350 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11351 /// 11352 /// The testcases are checking the output of a function pass: 11353 /// DelinearizationPass that walks through all loads and stores of a function 11354 /// asking for the SCEV of the memory access with respect to all enclosing 11355 /// loops, calling SCEV->delinearize on that and printing the results. 11356 void ScalarEvolution::delinearize(const SCEV *Expr, 11357 SmallVectorImpl<const SCEV *> &Subscripts, 11358 SmallVectorImpl<const SCEV *> &Sizes, 11359 const SCEV *ElementSize) { 11360 // First step: collect parametric terms. 11361 SmallVector<const SCEV *, 4> Terms; 11362 collectParametricTerms(Expr, Terms); 11363 11364 if (Terms.empty()) 11365 return; 11366 11367 // Second step: find subscript sizes. 11368 findArrayDimensions(Terms, Sizes, ElementSize); 11369 11370 if (Sizes.empty()) 11371 return; 11372 11373 // Third step: compute the access functions for each subscript. 11374 computeAccessFunctions(Expr, Subscripts, Sizes); 11375 11376 if (Subscripts.empty()) 11377 return; 11378 11379 LLVM_DEBUG({ 11380 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11381 dbgs() << "ArrayDecl[UnknownSize]"; 11382 for (const SCEV *S : Sizes) 11383 dbgs() << "[" << *S << "]"; 11384 11385 dbgs() << "\nArrayRef"; 11386 for (const SCEV *S : Subscripts) 11387 dbgs() << "[" << *S << "]"; 11388 dbgs() << "\n"; 11389 }); 11390 } 11391 11392 //===----------------------------------------------------------------------===// 11393 // SCEVCallbackVH Class Implementation 11394 //===----------------------------------------------------------------------===// 11395 11396 void ScalarEvolution::SCEVCallbackVH::deleted() { 11397 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11398 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11399 SE->ConstantEvolutionLoopExitValue.erase(PN); 11400 SE->eraseValueFromMap(getValPtr()); 11401 // this now dangles! 11402 } 11403 11404 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11405 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11406 11407 // Forget all the expressions associated with users of the old value, 11408 // so that future queries will recompute the expressions using the new 11409 // value. 11410 Value *Old = getValPtr(); 11411 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11412 SmallPtrSet<User *, 8> Visited; 11413 while (!Worklist.empty()) { 11414 User *U = Worklist.pop_back_val(); 11415 // Deleting the Old value will cause this to dangle. Postpone 11416 // that until everything else is done. 11417 if (U == Old) 11418 continue; 11419 if (!Visited.insert(U).second) 11420 continue; 11421 if (PHINode *PN = dyn_cast<PHINode>(U)) 11422 SE->ConstantEvolutionLoopExitValue.erase(PN); 11423 SE->eraseValueFromMap(U); 11424 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11425 } 11426 // Delete the Old value. 11427 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11428 SE->ConstantEvolutionLoopExitValue.erase(PN); 11429 SE->eraseValueFromMap(Old); 11430 // this now dangles! 11431 } 11432 11433 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11434 : CallbackVH(V), SE(se) {} 11435 11436 //===----------------------------------------------------------------------===// 11437 // ScalarEvolution Class Implementation 11438 //===----------------------------------------------------------------------===// 11439 11440 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11441 AssumptionCache &AC, DominatorTree &DT, 11442 LoopInfo &LI) 11443 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11444 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11445 LoopDispositions(64), BlockDispositions(64) { 11446 // To use guards for proving predicates, we need to scan every instruction in 11447 // relevant basic blocks, and not just terminators. Doing this is a waste of 11448 // time if the IR does not actually contain any calls to 11449 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11450 // 11451 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11452 // to _add_ guards to the module when there weren't any before, and wants 11453 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11454 // efficient in lieu of being smart in that rather obscure case. 11455 11456 auto *GuardDecl = F.getParent()->getFunction( 11457 Intrinsic::getName(Intrinsic::experimental_guard)); 11458 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11459 } 11460 11461 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11462 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11463 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11464 ValueExprMap(std::move(Arg.ValueExprMap)), 11465 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11466 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11467 PendingMerges(std::move(Arg.PendingMerges)), 11468 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11469 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11470 PredicatedBackedgeTakenCounts( 11471 std::move(Arg.PredicatedBackedgeTakenCounts)), 11472 ConstantEvolutionLoopExitValue( 11473 std::move(Arg.ConstantEvolutionLoopExitValue)), 11474 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11475 LoopDispositions(std::move(Arg.LoopDispositions)), 11476 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11477 BlockDispositions(std::move(Arg.BlockDispositions)), 11478 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11479 SignedRanges(std::move(Arg.SignedRanges)), 11480 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11481 UniquePreds(std::move(Arg.UniquePreds)), 11482 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11483 LoopUsers(std::move(Arg.LoopUsers)), 11484 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11485 FirstUnknown(Arg.FirstUnknown) { 11486 Arg.FirstUnknown = nullptr; 11487 } 11488 11489 ScalarEvolution::~ScalarEvolution() { 11490 // Iterate through all the SCEVUnknown instances and call their 11491 // destructors, so that they release their references to their values. 11492 for (SCEVUnknown *U = FirstUnknown; U;) { 11493 SCEVUnknown *Tmp = U; 11494 U = U->Next; 11495 Tmp->~SCEVUnknown(); 11496 } 11497 FirstUnknown = nullptr; 11498 11499 ExprValueMap.clear(); 11500 ValueExprMap.clear(); 11501 HasRecMap.clear(); 11502 11503 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11504 // that a loop had multiple computable exits. 11505 for (auto &BTCI : BackedgeTakenCounts) 11506 BTCI.second.clear(); 11507 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11508 BTCI.second.clear(); 11509 11510 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11511 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11512 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11513 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11514 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11515 } 11516 11517 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11518 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11519 } 11520 11521 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11522 const Loop *L) { 11523 // Print all inner loops first 11524 for (Loop *I : *L) 11525 PrintLoopInfo(OS, SE, I); 11526 11527 OS << "Loop "; 11528 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11529 OS << ": "; 11530 11531 SmallVector<BasicBlock *, 8> ExitingBlocks; 11532 L->getExitingBlocks(ExitingBlocks); 11533 if (ExitingBlocks.size() != 1) 11534 OS << "<multiple exits> "; 11535 11536 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11537 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11538 else 11539 OS << "Unpredictable backedge-taken count.\n"; 11540 11541 if (ExitingBlocks.size() > 1) 11542 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11543 OS << " exit count for " << ExitingBlock->getName() << ": " 11544 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11545 } 11546 11547 OS << "Loop "; 11548 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11549 OS << ": "; 11550 11551 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11552 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11553 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11554 OS << ", actual taken count either this or zero."; 11555 } else { 11556 OS << "Unpredictable max backedge-taken count. "; 11557 } 11558 11559 OS << "\n" 11560 "Loop "; 11561 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11562 OS << ": "; 11563 11564 SCEVUnionPredicate Pred; 11565 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11566 if (!isa<SCEVCouldNotCompute>(PBT)) { 11567 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11568 OS << " Predicates:\n"; 11569 Pred.print(OS, 4); 11570 } else { 11571 OS << "Unpredictable predicated backedge-taken count. "; 11572 } 11573 OS << "\n"; 11574 11575 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11576 OS << "Loop "; 11577 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11578 OS << ": "; 11579 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11580 } 11581 } 11582 11583 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11584 switch (LD) { 11585 case ScalarEvolution::LoopVariant: 11586 return "Variant"; 11587 case ScalarEvolution::LoopInvariant: 11588 return "Invariant"; 11589 case ScalarEvolution::LoopComputable: 11590 return "Computable"; 11591 } 11592 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11593 } 11594 11595 void ScalarEvolution::print(raw_ostream &OS) const { 11596 // ScalarEvolution's implementation of the print method is to print 11597 // out SCEV values of all instructions that are interesting. Doing 11598 // this potentially causes it to create new SCEV objects though, 11599 // which technically conflicts with the const qualifier. This isn't 11600 // observable from outside the class though, so casting away the 11601 // const isn't dangerous. 11602 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11603 11604 if (ClassifyExpressions) { 11605 OS << "Classifying expressions for: "; 11606 F.printAsOperand(OS, /*PrintType=*/false); 11607 OS << "\n"; 11608 for (Instruction &I : instructions(F)) 11609 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11610 OS << I << '\n'; 11611 OS << " --> "; 11612 const SCEV *SV = SE.getSCEV(&I); 11613 SV->print(OS); 11614 if (!isa<SCEVCouldNotCompute>(SV)) { 11615 OS << " U: "; 11616 SE.getUnsignedRange(SV).print(OS); 11617 OS << " S: "; 11618 SE.getSignedRange(SV).print(OS); 11619 } 11620 11621 const Loop *L = LI.getLoopFor(I.getParent()); 11622 11623 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11624 if (AtUse != SV) { 11625 OS << " --> "; 11626 AtUse->print(OS); 11627 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11628 OS << " U: "; 11629 SE.getUnsignedRange(AtUse).print(OS); 11630 OS << " S: "; 11631 SE.getSignedRange(AtUse).print(OS); 11632 } 11633 } 11634 11635 if (L) { 11636 OS << "\t\t" "Exits: "; 11637 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11638 if (!SE.isLoopInvariant(ExitValue, L)) { 11639 OS << "<<Unknown>>"; 11640 } else { 11641 OS << *ExitValue; 11642 } 11643 11644 bool First = true; 11645 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11646 if (First) { 11647 OS << "\t\t" "LoopDispositions: { "; 11648 First = false; 11649 } else { 11650 OS << ", "; 11651 } 11652 11653 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11654 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11655 } 11656 11657 for (auto *InnerL : depth_first(L)) { 11658 if (InnerL == L) 11659 continue; 11660 if (First) { 11661 OS << "\t\t" "LoopDispositions: { "; 11662 First = false; 11663 } else { 11664 OS << ", "; 11665 } 11666 11667 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11668 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11669 } 11670 11671 OS << " }"; 11672 } 11673 11674 OS << "\n"; 11675 } 11676 } 11677 11678 OS << "Determining loop execution counts for: "; 11679 F.printAsOperand(OS, /*PrintType=*/false); 11680 OS << "\n"; 11681 for (Loop *I : LI) 11682 PrintLoopInfo(OS, &SE, I); 11683 } 11684 11685 ScalarEvolution::LoopDisposition 11686 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11687 auto &Values = LoopDispositions[S]; 11688 for (auto &V : Values) { 11689 if (V.getPointer() == L) 11690 return V.getInt(); 11691 } 11692 Values.emplace_back(L, LoopVariant); 11693 LoopDisposition D = computeLoopDisposition(S, L); 11694 auto &Values2 = LoopDispositions[S]; 11695 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11696 if (V.getPointer() == L) { 11697 V.setInt(D); 11698 break; 11699 } 11700 } 11701 return D; 11702 } 11703 11704 ScalarEvolution::LoopDisposition 11705 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11706 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11707 case scConstant: 11708 return LoopInvariant; 11709 case scTruncate: 11710 case scZeroExtend: 11711 case scSignExtend: 11712 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11713 case scAddRecExpr: { 11714 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11715 11716 // If L is the addrec's loop, it's computable. 11717 if (AR->getLoop() == L) 11718 return LoopComputable; 11719 11720 // Add recurrences are never invariant in the function-body (null loop). 11721 if (!L) 11722 return LoopVariant; 11723 11724 // Everything that is not defined at loop entry is variant. 11725 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11726 return LoopVariant; 11727 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11728 " dominate the contained loop's header?"); 11729 11730 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11731 if (AR->getLoop()->contains(L)) 11732 return LoopInvariant; 11733 11734 // This recurrence is variant w.r.t. L if any of its operands 11735 // are variant. 11736 for (auto *Op : AR->operands()) 11737 if (!isLoopInvariant(Op, L)) 11738 return LoopVariant; 11739 11740 // Otherwise it's loop-invariant. 11741 return LoopInvariant; 11742 } 11743 case scAddExpr: 11744 case scMulExpr: 11745 case scUMaxExpr: 11746 case scSMaxExpr: 11747 case scUMinExpr: 11748 case scSMinExpr: { 11749 bool HasVarying = false; 11750 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11751 LoopDisposition D = getLoopDisposition(Op, L); 11752 if (D == LoopVariant) 11753 return LoopVariant; 11754 if (D == LoopComputable) 11755 HasVarying = true; 11756 } 11757 return HasVarying ? LoopComputable : LoopInvariant; 11758 } 11759 case scUDivExpr: { 11760 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11761 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11762 if (LD == LoopVariant) 11763 return LoopVariant; 11764 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11765 if (RD == LoopVariant) 11766 return LoopVariant; 11767 return (LD == LoopInvariant && RD == LoopInvariant) ? 11768 LoopInvariant : LoopComputable; 11769 } 11770 case scUnknown: 11771 // All non-instruction values are loop invariant. All instructions are loop 11772 // invariant if they are not contained in the specified loop. 11773 // Instructions are never considered invariant in the function body 11774 // (null loop) because they are defined within the "loop". 11775 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11776 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11777 return LoopInvariant; 11778 case scCouldNotCompute: 11779 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11780 } 11781 llvm_unreachable("Unknown SCEV kind!"); 11782 } 11783 11784 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11785 return getLoopDisposition(S, L) == LoopInvariant; 11786 } 11787 11788 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11789 return getLoopDisposition(S, L) == LoopComputable; 11790 } 11791 11792 ScalarEvolution::BlockDisposition 11793 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11794 auto &Values = BlockDispositions[S]; 11795 for (auto &V : Values) { 11796 if (V.getPointer() == BB) 11797 return V.getInt(); 11798 } 11799 Values.emplace_back(BB, DoesNotDominateBlock); 11800 BlockDisposition D = computeBlockDisposition(S, BB); 11801 auto &Values2 = BlockDispositions[S]; 11802 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11803 if (V.getPointer() == BB) { 11804 V.setInt(D); 11805 break; 11806 } 11807 } 11808 return D; 11809 } 11810 11811 ScalarEvolution::BlockDisposition 11812 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11813 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11814 case scConstant: 11815 return ProperlyDominatesBlock; 11816 case scTruncate: 11817 case scZeroExtend: 11818 case scSignExtend: 11819 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11820 case scAddRecExpr: { 11821 // This uses a "dominates" query instead of "properly dominates" query 11822 // to test for proper dominance too, because the instruction which 11823 // produces the addrec's value is a PHI, and a PHI effectively properly 11824 // dominates its entire containing block. 11825 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11826 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11827 return DoesNotDominateBlock; 11828 11829 // Fall through into SCEVNAryExpr handling. 11830 LLVM_FALLTHROUGH; 11831 } 11832 case scAddExpr: 11833 case scMulExpr: 11834 case scUMaxExpr: 11835 case scSMaxExpr: 11836 case scUMinExpr: 11837 case scSMinExpr: { 11838 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11839 bool Proper = true; 11840 for (const SCEV *NAryOp : NAry->operands()) { 11841 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11842 if (D == DoesNotDominateBlock) 11843 return DoesNotDominateBlock; 11844 if (D == DominatesBlock) 11845 Proper = false; 11846 } 11847 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11848 } 11849 case scUDivExpr: { 11850 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11851 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11852 BlockDisposition LD = getBlockDisposition(LHS, BB); 11853 if (LD == DoesNotDominateBlock) 11854 return DoesNotDominateBlock; 11855 BlockDisposition RD = getBlockDisposition(RHS, BB); 11856 if (RD == DoesNotDominateBlock) 11857 return DoesNotDominateBlock; 11858 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11859 ProperlyDominatesBlock : DominatesBlock; 11860 } 11861 case scUnknown: 11862 if (Instruction *I = 11863 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11864 if (I->getParent() == BB) 11865 return DominatesBlock; 11866 if (DT.properlyDominates(I->getParent(), BB)) 11867 return ProperlyDominatesBlock; 11868 return DoesNotDominateBlock; 11869 } 11870 return ProperlyDominatesBlock; 11871 case scCouldNotCompute: 11872 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11873 } 11874 llvm_unreachable("Unknown SCEV kind!"); 11875 } 11876 11877 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11878 return getBlockDisposition(S, BB) >= DominatesBlock; 11879 } 11880 11881 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11882 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11883 } 11884 11885 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11886 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11887 } 11888 11889 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11890 auto IsS = [&](const SCEV *X) { return S == X; }; 11891 auto ContainsS = [&](const SCEV *X) { 11892 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11893 }; 11894 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11895 } 11896 11897 void 11898 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11899 ValuesAtScopes.erase(S); 11900 LoopDispositions.erase(S); 11901 BlockDispositions.erase(S); 11902 UnsignedRanges.erase(S); 11903 SignedRanges.erase(S); 11904 ExprValueMap.erase(S); 11905 HasRecMap.erase(S); 11906 MinTrailingZerosCache.erase(S); 11907 11908 for (auto I = PredicatedSCEVRewrites.begin(); 11909 I != PredicatedSCEVRewrites.end();) { 11910 std::pair<const SCEV *, const Loop *> Entry = I->first; 11911 if (Entry.first == S) 11912 PredicatedSCEVRewrites.erase(I++); 11913 else 11914 ++I; 11915 } 11916 11917 auto RemoveSCEVFromBackedgeMap = 11918 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11919 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11920 BackedgeTakenInfo &BEInfo = I->second; 11921 if (BEInfo.hasOperand(S, this)) { 11922 BEInfo.clear(); 11923 Map.erase(I++); 11924 } else 11925 ++I; 11926 } 11927 }; 11928 11929 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11930 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11931 } 11932 11933 void 11934 ScalarEvolution::getUsedLoops(const SCEV *S, 11935 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11936 struct FindUsedLoops { 11937 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11938 : LoopsUsed(LoopsUsed) {} 11939 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11940 bool follow(const SCEV *S) { 11941 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11942 LoopsUsed.insert(AR->getLoop()); 11943 return true; 11944 } 11945 11946 bool isDone() const { return false; } 11947 }; 11948 11949 FindUsedLoops F(LoopsUsed); 11950 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11951 } 11952 11953 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11954 SmallPtrSet<const Loop *, 8> LoopsUsed; 11955 getUsedLoops(S, LoopsUsed); 11956 for (auto *L : LoopsUsed) 11957 LoopUsers[L].push_back(S); 11958 } 11959 11960 void ScalarEvolution::verify() const { 11961 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11962 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11963 11964 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11965 11966 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11967 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11968 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11969 11970 const SCEV *visitConstant(const SCEVConstant *Constant) { 11971 return SE.getConstant(Constant->getAPInt()); 11972 } 11973 11974 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11975 return SE.getUnknown(Expr->getValue()); 11976 } 11977 11978 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11979 return SE.getCouldNotCompute(); 11980 } 11981 }; 11982 11983 SCEVMapper SCM(SE2); 11984 11985 while (!LoopStack.empty()) { 11986 auto *L = LoopStack.pop_back_val(); 11987 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11988 11989 auto *CurBECount = SCM.visit( 11990 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11991 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11992 11993 if (CurBECount == SE2.getCouldNotCompute() || 11994 NewBECount == SE2.getCouldNotCompute()) { 11995 // NB! This situation is legal, but is very suspicious -- whatever pass 11996 // change the loop to make a trip count go from could not compute to 11997 // computable or vice-versa *should have* invalidated SCEV. However, we 11998 // choose not to assert here (for now) since we don't want false 11999 // positives. 12000 continue; 12001 } 12002 12003 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12004 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12005 // not propagate undef aggressively). This means we can (and do) fail 12006 // verification in cases where a transform makes the trip count of a loop 12007 // go from "undef" to "undef+1" (say). The transform is fine, since in 12008 // both cases the loop iterates "undef" times, but SCEV thinks we 12009 // increased the trip count of the loop by 1 incorrectly. 12010 continue; 12011 } 12012 12013 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12014 SE.getTypeSizeInBits(NewBECount->getType())) 12015 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12016 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12017 SE.getTypeSizeInBits(NewBECount->getType())) 12018 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12019 12020 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12021 12022 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12023 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12024 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12025 dbgs() << "Old: " << *CurBECount << "\n"; 12026 dbgs() << "New: " << *NewBECount << "\n"; 12027 dbgs() << "Delta: " << *Delta << "\n"; 12028 std::abort(); 12029 } 12030 } 12031 } 12032 12033 bool ScalarEvolution::invalidate( 12034 Function &F, const PreservedAnalyses &PA, 12035 FunctionAnalysisManager::Invalidator &Inv) { 12036 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12037 // of its dependencies is invalidated. 12038 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12039 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12040 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12041 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12042 Inv.invalidate<LoopAnalysis>(F, PA); 12043 } 12044 12045 AnalysisKey ScalarEvolutionAnalysis::Key; 12046 12047 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12048 FunctionAnalysisManager &AM) { 12049 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12050 AM.getResult<AssumptionAnalysis>(F), 12051 AM.getResult<DominatorTreeAnalysis>(F), 12052 AM.getResult<LoopAnalysis>(F)); 12053 } 12054 12055 PreservedAnalyses 12056 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12057 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12058 return PreservedAnalyses::all(); 12059 } 12060 12061 PreservedAnalyses 12062 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12063 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12064 return PreservedAnalyses::all(); 12065 } 12066 12067 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12068 "Scalar Evolution Analysis", false, true) 12069 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12070 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12071 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12072 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12073 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12074 "Scalar Evolution Analysis", false, true) 12075 12076 char ScalarEvolutionWrapperPass::ID = 0; 12077 12078 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12079 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12080 } 12081 12082 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12083 SE.reset(new ScalarEvolution( 12084 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12085 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12086 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12087 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12088 return false; 12089 } 12090 12091 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12092 12093 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12094 SE->print(OS); 12095 } 12096 12097 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12098 if (!VerifySCEV) 12099 return; 12100 12101 SE->verify(); 12102 } 12103 12104 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12105 AU.setPreservesAll(); 12106 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12107 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12108 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12109 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12110 } 12111 12112 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12113 const SCEV *RHS) { 12114 FoldingSetNodeID ID; 12115 assert(LHS->getType() == RHS->getType() && 12116 "Type mismatch between LHS and RHS"); 12117 // Unique this node based on the arguments 12118 ID.AddInteger(SCEVPredicate::P_Equal); 12119 ID.AddPointer(LHS); 12120 ID.AddPointer(RHS); 12121 void *IP = nullptr; 12122 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12123 return S; 12124 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12125 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12126 UniquePreds.InsertNode(Eq, IP); 12127 return Eq; 12128 } 12129 12130 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12131 const SCEVAddRecExpr *AR, 12132 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12133 FoldingSetNodeID ID; 12134 // Unique this node based on the arguments 12135 ID.AddInteger(SCEVPredicate::P_Wrap); 12136 ID.AddPointer(AR); 12137 ID.AddInteger(AddedFlags); 12138 void *IP = nullptr; 12139 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12140 return S; 12141 auto *OF = new (SCEVAllocator) 12142 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12143 UniquePreds.InsertNode(OF, IP); 12144 return OF; 12145 } 12146 12147 namespace { 12148 12149 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12150 public: 12151 12152 /// Rewrites \p S in the context of a loop L and the SCEV predication 12153 /// infrastructure. 12154 /// 12155 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12156 /// equivalences present in \p Pred. 12157 /// 12158 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12159 /// \p NewPreds such that the result will be an AddRecExpr. 12160 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12161 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12162 SCEVUnionPredicate *Pred) { 12163 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12164 return Rewriter.visit(S); 12165 } 12166 12167 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12168 if (Pred) { 12169 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12170 for (auto *Pred : ExprPreds) 12171 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12172 if (IPred->getLHS() == Expr) 12173 return IPred->getRHS(); 12174 } 12175 return convertToAddRecWithPreds(Expr); 12176 } 12177 12178 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12179 const SCEV *Operand = visit(Expr->getOperand()); 12180 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12181 if (AR && AR->getLoop() == L && AR->isAffine()) { 12182 // This couldn't be folded because the operand didn't have the nuw 12183 // flag. Add the nusw flag as an assumption that we could make. 12184 const SCEV *Step = AR->getStepRecurrence(SE); 12185 Type *Ty = Expr->getType(); 12186 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12187 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12188 SE.getSignExtendExpr(Step, Ty), L, 12189 AR->getNoWrapFlags()); 12190 } 12191 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12192 } 12193 12194 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12195 const SCEV *Operand = visit(Expr->getOperand()); 12196 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12197 if (AR && AR->getLoop() == L && AR->isAffine()) { 12198 // This couldn't be folded because the operand didn't have the nsw 12199 // flag. Add the nssw flag as an assumption that we could make. 12200 const SCEV *Step = AR->getStepRecurrence(SE); 12201 Type *Ty = Expr->getType(); 12202 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12203 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12204 SE.getSignExtendExpr(Step, Ty), L, 12205 AR->getNoWrapFlags()); 12206 } 12207 return SE.getSignExtendExpr(Operand, Expr->getType()); 12208 } 12209 12210 private: 12211 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12212 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12213 SCEVUnionPredicate *Pred) 12214 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12215 12216 bool addOverflowAssumption(const SCEVPredicate *P) { 12217 if (!NewPreds) { 12218 // Check if we've already made this assumption. 12219 return Pred && Pred->implies(P); 12220 } 12221 NewPreds->insert(P); 12222 return true; 12223 } 12224 12225 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12226 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12227 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12228 return addOverflowAssumption(A); 12229 } 12230 12231 // If \p Expr represents a PHINode, we try to see if it can be represented 12232 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12233 // to add this predicate as a runtime overflow check, we return the AddRec. 12234 // If \p Expr does not meet these conditions (is not a PHI node, or we 12235 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12236 // return \p Expr. 12237 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12238 if (!isa<PHINode>(Expr->getValue())) 12239 return Expr; 12240 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12241 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12242 if (!PredicatedRewrite) 12243 return Expr; 12244 for (auto *P : PredicatedRewrite->second){ 12245 // Wrap predicates from outer loops are not supported. 12246 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12247 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12248 if (L != AR->getLoop()) 12249 return Expr; 12250 } 12251 if (!addOverflowAssumption(P)) 12252 return Expr; 12253 } 12254 return PredicatedRewrite->first; 12255 } 12256 12257 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12258 SCEVUnionPredicate *Pred; 12259 const Loop *L; 12260 }; 12261 12262 } // end anonymous namespace 12263 12264 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12265 SCEVUnionPredicate &Preds) { 12266 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12267 } 12268 12269 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12270 const SCEV *S, const Loop *L, 12271 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12272 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12273 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12274 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12275 12276 if (!AddRec) 12277 return nullptr; 12278 12279 // Since the transformation was successful, we can now transfer the SCEV 12280 // predicates. 12281 for (auto *P : TransformPreds) 12282 Preds.insert(P); 12283 12284 return AddRec; 12285 } 12286 12287 /// SCEV predicates 12288 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12289 SCEVPredicateKind Kind) 12290 : FastID(ID), Kind(Kind) {} 12291 12292 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12293 const SCEV *LHS, const SCEV *RHS) 12294 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12295 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12296 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12297 } 12298 12299 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12300 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12301 12302 if (!Op) 12303 return false; 12304 12305 return Op->LHS == LHS && Op->RHS == RHS; 12306 } 12307 12308 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12309 12310 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12311 12312 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12313 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12314 } 12315 12316 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12317 const SCEVAddRecExpr *AR, 12318 IncrementWrapFlags Flags) 12319 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12320 12321 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12322 12323 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12324 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12325 12326 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12327 } 12328 12329 bool SCEVWrapPredicate::isAlwaysTrue() const { 12330 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12331 IncrementWrapFlags IFlags = Flags; 12332 12333 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12334 IFlags = clearFlags(IFlags, IncrementNSSW); 12335 12336 return IFlags == IncrementAnyWrap; 12337 } 12338 12339 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12340 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12341 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12342 OS << "<nusw>"; 12343 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12344 OS << "<nssw>"; 12345 OS << "\n"; 12346 } 12347 12348 SCEVWrapPredicate::IncrementWrapFlags 12349 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12350 ScalarEvolution &SE) { 12351 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12352 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12353 12354 // We can safely transfer the NSW flag as NSSW. 12355 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12356 ImpliedFlags = IncrementNSSW; 12357 12358 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12359 // If the increment is positive, the SCEV NUW flag will also imply the 12360 // WrapPredicate NUSW flag. 12361 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12362 if (Step->getValue()->getValue().isNonNegative()) 12363 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12364 } 12365 12366 return ImpliedFlags; 12367 } 12368 12369 /// Union predicates don't get cached so create a dummy set ID for it. 12370 SCEVUnionPredicate::SCEVUnionPredicate() 12371 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12372 12373 bool SCEVUnionPredicate::isAlwaysTrue() const { 12374 return all_of(Preds, 12375 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12376 } 12377 12378 ArrayRef<const SCEVPredicate *> 12379 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12380 auto I = SCEVToPreds.find(Expr); 12381 if (I == SCEVToPreds.end()) 12382 return ArrayRef<const SCEVPredicate *>(); 12383 return I->second; 12384 } 12385 12386 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12387 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12388 return all_of(Set->Preds, 12389 [this](const SCEVPredicate *I) { return this->implies(I); }); 12390 12391 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12392 if (ScevPredsIt == SCEVToPreds.end()) 12393 return false; 12394 auto &SCEVPreds = ScevPredsIt->second; 12395 12396 return any_of(SCEVPreds, 12397 [N](const SCEVPredicate *I) { return I->implies(N); }); 12398 } 12399 12400 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12401 12402 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12403 for (auto Pred : Preds) 12404 Pred->print(OS, Depth); 12405 } 12406 12407 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12408 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12409 for (auto Pred : Set->Preds) 12410 add(Pred); 12411 return; 12412 } 12413 12414 if (implies(N)) 12415 return; 12416 12417 const SCEV *Key = N->getExpr(); 12418 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12419 " associated expression!"); 12420 12421 SCEVToPreds[Key].push_back(N); 12422 Preds.push_back(N); 12423 } 12424 12425 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12426 Loop &L) 12427 : SE(SE), L(L) {} 12428 12429 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12430 const SCEV *Expr = SE.getSCEV(V); 12431 RewriteEntry &Entry = RewriteMap[Expr]; 12432 12433 // If we already have an entry and the version matches, return it. 12434 if (Entry.second && Generation == Entry.first) 12435 return Entry.second; 12436 12437 // We found an entry but it's stale. Rewrite the stale entry 12438 // according to the current predicate. 12439 if (Entry.second) 12440 Expr = Entry.second; 12441 12442 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12443 Entry = {Generation, NewSCEV}; 12444 12445 return NewSCEV; 12446 } 12447 12448 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12449 if (!BackedgeCount) { 12450 SCEVUnionPredicate BackedgePred; 12451 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12452 addPredicate(BackedgePred); 12453 } 12454 return BackedgeCount; 12455 } 12456 12457 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12458 if (Preds.implies(&Pred)) 12459 return; 12460 Preds.add(&Pred); 12461 updateGeneration(); 12462 } 12463 12464 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12465 return Preds; 12466 } 12467 12468 void PredicatedScalarEvolution::updateGeneration() { 12469 // If the generation number wrapped recompute everything. 12470 if (++Generation == 0) { 12471 for (auto &II : RewriteMap) { 12472 const SCEV *Rewritten = II.second.second; 12473 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12474 } 12475 } 12476 } 12477 12478 void PredicatedScalarEvolution::setNoOverflow( 12479 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12480 const SCEV *Expr = getSCEV(V); 12481 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12482 12483 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12484 12485 // Clear the statically implied flags. 12486 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12487 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12488 12489 auto II = FlagsMap.insert({V, Flags}); 12490 if (!II.second) 12491 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12492 } 12493 12494 bool PredicatedScalarEvolution::hasNoOverflow( 12495 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12496 const SCEV *Expr = getSCEV(V); 12497 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12498 12499 Flags = SCEVWrapPredicate::clearFlags( 12500 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12501 12502 auto II = FlagsMap.find(V); 12503 12504 if (II != FlagsMap.end()) 12505 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12506 12507 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12508 } 12509 12510 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12511 const SCEV *Expr = this->getSCEV(V); 12512 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12513 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12514 12515 if (!New) 12516 return nullptr; 12517 12518 for (auto *P : NewPreds) 12519 Preds.add(P); 12520 12521 updateGeneration(); 12522 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12523 return New; 12524 } 12525 12526 PredicatedScalarEvolution::PredicatedScalarEvolution( 12527 const PredicatedScalarEvolution &Init) 12528 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12529 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12530 for (const auto &I : Init.FlagsMap) 12531 FlagsMap.insert(I); 12532 } 12533 12534 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12535 // For each block. 12536 for (auto *BB : L.getBlocks()) 12537 for (auto &I : *BB) { 12538 if (!SE.isSCEVable(I.getType())) 12539 continue; 12540 12541 auto *Expr = SE.getSCEV(&I); 12542 auto II = RewriteMap.find(Expr); 12543 12544 if (II == RewriteMap.end()) 12545 continue; 12546 12547 // Don't print things that are not interesting. 12548 if (II->second.second == Expr) 12549 continue; 12550 12551 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12552 OS.indent(Depth + 2) << *Expr << "\n"; 12553 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12554 } 12555 } 12556 12557 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12558 // arbitrary expressions. 12559 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12560 // 4, A / B becomes X / 8). 12561 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12562 const SCEV *&RHS) { 12563 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12564 if (Add == nullptr || Add->getNumOperands() != 2) 12565 return false; 12566 12567 const SCEV *A = Add->getOperand(1); 12568 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12569 12570 if (Mul == nullptr) 12571 return false; 12572 12573 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12574 // (SomeExpr + (-(SomeExpr / B) * B)). 12575 if (Expr == getURemExpr(A, B)) { 12576 LHS = A; 12577 RHS = B; 12578 return true; 12579 } 12580 return false; 12581 }; 12582 12583 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12584 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12585 return MatchURemWithDivisor(Mul->getOperand(1)) || 12586 MatchURemWithDivisor(Mul->getOperand(2)); 12587 12588 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12589 if (Mul->getNumOperands() == 2) 12590 return MatchURemWithDivisor(Mul->getOperand(1)) || 12591 MatchURemWithDivisor(Mul->getOperand(0)) || 12592 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12593 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12594 return false; 12595 } 12596