1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::desc("Maximum number of iterations SCEV will " 152 "symbolically execute a constant " 153 "derived loop"), 154 cl::init(100)); 155 156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 157 static cl::opt<bool> VerifySCEV( 158 "verify-scev", cl::Hidden, 159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 //===----------------------------------------------------------------------===// 220 // SCEV class definitions 221 //===----------------------------------------------------------------------===// 222 223 //===----------------------------------------------------------------------===// 224 // Implementation of the SCEV class. 225 // 226 227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 228 LLVM_DUMP_METHOD void SCEV::dump() const { 229 print(dbgs()); 230 dbgs() << '\n'; 231 } 232 #endif 233 234 void SCEV::print(raw_ostream &OS) const { 235 switch (static_cast<SCEVTypes>(getSCEVType())) { 236 case scConstant: 237 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 238 return; 239 case scTruncate: { 240 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 241 const SCEV *Op = Trunc->getOperand(); 242 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 243 << *Trunc->getType() << ")"; 244 return; 245 } 246 case scZeroExtend: { 247 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 248 const SCEV *Op = ZExt->getOperand(); 249 OS << "(zext " << *Op->getType() << " " << *Op << " to " 250 << *ZExt->getType() << ")"; 251 return; 252 } 253 case scSignExtend: { 254 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 255 const SCEV *Op = SExt->getOperand(); 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " 257 << *SExt->getType() << ")"; 258 return; 259 } 260 case scAddRecExpr: { 261 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 262 OS << "{" << *AR->getOperand(0); 263 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 264 OS << ",+," << *AR->getOperand(i); 265 OS << "}<"; 266 if (AR->hasNoUnsignedWrap()) 267 OS << "nuw><"; 268 if (AR->hasNoSignedWrap()) 269 OS << "nsw><"; 270 if (AR->hasNoSelfWrap() && 271 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 272 OS << "nw><"; 273 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 274 OS << ">"; 275 return; 276 } 277 case scAddExpr: 278 case scMulExpr: 279 case scUMaxExpr: 280 case scSMaxExpr: 281 case scUMinExpr: 282 case scSMinExpr: { 283 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 284 const char *OpStr = nullptr; 285 switch (NAry->getSCEVType()) { 286 case scAddExpr: OpStr = " + "; break; 287 case scMulExpr: OpStr = " * "; break; 288 case scUMaxExpr: OpStr = " umax "; break; 289 case scSMaxExpr: OpStr = " smax "; break; 290 case scUMinExpr: 291 OpStr = " umin "; 292 break; 293 case scSMinExpr: 294 OpStr = " smin "; 295 break; 296 } 297 OS << "("; 298 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 299 I != E; ++I) { 300 OS << **I; 301 if (std::next(I) != E) 302 OS << OpStr; 303 } 304 OS << ")"; 305 switch (NAry->getSCEVType()) { 306 case scAddExpr: 307 case scMulExpr: 308 if (NAry->hasNoUnsignedWrap()) 309 OS << "<nuw>"; 310 if (NAry->hasNoSignedWrap()) 311 OS << "<nsw>"; 312 } 313 return; 314 } 315 case scUDivExpr: { 316 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 317 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 318 return; 319 } 320 case scUnknown: { 321 const SCEVUnknown *U = cast<SCEVUnknown>(this); 322 Type *AllocTy; 323 if (U->isSizeOf(AllocTy)) { 324 OS << "sizeof(" << *AllocTy << ")"; 325 return; 326 } 327 if (U->isAlignOf(AllocTy)) { 328 OS << "alignof(" << *AllocTy << ")"; 329 return; 330 } 331 332 Type *CTy; 333 Constant *FieldNo; 334 if (U->isOffsetOf(CTy, FieldNo)) { 335 OS << "offsetof(" << *CTy << ", "; 336 FieldNo->printAsOperand(OS, false); 337 OS << ")"; 338 return; 339 } 340 341 // Otherwise just print it normally. 342 U->getValue()->printAsOperand(OS, false); 343 return; 344 } 345 case scCouldNotCompute: 346 OS << "***COULDNOTCOMPUTE***"; 347 return; 348 } 349 llvm_unreachable("Unknown SCEV kind!"); 350 } 351 352 Type *SCEV::getType() const { 353 switch (static_cast<SCEVTypes>(getSCEVType())) { 354 case scConstant: 355 return cast<SCEVConstant>(this)->getType(); 356 case scTruncate: 357 case scZeroExtend: 358 case scSignExtend: 359 return cast<SCEVCastExpr>(this)->getType(); 360 case scAddRecExpr: 361 case scMulExpr: 362 case scUMaxExpr: 363 case scSMaxExpr: 364 case scUMinExpr: 365 case scSMinExpr: 366 return cast<SCEVNAryExpr>(this)->getType(); 367 case scAddExpr: 368 return cast<SCEVAddExpr>(this)->getType(); 369 case scUDivExpr: 370 return cast<SCEVUDivExpr>(this)->getType(); 371 case scUnknown: 372 return cast<SCEVUnknown>(this)->getType(); 373 case scCouldNotCompute: 374 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 375 } 376 llvm_unreachable("Unknown SCEV kind!"); 377 } 378 379 bool SCEV::isZero() const { 380 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 381 return SC->getValue()->isZero(); 382 return false; 383 } 384 385 bool SCEV::isOne() const { 386 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 387 return SC->getValue()->isOne(); 388 return false; 389 } 390 391 bool SCEV::isAllOnesValue() const { 392 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 393 return SC->getValue()->isMinusOne(); 394 return false; 395 } 396 397 bool SCEV::isNonConstantNegative() const { 398 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 399 if (!Mul) return false; 400 401 // If there is a constant factor, it will be first. 402 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 403 if (!SC) return false; 404 405 // Return true if the value is negative, this matches things like (-42 * V). 406 return SC->getAPInt().isNegative(); 407 } 408 409 SCEVCouldNotCompute::SCEVCouldNotCompute() : 410 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 411 412 bool SCEVCouldNotCompute::classof(const SCEV *S) { 413 return S->getSCEVType() == scCouldNotCompute; 414 } 415 416 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 417 FoldingSetNodeID ID; 418 ID.AddInteger(scConstant); 419 ID.AddPointer(V); 420 void *IP = nullptr; 421 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 422 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 423 UniqueSCEVs.InsertNode(S, IP); 424 return S; 425 } 426 427 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 428 return getConstant(ConstantInt::get(getContext(), Val)); 429 } 430 431 const SCEV * 432 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 433 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 434 return getConstant(ConstantInt::get(ITy, V, isSigned)); 435 } 436 437 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 438 unsigned SCEVTy, const SCEV *op, Type *ty) 439 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 440 441 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 442 const SCEV *op, Type *ty) 443 : SCEVCastExpr(ID, scTruncate, op, ty) { 444 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 445 "Cannot truncate non-integer value!"); 446 } 447 448 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 449 const SCEV *op, Type *ty) 450 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 451 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 452 "Cannot zero extend non-integer value!"); 453 } 454 455 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 456 const SCEV *op, Type *ty) 457 : SCEVCastExpr(ID, scSignExtend, op, ty) { 458 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 459 "Cannot sign extend non-integer value!"); 460 } 461 462 void SCEVUnknown::deleted() { 463 // Clear this SCEVUnknown from various maps. 464 SE->forgetMemoizedResults(this); 465 466 // Remove this SCEVUnknown from the uniquing map. 467 SE->UniqueSCEVs.RemoveNode(this); 468 469 // Release the value. 470 setValPtr(nullptr); 471 } 472 473 void SCEVUnknown::allUsesReplacedWith(Value *New) { 474 // Remove this SCEVUnknown from the uniquing map. 475 SE->UniqueSCEVs.RemoveNode(this); 476 477 // Update this SCEVUnknown to point to the new value. This is needed 478 // because there may still be outstanding SCEVs which still point to 479 // this SCEVUnknown. 480 setValPtr(New); 481 } 482 483 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 484 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 485 if (VCE->getOpcode() == Instruction::PtrToInt) 486 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 487 if (CE->getOpcode() == Instruction::GetElementPtr && 488 CE->getOperand(0)->isNullValue() && 489 CE->getNumOperands() == 2) 490 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 491 if (CI->isOne()) { 492 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 493 ->getElementType(); 494 return true; 495 } 496 497 return false; 498 } 499 500 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 501 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 502 if (VCE->getOpcode() == Instruction::PtrToInt) 503 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 504 if (CE->getOpcode() == Instruction::GetElementPtr && 505 CE->getOperand(0)->isNullValue()) { 506 Type *Ty = 507 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 508 if (StructType *STy = dyn_cast<StructType>(Ty)) 509 if (!STy->isPacked() && 510 CE->getNumOperands() == 3 && 511 CE->getOperand(1)->isNullValue()) { 512 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 513 if (CI->isOne() && 514 STy->getNumElements() == 2 && 515 STy->getElementType(0)->isIntegerTy(1)) { 516 AllocTy = STy->getElementType(1); 517 return true; 518 } 519 } 520 } 521 522 return false; 523 } 524 525 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 526 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 527 if (VCE->getOpcode() == Instruction::PtrToInt) 528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 529 if (CE->getOpcode() == Instruction::GetElementPtr && 530 CE->getNumOperands() == 3 && 531 CE->getOperand(0)->isNullValue() && 532 CE->getOperand(1)->isNullValue()) { 533 Type *Ty = 534 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 535 // Ignore vector types here so that ScalarEvolutionExpander doesn't 536 // emit getelementptrs that index into vectors. 537 if (Ty->isStructTy() || Ty->isArrayTy()) { 538 CTy = Ty; 539 FieldNo = CE->getOperand(2); 540 return true; 541 } 542 } 543 544 return false; 545 } 546 547 //===----------------------------------------------------------------------===// 548 // SCEV Utilities 549 //===----------------------------------------------------------------------===// 550 551 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 552 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 553 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 554 /// have been previously deemed to be "equally complex" by this routine. It is 555 /// intended to avoid exponential time complexity in cases like: 556 /// 557 /// %a = f(%x, %y) 558 /// %b = f(%a, %a) 559 /// %c = f(%b, %b) 560 /// 561 /// %d = f(%x, %y) 562 /// %e = f(%d, %d) 563 /// %f = f(%e, %e) 564 /// 565 /// CompareValueComplexity(%f, %c) 566 /// 567 /// Since we do not continue running this routine on expression trees once we 568 /// have seen unequal values, there is no need to track them in the cache. 569 static int 570 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 571 const LoopInfo *const LI, Value *LV, Value *RV, 572 unsigned Depth) { 573 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 574 return 0; 575 576 // Order pointer values after integer values. This helps SCEVExpander form 577 // GEPs. 578 bool LIsPointer = LV->getType()->isPointerTy(), 579 RIsPointer = RV->getType()->isPointerTy(); 580 if (LIsPointer != RIsPointer) 581 return (int)LIsPointer - (int)RIsPointer; 582 583 // Compare getValueID values. 584 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 585 if (LID != RID) 586 return (int)LID - (int)RID; 587 588 // Sort arguments by their position. 589 if (const auto *LA = dyn_cast<Argument>(LV)) { 590 const auto *RA = cast<Argument>(RV); 591 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 592 return (int)LArgNo - (int)RArgNo; 593 } 594 595 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 596 const auto *RGV = cast<GlobalValue>(RV); 597 598 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 599 auto LT = GV->getLinkage(); 600 return !(GlobalValue::isPrivateLinkage(LT) || 601 GlobalValue::isInternalLinkage(LT)); 602 }; 603 604 // Use the names to distinguish the two values, but only if the 605 // names are semantically important. 606 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 607 return LGV->getName().compare(RGV->getName()); 608 } 609 610 // For instructions, compare their loop depth, and their operand count. This 611 // is pretty loose. 612 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 613 const auto *RInst = cast<Instruction>(RV); 614 615 // Compare loop depths. 616 const BasicBlock *LParent = LInst->getParent(), 617 *RParent = RInst->getParent(); 618 if (LParent != RParent) { 619 unsigned LDepth = LI->getLoopDepth(LParent), 620 RDepth = LI->getLoopDepth(RParent); 621 if (LDepth != RDepth) 622 return (int)LDepth - (int)RDepth; 623 } 624 625 // Compare the number of operands. 626 unsigned LNumOps = LInst->getNumOperands(), 627 RNumOps = RInst->getNumOperands(); 628 if (LNumOps != RNumOps) 629 return (int)LNumOps - (int)RNumOps; 630 631 for (unsigned Idx : seq(0u, LNumOps)) { 632 int Result = 633 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 634 RInst->getOperand(Idx), Depth + 1); 635 if (Result != 0) 636 return Result; 637 } 638 } 639 640 EqCacheValue.unionSets(LV, RV); 641 return 0; 642 } 643 644 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 645 // than RHS, respectively. A three-way result allows recursive comparisons to be 646 // more efficient. 647 static int CompareSCEVComplexity( 648 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 649 EquivalenceClasses<const Value *> &EqCacheValue, 650 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 651 DominatorTree &DT, unsigned Depth = 0) { 652 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 653 if (LHS == RHS) 654 return 0; 655 656 // Primarily, sort the SCEVs by their getSCEVType(). 657 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 658 if (LType != RType) 659 return (int)LType - (int)RType; 660 661 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 662 return 0; 663 // Aside from the getSCEVType() ordering, the particular ordering 664 // isn't very important except that it's beneficial to be consistent, 665 // so that (a + b) and (b + a) don't end up as different expressions. 666 switch (static_cast<SCEVTypes>(LType)) { 667 case scUnknown: { 668 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 669 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 670 671 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 672 RU->getValue(), Depth + 1); 673 if (X == 0) 674 EqCacheSCEV.unionSets(LHS, RHS); 675 return X; 676 } 677 678 case scConstant: { 679 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 680 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 681 682 // Compare constant values. 683 const APInt &LA = LC->getAPInt(); 684 const APInt &RA = RC->getAPInt(); 685 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 686 if (LBitWidth != RBitWidth) 687 return (int)LBitWidth - (int)RBitWidth; 688 return LA.ult(RA) ? -1 : 1; 689 } 690 691 case scAddRecExpr: { 692 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 693 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 694 695 // There is always a dominance between two recs that are used by one SCEV, 696 // so we can safely sort recs by loop header dominance. We require such 697 // order in getAddExpr. 698 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 699 if (LLoop != RLoop) { 700 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 701 assert(LHead != RHead && "Two loops share the same header?"); 702 if (DT.dominates(LHead, RHead)) 703 return 1; 704 else 705 assert(DT.dominates(RHead, LHead) && 706 "No dominance between recurrences used by one SCEV?"); 707 return -1; 708 } 709 710 // Addrec complexity grows with operand count. 711 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 712 if (LNumOps != RNumOps) 713 return (int)LNumOps - (int)RNumOps; 714 715 // Lexicographically compare. 716 for (unsigned i = 0; i != LNumOps; ++i) { 717 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 718 LA->getOperand(i), RA->getOperand(i), DT, 719 Depth + 1); 720 if (X != 0) 721 return X; 722 } 723 EqCacheSCEV.unionSets(LHS, RHS); 724 return 0; 725 } 726 727 case scAddExpr: 728 case scMulExpr: 729 case scSMaxExpr: 730 case scUMaxExpr: 731 case scSMinExpr: 732 case scUMinExpr: { 733 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 734 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 735 736 // Lexicographically compare n-ary expressions. 737 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 738 if (LNumOps != RNumOps) 739 return (int)LNumOps - (int)RNumOps; 740 741 for (unsigned i = 0; i != LNumOps; ++i) { 742 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 743 LC->getOperand(i), RC->getOperand(i), DT, 744 Depth + 1); 745 if (X != 0) 746 return X; 747 } 748 EqCacheSCEV.unionSets(LHS, RHS); 749 return 0; 750 } 751 752 case scUDivExpr: { 753 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 754 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 755 756 // Lexicographically compare udiv expressions. 757 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 758 RC->getLHS(), DT, Depth + 1); 759 if (X != 0) 760 return X; 761 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 762 RC->getRHS(), DT, Depth + 1); 763 if (X == 0) 764 EqCacheSCEV.unionSets(LHS, RHS); 765 return X; 766 } 767 768 case scTruncate: 769 case scZeroExtend: 770 case scSignExtend: { 771 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 772 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 773 774 // Compare cast expressions by operand. 775 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 776 LC->getOperand(), RC->getOperand(), DT, 777 Depth + 1); 778 if (X == 0) 779 EqCacheSCEV.unionSets(LHS, RHS); 780 return X; 781 } 782 783 case scCouldNotCompute: 784 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 785 } 786 llvm_unreachable("Unknown SCEV kind!"); 787 } 788 789 /// Given a list of SCEV objects, order them by their complexity, and group 790 /// objects of the same complexity together by value. When this routine is 791 /// finished, we know that any duplicates in the vector are consecutive and that 792 /// complexity is monotonically increasing. 793 /// 794 /// Note that we go take special precautions to ensure that we get deterministic 795 /// results from this routine. In other words, we don't want the results of 796 /// this to depend on where the addresses of various SCEV objects happened to 797 /// land in memory. 798 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 799 LoopInfo *LI, DominatorTree &DT) { 800 if (Ops.size() < 2) return; // Noop 801 802 EquivalenceClasses<const SCEV *> EqCacheSCEV; 803 EquivalenceClasses<const Value *> EqCacheValue; 804 if (Ops.size() == 2) { 805 // This is the common case, which also happens to be trivially simple. 806 // Special case it. 807 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 808 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 809 std::swap(LHS, RHS); 810 return; 811 } 812 813 // Do the rough sort by complexity. 814 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 815 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 816 0; 817 }); 818 819 // Now that we are sorted by complexity, group elements of the same 820 // complexity. Note that this is, at worst, N^2, but the vector is likely to 821 // be extremely short in practice. Note that we take this approach because we 822 // do not want to depend on the addresses of the objects we are grouping. 823 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 824 const SCEV *S = Ops[i]; 825 unsigned Complexity = S->getSCEVType(); 826 827 // If there are any objects of the same complexity and same value as this 828 // one, group them. 829 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 830 if (Ops[j] == S) { // Found a duplicate. 831 // Move it to immediately after i'th element. 832 std::swap(Ops[i+1], Ops[j]); 833 ++i; // no need to rescan it. 834 if (i == e-2) return; // Done! 835 } 836 } 837 } 838 } 839 840 // Returns the size of the SCEV S. 841 static inline int sizeOfSCEV(const SCEV *S) { 842 struct FindSCEVSize { 843 int Size = 0; 844 845 FindSCEVSize() = default; 846 847 bool follow(const SCEV *S) { 848 ++Size; 849 // Keep looking at all operands of S. 850 return true; 851 } 852 853 bool isDone() const { 854 return false; 855 } 856 }; 857 858 FindSCEVSize F; 859 SCEVTraversal<FindSCEVSize> ST(F); 860 ST.visitAll(S); 861 return F.Size; 862 } 863 864 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 865 /// nodes. 866 static bool isHugeExpression(const SCEV *S) { 867 return S->getExpressionSize() >= HugeExprThreshold; 868 } 869 870 /// Returns true of \p Ops contains a huge SCEV (see definition above). 871 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 872 return any_of(Ops, isHugeExpression); 873 } 874 875 namespace { 876 877 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 878 public: 879 // Computes the Quotient and Remainder of the division of Numerator by 880 // Denominator. 881 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 882 const SCEV *Denominator, const SCEV **Quotient, 883 const SCEV **Remainder) { 884 assert(Numerator && Denominator && "Uninitialized SCEV"); 885 886 SCEVDivision D(SE, Numerator, Denominator); 887 888 // Check for the trivial case here to avoid having to check for it in the 889 // rest of the code. 890 if (Numerator == Denominator) { 891 *Quotient = D.One; 892 *Remainder = D.Zero; 893 return; 894 } 895 896 if (Numerator->isZero()) { 897 *Quotient = D.Zero; 898 *Remainder = D.Zero; 899 return; 900 } 901 902 // A simple case when N/1. The quotient is N. 903 if (Denominator->isOne()) { 904 *Quotient = Numerator; 905 *Remainder = D.Zero; 906 return; 907 } 908 909 // Split the Denominator when it is a product. 910 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 911 const SCEV *Q, *R; 912 *Quotient = Numerator; 913 for (const SCEV *Op : T->operands()) { 914 divide(SE, *Quotient, Op, &Q, &R); 915 *Quotient = Q; 916 917 // Bail out when the Numerator is not divisible by one of the terms of 918 // the Denominator. 919 if (!R->isZero()) { 920 *Quotient = D.Zero; 921 *Remainder = Numerator; 922 return; 923 } 924 } 925 *Remainder = D.Zero; 926 return; 927 } 928 929 D.visit(Numerator); 930 *Quotient = D.Quotient; 931 *Remainder = D.Remainder; 932 } 933 934 // Except in the trivial case described above, we do not know how to divide 935 // Expr by Denominator for the following functions with empty implementation. 936 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 937 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 938 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 939 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 940 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 941 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 942 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 943 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 944 void visitUnknown(const SCEVUnknown *Numerator) {} 945 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 946 947 void visitConstant(const SCEVConstant *Numerator) { 948 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 949 APInt NumeratorVal = Numerator->getAPInt(); 950 APInt DenominatorVal = D->getAPInt(); 951 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 952 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 953 954 if (NumeratorBW > DenominatorBW) 955 DenominatorVal = DenominatorVal.sext(NumeratorBW); 956 else if (NumeratorBW < DenominatorBW) 957 NumeratorVal = NumeratorVal.sext(DenominatorBW); 958 959 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 960 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 961 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 962 Quotient = SE.getConstant(QuotientVal); 963 Remainder = SE.getConstant(RemainderVal); 964 return; 965 } 966 } 967 968 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 969 const SCEV *StartQ, *StartR, *StepQ, *StepR; 970 if (!Numerator->isAffine()) 971 return cannotDivide(Numerator); 972 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 973 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 974 // Bail out if the types do not match. 975 Type *Ty = Denominator->getType(); 976 if (Ty != StartQ->getType() || Ty != StartR->getType() || 977 Ty != StepQ->getType() || Ty != StepR->getType()) 978 return cannotDivide(Numerator); 979 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 980 Numerator->getNoWrapFlags()); 981 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 982 Numerator->getNoWrapFlags()); 983 } 984 985 void visitAddExpr(const SCEVAddExpr *Numerator) { 986 SmallVector<const SCEV *, 2> Qs, Rs; 987 Type *Ty = Denominator->getType(); 988 989 for (const SCEV *Op : Numerator->operands()) { 990 const SCEV *Q, *R; 991 divide(SE, Op, Denominator, &Q, &R); 992 993 // Bail out if types do not match. 994 if (Ty != Q->getType() || Ty != R->getType()) 995 return cannotDivide(Numerator); 996 997 Qs.push_back(Q); 998 Rs.push_back(R); 999 } 1000 1001 if (Qs.size() == 1) { 1002 Quotient = Qs[0]; 1003 Remainder = Rs[0]; 1004 return; 1005 } 1006 1007 Quotient = SE.getAddExpr(Qs); 1008 Remainder = SE.getAddExpr(Rs); 1009 } 1010 1011 void visitMulExpr(const SCEVMulExpr *Numerator) { 1012 SmallVector<const SCEV *, 2> Qs; 1013 Type *Ty = Denominator->getType(); 1014 1015 bool FoundDenominatorTerm = false; 1016 for (const SCEV *Op : Numerator->operands()) { 1017 // Bail out if types do not match. 1018 if (Ty != Op->getType()) 1019 return cannotDivide(Numerator); 1020 1021 if (FoundDenominatorTerm) { 1022 Qs.push_back(Op); 1023 continue; 1024 } 1025 1026 // Check whether Denominator divides one of the product operands. 1027 const SCEV *Q, *R; 1028 divide(SE, Op, Denominator, &Q, &R); 1029 if (!R->isZero()) { 1030 Qs.push_back(Op); 1031 continue; 1032 } 1033 1034 // Bail out if types do not match. 1035 if (Ty != Q->getType()) 1036 return cannotDivide(Numerator); 1037 1038 FoundDenominatorTerm = true; 1039 Qs.push_back(Q); 1040 } 1041 1042 if (FoundDenominatorTerm) { 1043 Remainder = Zero; 1044 if (Qs.size() == 1) 1045 Quotient = Qs[0]; 1046 else 1047 Quotient = SE.getMulExpr(Qs); 1048 return; 1049 } 1050 1051 if (!isa<SCEVUnknown>(Denominator)) 1052 return cannotDivide(Numerator); 1053 1054 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1055 ValueToValueMap RewriteMap; 1056 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1057 cast<SCEVConstant>(Zero)->getValue(); 1058 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1059 1060 if (Remainder->isZero()) { 1061 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1062 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1063 cast<SCEVConstant>(One)->getValue(); 1064 Quotient = 1065 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1066 return; 1067 } 1068 1069 // Quotient is (Numerator - Remainder) divided by Denominator. 1070 const SCEV *Q, *R; 1071 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1072 // This SCEV does not seem to simplify: fail the division here. 1073 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1074 return cannotDivide(Numerator); 1075 divide(SE, Diff, Denominator, &Q, &R); 1076 if (R != Zero) 1077 return cannotDivide(Numerator); 1078 Quotient = Q; 1079 } 1080 1081 private: 1082 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1083 const SCEV *Denominator) 1084 : SE(S), Denominator(Denominator) { 1085 Zero = SE.getZero(Denominator->getType()); 1086 One = SE.getOne(Denominator->getType()); 1087 1088 // We generally do not know how to divide Expr by Denominator. We 1089 // initialize the division to a "cannot divide" state to simplify the rest 1090 // of the code. 1091 cannotDivide(Numerator); 1092 } 1093 1094 // Convenience function for giving up on the division. We set the quotient to 1095 // be equal to zero and the remainder to be equal to the numerator. 1096 void cannotDivide(const SCEV *Numerator) { 1097 Quotient = Zero; 1098 Remainder = Numerator; 1099 } 1100 1101 ScalarEvolution &SE; 1102 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1103 }; 1104 1105 } // end anonymous namespace 1106 1107 //===----------------------------------------------------------------------===// 1108 // Simple SCEV method implementations 1109 //===----------------------------------------------------------------------===// 1110 1111 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1112 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1113 ScalarEvolution &SE, 1114 Type *ResultTy) { 1115 // Handle the simplest case efficiently. 1116 if (K == 1) 1117 return SE.getTruncateOrZeroExtend(It, ResultTy); 1118 1119 // We are using the following formula for BC(It, K): 1120 // 1121 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1122 // 1123 // Suppose, W is the bitwidth of the return value. We must be prepared for 1124 // overflow. Hence, we must assure that the result of our computation is 1125 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1126 // safe in modular arithmetic. 1127 // 1128 // However, this code doesn't use exactly that formula; the formula it uses 1129 // is something like the following, where T is the number of factors of 2 in 1130 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1131 // exponentiation: 1132 // 1133 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1134 // 1135 // This formula is trivially equivalent to the previous formula. However, 1136 // this formula can be implemented much more efficiently. The trick is that 1137 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1138 // arithmetic. To do exact division in modular arithmetic, all we have 1139 // to do is multiply by the inverse. Therefore, this step can be done at 1140 // width W. 1141 // 1142 // The next issue is how to safely do the division by 2^T. The way this 1143 // is done is by doing the multiplication step at a width of at least W + T 1144 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1145 // when we perform the division by 2^T (which is equivalent to a right shift 1146 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1147 // truncated out after the division by 2^T. 1148 // 1149 // In comparison to just directly using the first formula, this technique 1150 // is much more efficient; using the first formula requires W * K bits, 1151 // but this formula less than W + K bits. Also, the first formula requires 1152 // a division step, whereas this formula only requires multiplies and shifts. 1153 // 1154 // It doesn't matter whether the subtraction step is done in the calculation 1155 // width or the input iteration count's width; if the subtraction overflows, 1156 // the result must be zero anyway. We prefer here to do it in the width of 1157 // the induction variable because it helps a lot for certain cases; CodeGen 1158 // isn't smart enough to ignore the overflow, which leads to much less 1159 // efficient code if the width of the subtraction is wider than the native 1160 // register width. 1161 // 1162 // (It's possible to not widen at all by pulling out factors of 2 before 1163 // the multiplication; for example, K=2 can be calculated as 1164 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1165 // extra arithmetic, so it's not an obvious win, and it gets 1166 // much more complicated for K > 3.) 1167 1168 // Protection from insane SCEVs; this bound is conservative, 1169 // but it probably doesn't matter. 1170 if (K > 1000) 1171 return SE.getCouldNotCompute(); 1172 1173 unsigned W = SE.getTypeSizeInBits(ResultTy); 1174 1175 // Calculate K! / 2^T and T; we divide out the factors of two before 1176 // multiplying for calculating K! / 2^T to avoid overflow. 1177 // Other overflow doesn't matter because we only care about the bottom 1178 // W bits of the result. 1179 APInt OddFactorial(W, 1); 1180 unsigned T = 1; 1181 for (unsigned i = 3; i <= K; ++i) { 1182 APInt Mult(W, i); 1183 unsigned TwoFactors = Mult.countTrailingZeros(); 1184 T += TwoFactors; 1185 Mult.lshrInPlace(TwoFactors); 1186 OddFactorial *= Mult; 1187 } 1188 1189 // We need at least W + T bits for the multiplication step 1190 unsigned CalculationBits = W + T; 1191 1192 // Calculate 2^T, at width T+W. 1193 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1194 1195 // Calculate the multiplicative inverse of K! / 2^T; 1196 // this multiplication factor will perform the exact division by 1197 // K! / 2^T. 1198 APInt Mod = APInt::getSignedMinValue(W+1); 1199 APInt MultiplyFactor = OddFactorial.zext(W+1); 1200 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1201 MultiplyFactor = MultiplyFactor.trunc(W); 1202 1203 // Calculate the product, at width T+W 1204 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1205 CalculationBits); 1206 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1207 for (unsigned i = 1; i != K; ++i) { 1208 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1209 Dividend = SE.getMulExpr(Dividend, 1210 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1211 } 1212 1213 // Divide by 2^T 1214 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1215 1216 // Truncate the result, and divide by K! / 2^T. 1217 1218 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1219 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1220 } 1221 1222 /// Return the value of this chain of recurrences at the specified iteration 1223 /// number. We can evaluate this recurrence by multiplying each element in the 1224 /// chain by the binomial coefficient corresponding to it. In other words, we 1225 /// can evaluate {A,+,B,+,C,+,D} as: 1226 /// 1227 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1228 /// 1229 /// where BC(It, k) stands for binomial coefficient. 1230 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1231 ScalarEvolution &SE) const { 1232 const SCEV *Result = getStart(); 1233 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1234 // The computation is correct in the face of overflow provided that the 1235 // multiplication is performed _after_ the evaluation of the binomial 1236 // coefficient. 1237 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1238 if (isa<SCEVCouldNotCompute>(Coeff)) 1239 return Coeff; 1240 1241 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1242 } 1243 return Result; 1244 } 1245 1246 //===----------------------------------------------------------------------===// 1247 // SCEV Expression folder implementations 1248 //===----------------------------------------------------------------------===// 1249 1250 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1251 unsigned Depth) { 1252 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1253 "This is not a truncating conversion!"); 1254 assert(isSCEVable(Ty) && 1255 "This is not a conversion to a SCEVable type!"); 1256 Ty = getEffectiveSCEVType(Ty); 1257 1258 FoldingSetNodeID ID; 1259 ID.AddInteger(scTruncate); 1260 ID.AddPointer(Op); 1261 ID.AddPointer(Ty); 1262 void *IP = nullptr; 1263 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1264 1265 // Fold if the operand is constant. 1266 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1267 return getConstant( 1268 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1269 1270 // trunc(trunc(x)) --> trunc(x) 1271 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1272 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1273 1274 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1275 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1276 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1277 1278 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1279 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1280 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1281 1282 if (Depth > MaxCastDepth) { 1283 SCEV *S = 1284 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1285 UniqueSCEVs.InsertNode(S, IP); 1286 addToLoopUseLists(S); 1287 return S; 1288 } 1289 1290 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1291 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1292 // if after transforming we have at most one truncate, not counting truncates 1293 // that replace other casts. 1294 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1295 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1296 SmallVector<const SCEV *, 4> Operands; 1297 unsigned numTruncs = 0; 1298 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1299 ++i) { 1300 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1301 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1302 numTruncs++; 1303 Operands.push_back(S); 1304 } 1305 if (numTruncs < 2) { 1306 if (isa<SCEVAddExpr>(Op)) 1307 return getAddExpr(Operands); 1308 else if (isa<SCEVMulExpr>(Op)) 1309 return getMulExpr(Operands); 1310 else 1311 llvm_unreachable("Unexpected SCEV type for Op."); 1312 } 1313 // Although we checked in the beginning that ID is not in the cache, it is 1314 // possible that during recursion and different modification ID was inserted 1315 // into the cache. So if we find it, just return it. 1316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1317 return S; 1318 } 1319 1320 // If the input value is a chrec scev, truncate the chrec's operands. 1321 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1322 SmallVector<const SCEV *, 4> Operands; 1323 for (const SCEV *Op : AddRec->operands()) 1324 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1325 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1326 } 1327 1328 // The cast wasn't folded; create an explicit cast node. We can reuse 1329 // the existing insert position since if we get here, we won't have 1330 // made any changes which would invalidate it. 1331 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1332 Op, Ty); 1333 UniqueSCEVs.InsertNode(S, IP); 1334 addToLoopUseLists(S); 1335 return S; 1336 } 1337 1338 // Get the limit of a recurrence such that incrementing by Step cannot cause 1339 // signed overflow as long as the value of the recurrence within the 1340 // loop does not exceed this limit before incrementing. 1341 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1342 ICmpInst::Predicate *Pred, 1343 ScalarEvolution *SE) { 1344 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1345 if (SE->isKnownPositive(Step)) { 1346 *Pred = ICmpInst::ICMP_SLT; 1347 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1348 SE->getSignedRangeMax(Step)); 1349 } 1350 if (SE->isKnownNegative(Step)) { 1351 *Pred = ICmpInst::ICMP_SGT; 1352 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1353 SE->getSignedRangeMin(Step)); 1354 } 1355 return nullptr; 1356 } 1357 1358 // Get the limit of a recurrence such that incrementing by Step cannot cause 1359 // unsigned overflow as long as the value of the recurrence within the loop does 1360 // not exceed this limit before incrementing. 1361 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1362 ICmpInst::Predicate *Pred, 1363 ScalarEvolution *SE) { 1364 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1365 *Pred = ICmpInst::ICMP_ULT; 1366 1367 return SE->getConstant(APInt::getMinValue(BitWidth) - 1368 SE->getUnsignedRangeMax(Step)); 1369 } 1370 1371 namespace { 1372 1373 struct ExtendOpTraitsBase { 1374 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1375 unsigned); 1376 }; 1377 1378 // Used to make code generic over signed and unsigned overflow. 1379 template <typename ExtendOp> struct ExtendOpTraits { 1380 // Members present: 1381 // 1382 // static const SCEV::NoWrapFlags WrapType; 1383 // 1384 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1385 // 1386 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1387 // ICmpInst::Predicate *Pred, 1388 // ScalarEvolution *SE); 1389 }; 1390 1391 template <> 1392 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1393 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1394 1395 static const GetExtendExprTy GetExtendExpr; 1396 1397 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1398 ICmpInst::Predicate *Pred, 1399 ScalarEvolution *SE) { 1400 return getSignedOverflowLimitForStep(Step, Pred, SE); 1401 } 1402 }; 1403 1404 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1405 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1406 1407 template <> 1408 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1409 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1410 1411 static const GetExtendExprTy GetExtendExpr; 1412 1413 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1414 ICmpInst::Predicate *Pred, 1415 ScalarEvolution *SE) { 1416 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1417 } 1418 }; 1419 1420 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1421 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1422 1423 } // end anonymous namespace 1424 1425 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1426 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1427 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1428 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1429 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1430 // expression "Step + sext/zext(PreIncAR)" is congruent with 1431 // "sext/zext(PostIncAR)" 1432 template <typename ExtendOpTy> 1433 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1434 ScalarEvolution *SE, unsigned Depth) { 1435 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1436 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1437 1438 const Loop *L = AR->getLoop(); 1439 const SCEV *Start = AR->getStart(); 1440 const SCEV *Step = AR->getStepRecurrence(*SE); 1441 1442 // Check for a simple looking step prior to loop entry. 1443 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1444 if (!SA) 1445 return nullptr; 1446 1447 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1448 // subtraction is expensive. For this purpose, perform a quick and dirty 1449 // difference, by checking for Step in the operand list. 1450 SmallVector<const SCEV *, 4> DiffOps; 1451 for (const SCEV *Op : SA->operands()) 1452 if (Op != Step) 1453 DiffOps.push_back(Op); 1454 1455 if (DiffOps.size() == SA->getNumOperands()) 1456 return nullptr; 1457 1458 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1459 // `Step`: 1460 1461 // 1. NSW/NUW flags on the step increment. 1462 auto PreStartFlags = 1463 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1464 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1465 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1466 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1467 1468 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1469 // "S+X does not sign/unsign-overflow". 1470 // 1471 1472 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1473 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1474 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1475 return PreStart; 1476 1477 // 2. Direct overflow check on the step operation's expression. 1478 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1479 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1480 const SCEV *OperandExtendedStart = 1481 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1482 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1483 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1484 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1485 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1486 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1487 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1488 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1489 } 1490 return PreStart; 1491 } 1492 1493 // 3. Loop precondition. 1494 ICmpInst::Predicate Pred; 1495 const SCEV *OverflowLimit = 1496 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1497 1498 if (OverflowLimit && 1499 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1500 return PreStart; 1501 1502 return nullptr; 1503 } 1504 1505 // Get the normalized zero or sign extended expression for this AddRec's Start. 1506 template <typename ExtendOpTy> 1507 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1508 ScalarEvolution *SE, 1509 unsigned Depth) { 1510 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1511 1512 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1513 if (!PreStart) 1514 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1515 1516 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1517 Depth), 1518 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1519 } 1520 1521 // Try to prove away overflow by looking at "nearby" add recurrences. A 1522 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1523 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1524 // 1525 // Formally: 1526 // 1527 // {S,+,X} == {S-T,+,X} + T 1528 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1529 // 1530 // If ({S-T,+,X} + T) does not overflow ... (1) 1531 // 1532 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1533 // 1534 // If {S-T,+,X} does not overflow ... (2) 1535 // 1536 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1537 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1538 // 1539 // If (S-T)+T does not overflow ... (3) 1540 // 1541 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1542 // == {Ext(S),+,Ext(X)} == LHS 1543 // 1544 // Thus, if (1), (2) and (3) are true for some T, then 1545 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1546 // 1547 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1548 // does not overflow" restricted to the 0th iteration. Therefore we only need 1549 // to check for (1) and (2). 1550 // 1551 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1552 // is `Delta` (defined below). 1553 template <typename ExtendOpTy> 1554 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1555 const SCEV *Step, 1556 const Loop *L) { 1557 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1558 1559 // We restrict `Start` to a constant to prevent SCEV from spending too much 1560 // time here. It is correct (but more expensive) to continue with a 1561 // non-constant `Start` and do a general SCEV subtraction to compute 1562 // `PreStart` below. 1563 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1564 if (!StartC) 1565 return false; 1566 1567 APInt StartAI = StartC->getAPInt(); 1568 1569 for (unsigned Delta : {-2, -1, 1, 2}) { 1570 const SCEV *PreStart = getConstant(StartAI - Delta); 1571 1572 FoldingSetNodeID ID; 1573 ID.AddInteger(scAddRecExpr); 1574 ID.AddPointer(PreStart); 1575 ID.AddPointer(Step); 1576 ID.AddPointer(L); 1577 void *IP = nullptr; 1578 const auto *PreAR = 1579 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1580 1581 // Give up if we don't already have the add recurrence we need because 1582 // actually constructing an add recurrence is relatively expensive. 1583 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1584 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1585 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1586 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1587 DeltaS, &Pred, this); 1588 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1589 return true; 1590 } 1591 } 1592 1593 return false; 1594 } 1595 1596 // Finds an integer D for an expression (C + x + y + ...) such that the top 1597 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1598 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1599 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1600 // the (C + x + y + ...) expression is \p WholeAddExpr. 1601 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1602 const SCEVConstant *ConstantTerm, 1603 const SCEVAddExpr *WholeAddExpr) { 1604 const APInt C = ConstantTerm->getAPInt(); 1605 const unsigned BitWidth = C.getBitWidth(); 1606 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1607 uint32_t TZ = BitWidth; 1608 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1609 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1610 if (TZ) { 1611 // Set D to be as many least significant bits of C as possible while still 1612 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1613 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1614 } 1615 return APInt(BitWidth, 0); 1616 } 1617 1618 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1619 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1620 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1621 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1622 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1623 const APInt &ConstantStart, 1624 const SCEV *Step) { 1625 const unsigned BitWidth = ConstantStart.getBitWidth(); 1626 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1627 if (TZ) 1628 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1629 : ConstantStart; 1630 return APInt(BitWidth, 0); 1631 } 1632 1633 const SCEV * 1634 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1635 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1636 "This is not an extending conversion!"); 1637 assert(isSCEVable(Ty) && 1638 "This is not a conversion to a SCEVable type!"); 1639 Ty = getEffectiveSCEVType(Ty); 1640 1641 // Fold if the operand is constant. 1642 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1643 return getConstant( 1644 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1645 1646 // zext(zext(x)) --> zext(x) 1647 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1648 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1649 1650 // Before doing any expensive analysis, check to see if we've already 1651 // computed a SCEV for this Op and Ty. 1652 FoldingSetNodeID ID; 1653 ID.AddInteger(scZeroExtend); 1654 ID.AddPointer(Op); 1655 ID.AddPointer(Ty); 1656 void *IP = nullptr; 1657 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1658 if (Depth > MaxCastDepth) { 1659 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1660 Op, Ty); 1661 UniqueSCEVs.InsertNode(S, IP); 1662 addToLoopUseLists(S); 1663 return S; 1664 } 1665 1666 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1667 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1668 // It's possible the bits taken off by the truncate were all zero bits. If 1669 // so, we should be able to simplify this further. 1670 const SCEV *X = ST->getOperand(); 1671 ConstantRange CR = getUnsignedRange(X); 1672 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1673 unsigned NewBits = getTypeSizeInBits(Ty); 1674 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1675 CR.zextOrTrunc(NewBits))) 1676 return getTruncateOrZeroExtend(X, Ty, Depth); 1677 } 1678 1679 // If the input value is a chrec scev, and we can prove that the value 1680 // did not overflow the old, smaller, value, we can zero extend all of the 1681 // operands (often constants). This allows analysis of something like 1682 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1683 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1684 if (AR->isAffine()) { 1685 const SCEV *Start = AR->getStart(); 1686 const SCEV *Step = AR->getStepRecurrence(*this); 1687 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1688 const Loop *L = AR->getLoop(); 1689 1690 if (!AR->hasNoUnsignedWrap()) { 1691 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1692 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1693 } 1694 1695 // If we have special knowledge that this addrec won't overflow, 1696 // we don't need to do any further analysis. 1697 if (AR->hasNoUnsignedWrap()) 1698 return getAddRecExpr( 1699 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1700 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1701 1702 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1703 // Note that this serves two purposes: It filters out loops that are 1704 // simply not analyzable, and it covers the case where this code is 1705 // being called from within backedge-taken count analysis, such that 1706 // attempting to ask for the backedge-taken count would likely result 1707 // in infinite recursion. In the later case, the analysis code will 1708 // cope with a conservative value, and it will take care to purge 1709 // that value once it has finished. 1710 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1711 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1712 // Manually compute the final value for AR, checking for 1713 // overflow. 1714 1715 // Check whether the backedge-taken count can be losslessly casted to 1716 // the addrec's type. The count is always unsigned. 1717 const SCEV *CastedMaxBECount = 1718 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1719 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1720 CastedMaxBECount, MaxBECount->getType(), Depth); 1721 if (MaxBECount == RecastedMaxBECount) { 1722 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1723 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1724 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1725 SCEV::FlagAnyWrap, Depth + 1); 1726 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1727 SCEV::FlagAnyWrap, 1728 Depth + 1), 1729 WideTy, Depth + 1); 1730 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1731 const SCEV *WideMaxBECount = 1732 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1733 const SCEV *OperandExtendedAdd = 1734 getAddExpr(WideStart, 1735 getMulExpr(WideMaxBECount, 1736 getZeroExtendExpr(Step, WideTy, Depth + 1), 1737 SCEV::FlagAnyWrap, Depth + 1), 1738 SCEV::FlagAnyWrap, Depth + 1); 1739 if (ZAdd == OperandExtendedAdd) { 1740 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1741 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1742 // Return the expression with the addrec on the outside. 1743 return getAddRecExpr( 1744 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1745 Depth + 1), 1746 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1747 AR->getNoWrapFlags()); 1748 } 1749 // Similar to above, only this time treat the step value as signed. 1750 // This covers loops that count down. 1751 OperandExtendedAdd = 1752 getAddExpr(WideStart, 1753 getMulExpr(WideMaxBECount, 1754 getSignExtendExpr(Step, WideTy, Depth + 1), 1755 SCEV::FlagAnyWrap, Depth + 1), 1756 SCEV::FlagAnyWrap, Depth + 1); 1757 if (ZAdd == OperandExtendedAdd) { 1758 // Cache knowledge of AR NW, which is propagated to this AddRec. 1759 // Negative step causes unsigned wrap, but it still can't self-wrap. 1760 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1761 // Return the expression with the addrec on the outside. 1762 return getAddRecExpr( 1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1764 Depth + 1), 1765 getSignExtendExpr(Step, Ty, Depth + 1), L, 1766 AR->getNoWrapFlags()); 1767 } 1768 } 1769 } 1770 1771 // Normally, in the cases we can prove no-overflow via a 1772 // backedge guarding condition, we can also compute a backedge 1773 // taken count for the loop. The exceptions are assumptions and 1774 // guards present in the loop -- SCEV is not great at exploiting 1775 // these to compute max backedge taken counts, but can still use 1776 // these to prove lack of overflow. Use this fact to avoid 1777 // doing extra work that may not pay off. 1778 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1779 !AC.assumptions().empty()) { 1780 // If the backedge is guarded by a comparison with the pre-inc 1781 // value the addrec is safe. Also, if the entry is guarded by 1782 // a comparison with the start value and the backedge is 1783 // guarded by a comparison with the post-inc value, the addrec 1784 // is safe. 1785 if (isKnownPositive(Step)) { 1786 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1787 getUnsignedRangeMax(Step)); 1788 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1789 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1790 // Cache knowledge of AR NUW, which is propagated to this 1791 // AddRec. 1792 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1793 // Return the expression with the addrec on the outside. 1794 return getAddRecExpr( 1795 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1796 Depth + 1), 1797 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1798 AR->getNoWrapFlags()); 1799 } 1800 } else if (isKnownNegative(Step)) { 1801 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1802 getSignedRangeMin(Step)); 1803 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1804 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1805 // Cache knowledge of AR NW, which is propagated to this 1806 // AddRec. Negative step causes unsigned wrap, but it 1807 // still can't self-wrap. 1808 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1809 // Return the expression with the addrec on the outside. 1810 return getAddRecExpr( 1811 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1812 Depth + 1), 1813 getSignExtendExpr(Step, Ty, Depth + 1), L, 1814 AR->getNoWrapFlags()); 1815 } 1816 } 1817 } 1818 1819 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1820 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1821 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1822 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1823 const APInt &C = SC->getAPInt(); 1824 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1825 if (D != 0) { 1826 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1827 const SCEV *SResidual = 1828 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1829 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1830 return getAddExpr(SZExtD, SZExtR, 1831 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1832 Depth + 1); 1833 } 1834 } 1835 1836 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1837 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1838 return getAddRecExpr( 1839 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1840 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1841 } 1842 } 1843 1844 // zext(A % B) --> zext(A) % zext(B) 1845 { 1846 const SCEV *LHS; 1847 const SCEV *RHS; 1848 if (matchURem(Op, LHS, RHS)) 1849 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1850 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1851 } 1852 1853 // zext(A / B) --> zext(A) / zext(B). 1854 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1855 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1856 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1857 1858 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1859 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1860 if (SA->hasNoUnsignedWrap()) { 1861 // If the addition does not unsign overflow then we can, by definition, 1862 // commute the zero extension with the addition operation. 1863 SmallVector<const SCEV *, 4> Ops; 1864 for (const auto *Op : SA->operands()) 1865 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1866 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1867 } 1868 1869 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1870 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1871 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1872 // 1873 // Often address arithmetics contain expressions like 1874 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1875 // This transformation is useful while proving that such expressions are 1876 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1877 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1878 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1879 if (D != 0) { 1880 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1881 const SCEV *SResidual = 1882 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1883 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1884 return getAddExpr(SZExtD, SZExtR, 1885 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1886 Depth + 1); 1887 } 1888 } 1889 } 1890 1891 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1892 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1893 if (SM->hasNoUnsignedWrap()) { 1894 // If the multiply does not unsign overflow then we can, by definition, 1895 // commute the zero extension with the multiply operation. 1896 SmallVector<const SCEV *, 4> Ops; 1897 for (const auto *Op : SM->operands()) 1898 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1899 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1900 } 1901 1902 // zext(2^K * (trunc X to iN)) to iM -> 1903 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1904 // 1905 // Proof: 1906 // 1907 // zext(2^K * (trunc X to iN)) to iM 1908 // = zext((trunc X to iN) << K) to iM 1909 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1910 // (because shl removes the top K bits) 1911 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1912 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1913 // 1914 if (SM->getNumOperands() == 2) 1915 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1916 if (MulLHS->getAPInt().isPowerOf2()) 1917 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1918 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1919 MulLHS->getAPInt().logBase2(); 1920 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1921 return getMulExpr( 1922 getZeroExtendExpr(MulLHS, Ty), 1923 getZeroExtendExpr( 1924 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1925 SCEV::FlagNUW, Depth + 1); 1926 } 1927 } 1928 1929 // The cast wasn't folded; create an explicit cast node. 1930 // Recompute the insert position, as it may have been invalidated. 1931 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1932 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1933 Op, Ty); 1934 UniqueSCEVs.InsertNode(S, IP); 1935 addToLoopUseLists(S); 1936 return S; 1937 } 1938 1939 const SCEV * 1940 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1941 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1942 "This is not an extending conversion!"); 1943 assert(isSCEVable(Ty) && 1944 "This is not a conversion to a SCEVable type!"); 1945 Ty = getEffectiveSCEVType(Ty); 1946 1947 // Fold if the operand is constant. 1948 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1949 return getConstant( 1950 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1951 1952 // sext(sext(x)) --> sext(x) 1953 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1954 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1955 1956 // sext(zext(x)) --> zext(x) 1957 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1958 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1959 1960 // Before doing any expensive analysis, check to see if we've already 1961 // computed a SCEV for this Op and Ty. 1962 FoldingSetNodeID ID; 1963 ID.AddInteger(scSignExtend); 1964 ID.AddPointer(Op); 1965 ID.AddPointer(Ty); 1966 void *IP = nullptr; 1967 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1968 // Limit recursion depth. 1969 if (Depth > MaxCastDepth) { 1970 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1971 Op, Ty); 1972 UniqueSCEVs.InsertNode(S, IP); 1973 addToLoopUseLists(S); 1974 return S; 1975 } 1976 1977 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1978 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1979 // It's possible the bits taken off by the truncate were all sign bits. If 1980 // so, we should be able to simplify this further. 1981 const SCEV *X = ST->getOperand(); 1982 ConstantRange CR = getSignedRange(X); 1983 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1984 unsigned NewBits = getTypeSizeInBits(Ty); 1985 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1986 CR.sextOrTrunc(NewBits))) 1987 return getTruncateOrSignExtend(X, Ty, Depth); 1988 } 1989 1990 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1991 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1992 if (SA->hasNoSignedWrap()) { 1993 // If the addition does not sign overflow then we can, by definition, 1994 // commute the sign extension with the addition operation. 1995 SmallVector<const SCEV *, 4> Ops; 1996 for (const auto *Op : SA->operands()) 1997 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1998 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1999 } 2000 2001 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2002 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2003 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2004 // 2005 // For instance, this will bring two seemingly different expressions: 2006 // 1 + sext(5 + 20 * %x + 24 * %y) and 2007 // sext(6 + 20 * %x + 24 * %y) 2008 // to the same form: 2009 // 2 + sext(4 + 20 * %x + 24 * %y) 2010 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2011 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2012 if (D != 0) { 2013 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2014 const SCEV *SResidual = 2015 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2016 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2017 return getAddExpr(SSExtD, SSExtR, 2018 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2019 Depth + 1); 2020 } 2021 } 2022 } 2023 // If the input value is a chrec scev, and we can prove that the value 2024 // did not overflow the old, smaller, value, we can sign extend all of the 2025 // operands (often constants). This allows analysis of something like 2026 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2027 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2028 if (AR->isAffine()) { 2029 const SCEV *Start = AR->getStart(); 2030 const SCEV *Step = AR->getStepRecurrence(*this); 2031 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2032 const Loop *L = AR->getLoop(); 2033 2034 if (!AR->hasNoSignedWrap()) { 2035 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2036 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2037 } 2038 2039 // If we have special knowledge that this addrec won't overflow, 2040 // we don't need to do any further analysis. 2041 if (AR->hasNoSignedWrap()) 2042 return getAddRecExpr( 2043 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2044 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2045 2046 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2047 // Note that this serves two purposes: It filters out loops that are 2048 // simply not analyzable, and it covers the case where this code is 2049 // being called from within backedge-taken count analysis, such that 2050 // attempting to ask for the backedge-taken count would likely result 2051 // in infinite recursion. In the later case, the analysis code will 2052 // cope with a conservative value, and it will take care to purge 2053 // that value once it has finished. 2054 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2055 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2056 // Manually compute the final value for AR, checking for 2057 // overflow. 2058 2059 // Check whether the backedge-taken count can be losslessly casted to 2060 // the addrec's type. The count is always unsigned. 2061 const SCEV *CastedMaxBECount = 2062 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2063 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2064 CastedMaxBECount, MaxBECount->getType(), Depth); 2065 if (MaxBECount == RecastedMaxBECount) { 2066 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2067 // Check whether Start+Step*MaxBECount has no signed overflow. 2068 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2069 SCEV::FlagAnyWrap, Depth + 1); 2070 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2071 SCEV::FlagAnyWrap, 2072 Depth + 1), 2073 WideTy, Depth + 1); 2074 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2075 const SCEV *WideMaxBECount = 2076 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2077 const SCEV *OperandExtendedAdd = 2078 getAddExpr(WideStart, 2079 getMulExpr(WideMaxBECount, 2080 getSignExtendExpr(Step, WideTy, Depth + 1), 2081 SCEV::FlagAnyWrap, Depth + 1), 2082 SCEV::FlagAnyWrap, Depth + 1); 2083 if (SAdd == OperandExtendedAdd) { 2084 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2085 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2086 // Return the expression with the addrec on the outside. 2087 return getAddRecExpr( 2088 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2089 Depth + 1), 2090 getSignExtendExpr(Step, Ty, Depth + 1), L, 2091 AR->getNoWrapFlags()); 2092 } 2093 // Similar to above, only this time treat the step value as unsigned. 2094 // This covers loops that count up with an unsigned step. 2095 OperandExtendedAdd = 2096 getAddExpr(WideStart, 2097 getMulExpr(WideMaxBECount, 2098 getZeroExtendExpr(Step, WideTy, Depth + 1), 2099 SCEV::FlagAnyWrap, Depth + 1), 2100 SCEV::FlagAnyWrap, Depth + 1); 2101 if (SAdd == OperandExtendedAdd) { 2102 // If AR wraps around then 2103 // 2104 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2105 // => SAdd != OperandExtendedAdd 2106 // 2107 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2108 // (SAdd == OperandExtendedAdd => AR is NW) 2109 2110 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2111 2112 // Return the expression with the addrec on the outside. 2113 return getAddRecExpr( 2114 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2115 Depth + 1), 2116 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2117 AR->getNoWrapFlags()); 2118 } 2119 } 2120 } 2121 2122 // Normally, in the cases we can prove no-overflow via a 2123 // backedge guarding condition, we can also compute a backedge 2124 // taken count for the loop. The exceptions are assumptions and 2125 // guards present in the loop -- SCEV is not great at exploiting 2126 // these to compute max backedge taken counts, but can still use 2127 // these to prove lack of overflow. Use this fact to avoid 2128 // doing extra work that may not pay off. 2129 2130 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2131 !AC.assumptions().empty()) { 2132 // If the backedge is guarded by a comparison with the pre-inc 2133 // value the addrec is safe. Also, if the entry is guarded by 2134 // a comparison with the start value and the backedge is 2135 // guarded by a comparison with the post-inc value, the addrec 2136 // is safe. 2137 ICmpInst::Predicate Pred; 2138 const SCEV *OverflowLimit = 2139 getSignedOverflowLimitForStep(Step, &Pred, this); 2140 if (OverflowLimit && 2141 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2142 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2143 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2144 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2145 return getAddRecExpr( 2146 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2147 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2148 } 2149 } 2150 2151 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2152 // if D + (C - D + Step * n) could be proven to not signed wrap 2153 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2154 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2155 const APInt &C = SC->getAPInt(); 2156 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2157 if (D != 0) { 2158 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2159 const SCEV *SResidual = 2160 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2161 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2162 return getAddExpr(SSExtD, SSExtR, 2163 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2164 Depth + 1); 2165 } 2166 } 2167 2168 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2169 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2170 return getAddRecExpr( 2171 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2172 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2173 } 2174 } 2175 2176 // If the input value is provably positive and we could not simplify 2177 // away the sext build a zext instead. 2178 if (isKnownNonNegative(Op)) 2179 return getZeroExtendExpr(Op, Ty, Depth + 1); 2180 2181 // The cast wasn't folded; create an explicit cast node. 2182 // Recompute the insert position, as it may have been invalidated. 2183 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2184 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2185 Op, Ty); 2186 UniqueSCEVs.InsertNode(S, IP); 2187 addToLoopUseLists(S); 2188 return S; 2189 } 2190 2191 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2192 /// unspecified bits out to the given type. 2193 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2194 Type *Ty) { 2195 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2196 "This is not an extending conversion!"); 2197 assert(isSCEVable(Ty) && 2198 "This is not a conversion to a SCEVable type!"); 2199 Ty = getEffectiveSCEVType(Ty); 2200 2201 // Sign-extend negative constants. 2202 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2203 if (SC->getAPInt().isNegative()) 2204 return getSignExtendExpr(Op, Ty); 2205 2206 // Peel off a truncate cast. 2207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2208 const SCEV *NewOp = T->getOperand(); 2209 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2210 return getAnyExtendExpr(NewOp, Ty); 2211 return getTruncateOrNoop(NewOp, Ty); 2212 } 2213 2214 // Next try a zext cast. If the cast is folded, use it. 2215 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2216 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2217 return ZExt; 2218 2219 // Next try a sext cast. If the cast is folded, use it. 2220 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2221 if (!isa<SCEVSignExtendExpr>(SExt)) 2222 return SExt; 2223 2224 // Force the cast to be folded into the operands of an addrec. 2225 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2226 SmallVector<const SCEV *, 4> Ops; 2227 for (const SCEV *Op : AR->operands()) 2228 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2229 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2230 } 2231 2232 // If the expression is obviously signed, use the sext cast value. 2233 if (isa<SCEVSMaxExpr>(Op)) 2234 return SExt; 2235 2236 // Absent any other information, use the zext cast value. 2237 return ZExt; 2238 } 2239 2240 /// Process the given Ops list, which is a list of operands to be added under 2241 /// the given scale, update the given map. This is a helper function for 2242 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2243 /// that would form an add expression like this: 2244 /// 2245 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2246 /// 2247 /// where A and B are constants, update the map with these values: 2248 /// 2249 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2250 /// 2251 /// and add 13 + A*B*29 to AccumulatedConstant. 2252 /// This will allow getAddRecExpr to produce this: 2253 /// 2254 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2255 /// 2256 /// This form often exposes folding opportunities that are hidden in 2257 /// the original operand list. 2258 /// 2259 /// Return true iff it appears that any interesting folding opportunities 2260 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2261 /// the common case where no interesting opportunities are present, and 2262 /// is also used as a check to avoid infinite recursion. 2263 static bool 2264 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2265 SmallVectorImpl<const SCEV *> &NewOps, 2266 APInt &AccumulatedConstant, 2267 const SCEV *const *Ops, size_t NumOperands, 2268 const APInt &Scale, 2269 ScalarEvolution &SE) { 2270 bool Interesting = false; 2271 2272 // Iterate over the add operands. They are sorted, with constants first. 2273 unsigned i = 0; 2274 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2275 ++i; 2276 // Pull a buried constant out to the outside. 2277 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2278 Interesting = true; 2279 AccumulatedConstant += Scale * C->getAPInt(); 2280 } 2281 2282 // Next comes everything else. We're especially interested in multiplies 2283 // here, but they're in the middle, so just visit the rest with one loop. 2284 for (; i != NumOperands; ++i) { 2285 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2286 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2287 APInt NewScale = 2288 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2289 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2290 // A multiplication of a constant with another add; recurse. 2291 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2292 Interesting |= 2293 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2294 Add->op_begin(), Add->getNumOperands(), 2295 NewScale, SE); 2296 } else { 2297 // A multiplication of a constant with some other value. Update 2298 // the map. 2299 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2300 const SCEV *Key = SE.getMulExpr(MulOps); 2301 auto Pair = M.insert({Key, NewScale}); 2302 if (Pair.second) { 2303 NewOps.push_back(Pair.first->first); 2304 } else { 2305 Pair.first->second += NewScale; 2306 // The map already had an entry for this value, which may indicate 2307 // a folding opportunity. 2308 Interesting = true; 2309 } 2310 } 2311 } else { 2312 // An ordinary operand. Update the map. 2313 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2314 M.insert({Ops[i], Scale}); 2315 if (Pair.second) { 2316 NewOps.push_back(Pair.first->first); 2317 } else { 2318 Pair.first->second += Scale; 2319 // The map already had an entry for this value, which may indicate 2320 // a folding opportunity. 2321 Interesting = true; 2322 } 2323 } 2324 } 2325 2326 return Interesting; 2327 } 2328 2329 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2330 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2331 // can't-overflow flags for the operation if possible. 2332 static SCEV::NoWrapFlags 2333 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2334 const ArrayRef<const SCEV *> Ops, 2335 SCEV::NoWrapFlags Flags) { 2336 using namespace std::placeholders; 2337 2338 using OBO = OverflowingBinaryOperator; 2339 2340 bool CanAnalyze = 2341 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2342 (void)CanAnalyze; 2343 assert(CanAnalyze && "don't call from other places!"); 2344 2345 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2346 SCEV::NoWrapFlags SignOrUnsignWrap = 2347 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2348 2349 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2350 auto IsKnownNonNegative = [&](const SCEV *S) { 2351 return SE->isKnownNonNegative(S); 2352 }; 2353 2354 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2355 Flags = 2356 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2357 2358 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2359 2360 if (SignOrUnsignWrap != SignOrUnsignMask && 2361 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2362 isa<SCEVConstant>(Ops[0])) { 2363 2364 auto Opcode = [&] { 2365 switch (Type) { 2366 case scAddExpr: 2367 return Instruction::Add; 2368 case scMulExpr: 2369 return Instruction::Mul; 2370 default: 2371 llvm_unreachable("Unexpected SCEV op."); 2372 } 2373 }(); 2374 2375 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2376 2377 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2378 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2379 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2380 Opcode, C, OBO::NoSignedWrap); 2381 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2382 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2383 } 2384 2385 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2386 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2387 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2388 Opcode, C, OBO::NoUnsignedWrap); 2389 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2390 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2391 } 2392 } 2393 2394 return Flags; 2395 } 2396 2397 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2398 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2399 } 2400 2401 /// Get a canonical add expression, or something simpler if possible. 2402 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2403 SCEV::NoWrapFlags Flags, 2404 unsigned Depth) { 2405 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2406 "only nuw or nsw allowed"); 2407 assert(!Ops.empty() && "Cannot get empty add!"); 2408 if (Ops.size() == 1) return Ops[0]; 2409 #ifndef NDEBUG 2410 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2411 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2412 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2413 "SCEVAddExpr operand types don't match!"); 2414 #endif 2415 2416 // Sort by complexity, this groups all similar expression types together. 2417 GroupByComplexity(Ops, &LI, DT); 2418 2419 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2420 2421 // If there are any constants, fold them together. 2422 unsigned Idx = 0; 2423 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2424 ++Idx; 2425 assert(Idx < Ops.size()); 2426 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2427 // We found two constants, fold them together! 2428 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2429 if (Ops.size() == 2) return Ops[0]; 2430 Ops.erase(Ops.begin()+1); // Erase the folded element 2431 LHSC = cast<SCEVConstant>(Ops[0]); 2432 } 2433 2434 // If we are left with a constant zero being added, strip it off. 2435 if (LHSC->getValue()->isZero()) { 2436 Ops.erase(Ops.begin()); 2437 --Idx; 2438 } 2439 2440 if (Ops.size() == 1) return Ops[0]; 2441 } 2442 2443 // Limit recursion calls depth. 2444 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2445 return getOrCreateAddExpr(Ops, Flags); 2446 2447 // Okay, check to see if the same value occurs in the operand list more than 2448 // once. If so, merge them together into an multiply expression. Since we 2449 // sorted the list, these values are required to be adjacent. 2450 Type *Ty = Ops[0]->getType(); 2451 bool FoundMatch = false; 2452 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2453 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2454 // Scan ahead to count how many equal operands there are. 2455 unsigned Count = 2; 2456 while (i+Count != e && Ops[i+Count] == Ops[i]) 2457 ++Count; 2458 // Merge the values into a multiply. 2459 const SCEV *Scale = getConstant(Ty, Count); 2460 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2461 if (Ops.size() == Count) 2462 return Mul; 2463 Ops[i] = Mul; 2464 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2465 --i; e -= Count - 1; 2466 FoundMatch = true; 2467 } 2468 if (FoundMatch) 2469 return getAddExpr(Ops, Flags, Depth + 1); 2470 2471 // Check for truncates. If all the operands are truncated from the same 2472 // type, see if factoring out the truncate would permit the result to be 2473 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2474 // if the contents of the resulting outer trunc fold to something simple. 2475 auto FindTruncSrcType = [&]() -> Type * { 2476 // We're ultimately looking to fold an addrec of truncs and muls of only 2477 // constants and truncs, so if we find any other types of SCEV 2478 // as operands of the addrec then we bail and return nullptr here. 2479 // Otherwise, we return the type of the operand of a trunc that we find. 2480 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2481 return T->getOperand()->getType(); 2482 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2483 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2484 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2485 return T->getOperand()->getType(); 2486 } 2487 return nullptr; 2488 }; 2489 if (auto *SrcType = FindTruncSrcType()) { 2490 SmallVector<const SCEV *, 8> LargeOps; 2491 bool Ok = true; 2492 // Check all the operands to see if they can be represented in the 2493 // source type of the truncate. 2494 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2495 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2496 if (T->getOperand()->getType() != SrcType) { 2497 Ok = false; 2498 break; 2499 } 2500 LargeOps.push_back(T->getOperand()); 2501 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2502 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2503 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2504 SmallVector<const SCEV *, 8> LargeMulOps; 2505 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2506 if (const SCEVTruncateExpr *T = 2507 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2508 if (T->getOperand()->getType() != SrcType) { 2509 Ok = false; 2510 break; 2511 } 2512 LargeMulOps.push_back(T->getOperand()); 2513 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2514 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2515 } else { 2516 Ok = false; 2517 break; 2518 } 2519 } 2520 if (Ok) 2521 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2522 } else { 2523 Ok = false; 2524 break; 2525 } 2526 } 2527 if (Ok) { 2528 // Evaluate the expression in the larger type. 2529 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2530 // If it folds to something simple, use it. Otherwise, don't. 2531 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2532 return getTruncateExpr(Fold, Ty); 2533 } 2534 } 2535 2536 // Skip past any other cast SCEVs. 2537 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2538 ++Idx; 2539 2540 // If there are add operands they would be next. 2541 if (Idx < Ops.size()) { 2542 bool DeletedAdd = false; 2543 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2544 if (Ops.size() > AddOpsInlineThreshold || 2545 Add->getNumOperands() > AddOpsInlineThreshold) 2546 break; 2547 // If we have an add, expand the add operands onto the end of the operands 2548 // list. 2549 Ops.erase(Ops.begin()+Idx); 2550 Ops.append(Add->op_begin(), Add->op_end()); 2551 DeletedAdd = true; 2552 } 2553 2554 // If we deleted at least one add, we added operands to the end of the list, 2555 // and they are not necessarily sorted. Recurse to resort and resimplify 2556 // any operands we just acquired. 2557 if (DeletedAdd) 2558 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2559 } 2560 2561 // Skip over the add expression until we get to a multiply. 2562 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2563 ++Idx; 2564 2565 // Check to see if there are any folding opportunities present with 2566 // operands multiplied by constant values. 2567 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2568 uint64_t BitWidth = getTypeSizeInBits(Ty); 2569 DenseMap<const SCEV *, APInt> M; 2570 SmallVector<const SCEV *, 8> NewOps; 2571 APInt AccumulatedConstant(BitWidth, 0); 2572 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2573 Ops.data(), Ops.size(), 2574 APInt(BitWidth, 1), *this)) { 2575 struct APIntCompare { 2576 bool operator()(const APInt &LHS, const APInt &RHS) const { 2577 return LHS.ult(RHS); 2578 } 2579 }; 2580 2581 // Some interesting folding opportunity is present, so its worthwhile to 2582 // re-generate the operands list. Group the operands by constant scale, 2583 // to avoid multiplying by the same constant scale multiple times. 2584 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2585 for (const SCEV *NewOp : NewOps) 2586 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2587 // Re-generate the operands list. 2588 Ops.clear(); 2589 if (AccumulatedConstant != 0) 2590 Ops.push_back(getConstant(AccumulatedConstant)); 2591 for (auto &MulOp : MulOpLists) 2592 if (MulOp.first != 0) 2593 Ops.push_back(getMulExpr( 2594 getConstant(MulOp.first), 2595 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2596 SCEV::FlagAnyWrap, Depth + 1)); 2597 if (Ops.empty()) 2598 return getZero(Ty); 2599 if (Ops.size() == 1) 2600 return Ops[0]; 2601 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2602 } 2603 } 2604 2605 // If we are adding something to a multiply expression, make sure the 2606 // something is not already an operand of the multiply. If so, merge it into 2607 // the multiply. 2608 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2609 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2610 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2611 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2612 if (isa<SCEVConstant>(MulOpSCEV)) 2613 continue; 2614 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2615 if (MulOpSCEV == Ops[AddOp]) { 2616 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2617 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2618 if (Mul->getNumOperands() != 2) { 2619 // If the multiply has more than two operands, we must get the 2620 // Y*Z term. 2621 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2622 Mul->op_begin()+MulOp); 2623 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2624 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2625 } 2626 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2627 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2628 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2629 SCEV::FlagAnyWrap, Depth + 1); 2630 if (Ops.size() == 2) return OuterMul; 2631 if (AddOp < Idx) { 2632 Ops.erase(Ops.begin()+AddOp); 2633 Ops.erase(Ops.begin()+Idx-1); 2634 } else { 2635 Ops.erase(Ops.begin()+Idx); 2636 Ops.erase(Ops.begin()+AddOp-1); 2637 } 2638 Ops.push_back(OuterMul); 2639 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2640 } 2641 2642 // Check this multiply against other multiplies being added together. 2643 for (unsigned OtherMulIdx = Idx+1; 2644 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2645 ++OtherMulIdx) { 2646 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2647 // If MulOp occurs in OtherMul, we can fold the two multiplies 2648 // together. 2649 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2650 OMulOp != e; ++OMulOp) 2651 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2652 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2653 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2654 if (Mul->getNumOperands() != 2) { 2655 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2656 Mul->op_begin()+MulOp); 2657 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2658 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2659 } 2660 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2661 if (OtherMul->getNumOperands() != 2) { 2662 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2663 OtherMul->op_begin()+OMulOp); 2664 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2665 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2666 } 2667 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2668 const SCEV *InnerMulSum = 2669 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2670 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2671 SCEV::FlagAnyWrap, Depth + 1); 2672 if (Ops.size() == 2) return OuterMul; 2673 Ops.erase(Ops.begin()+Idx); 2674 Ops.erase(Ops.begin()+OtherMulIdx-1); 2675 Ops.push_back(OuterMul); 2676 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2677 } 2678 } 2679 } 2680 } 2681 2682 // If there are any add recurrences in the operands list, see if any other 2683 // added values are loop invariant. If so, we can fold them into the 2684 // recurrence. 2685 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2686 ++Idx; 2687 2688 // Scan over all recurrences, trying to fold loop invariants into them. 2689 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2690 // Scan all of the other operands to this add and add them to the vector if 2691 // they are loop invariant w.r.t. the recurrence. 2692 SmallVector<const SCEV *, 8> LIOps; 2693 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2694 const Loop *AddRecLoop = AddRec->getLoop(); 2695 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2696 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2697 LIOps.push_back(Ops[i]); 2698 Ops.erase(Ops.begin()+i); 2699 --i; --e; 2700 } 2701 2702 // If we found some loop invariants, fold them into the recurrence. 2703 if (!LIOps.empty()) { 2704 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2705 LIOps.push_back(AddRec->getStart()); 2706 2707 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2708 AddRec->op_end()); 2709 // This follows from the fact that the no-wrap flags on the outer add 2710 // expression are applicable on the 0th iteration, when the add recurrence 2711 // will be equal to its start value. 2712 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2713 2714 // Build the new addrec. Propagate the NUW and NSW flags if both the 2715 // outer add and the inner addrec are guaranteed to have no overflow. 2716 // Always propagate NW. 2717 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2718 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2719 2720 // If all of the other operands were loop invariant, we are done. 2721 if (Ops.size() == 1) return NewRec; 2722 2723 // Otherwise, add the folded AddRec by the non-invariant parts. 2724 for (unsigned i = 0;; ++i) 2725 if (Ops[i] == AddRec) { 2726 Ops[i] = NewRec; 2727 break; 2728 } 2729 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2730 } 2731 2732 // Okay, if there weren't any loop invariants to be folded, check to see if 2733 // there are multiple AddRec's with the same loop induction variable being 2734 // added together. If so, we can fold them. 2735 for (unsigned OtherIdx = Idx+1; 2736 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2737 ++OtherIdx) { 2738 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2739 // so that the 1st found AddRecExpr is dominated by all others. 2740 assert(DT.dominates( 2741 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2742 AddRec->getLoop()->getHeader()) && 2743 "AddRecExprs are not sorted in reverse dominance order?"); 2744 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2745 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2746 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2747 AddRec->op_end()); 2748 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2749 ++OtherIdx) { 2750 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2751 if (OtherAddRec->getLoop() == AddRecLoop) { 2752 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2753 i != e; ++i) { 2754 if (i >= AddRecOps.size()) { 2755 AddRecOps.append(OtherAddRec->op_begin()+i, 2756 OtherAddRec->op_end()); 2757 break; 2758 } 2759 SmallVector<const SCEV *, 2> TwoOps = { 2760 AddRecOps[i], OtherAddRec->getOperand(i)}; 2761 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2762 } 2763 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2764 } 2765 } 2766 // Step size has changed, so we cannot guarantee no self-wraparound. 2767 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2768 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2769 } 2770 } 2771 2772 // Otherwise couldn't fold anything into this recurrence. Move onto the 2773 // next one. 2774 } 2775 2776 // Okay, it looks like we really DO need an add expr. Check to see if we 2777 // already have one, otherwise create a new one. 2778 return getOrCreateAddExpr(Ops, Flags); 2779 } 2780 2781 const SCEV * 2782 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2783 SCEV::NoWrapFlags Flags) { 2784 FoldingSetNodeID ID; 2785 ID.AddInteger(scAddExpr); 2786 for (const SCEV *Op : Ops) 2787 ID.AddPointer(Op); 2788 void *IP = nullptr; 2789 SCEVAddExpr *S = 2790 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2791 if (!S) { 2792 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2793 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2794 S = new (SCEVAllocator) 2795 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2796 UniqueSCEVs.InsertNode(S, IP); 2797 addToLoopUseLists(S); 2798 } 2799 S->setNoWrapFlags(Flags); 2800 return S; 2801 } 2802 2803 const SCEV * 2804 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2805 const Loop *L, SCEV::NoWrapFlags Flags) { 2806 FoldingSetNodeID ID; 2807 ID.AddInteger(scAddRecExpr); 2808 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2809 ID.AddPointer(Ops[i]); 2810 ID.AddPointer(L); 2811 void *IP = nullptr; 2812 SCEVAddRecExpr *S = 2813 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2814 if (!S) { 2815 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2816 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2817 S = new (SCEVAllocator) 2818 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2819 UniqueSCEVs.InsertNode(S, IP); 2820 addToLoopUseLists(S); 2821 } 2822 S->setNoWrapFlags(Flags); 2823 return S; 2824 } 2825 2826 const SCEV * 2827 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2828 SCEV::NoWrapFlags Flags) { 2829 FoldingSetNodeID ID; 2830 ID.AddInteger(scMulExpr); 2831 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2832 ID.AddPointer(Ops[i]); 2833 void *IP = nullptr; 2834 SCEVMulExpr *S = 2835 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2836 if (!S) { 2837 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2838 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2839 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2840 O, Ops.size()); 2841 UniqueSCEVs.InsertNode(S, IP); 2842 addToLoopUseLists(S); 2843 } 2844 S->setNoWrapFlags(Flags); 2845 return S; 2846 } 2847 2848 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2849 uint64_t k = i*j; 2850 if (j > 1 && k / j != i) Overflow = true; 2851 return k; 2852 } 2853 2854 /// Compute the result of "n choose k", the binomial coefficient. If an 2855 /// intermediate computation overflows, Overflow will be set and the return will 2856 /// be garbage. Overflow is not cleared on absence of overflow. 2857 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2858 // We use the multiplicative formula: 2859 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2860 // At each iteration, we take the n-th term of the numeral and divide by the 2861 // (k-n)th term of the denominator. This division will always produce an 2862 // integral result, and helps reduce the chance of overflow in the 2863 // intermediate computations. However, we can still overflow even when the 2864 // final result would fit. 2865 2866 if (n == 0 || n == k) return 1; 2867 if (k > n) return 0; 2868 2869 if (k > n/2) 2870 k = n-k; 2871 2872 uint64_t r = 1; 2873 for (uint64_t i = 1; i <= k; ++i) { 2874 r = umul_ov(r, n-(i-1), Overflow); 2875 r /= i; 2876 } 2877 return r; 2878 } 2879 2880 /// Determine if any of the operands in this SCEV are a constant or if 2881 /// any of the add or multiply expressions in this SCEV contain a constant. 2882 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2883 struct FindConstantInAddMulChain { 2884 bool FoundConstant = false; 2885 2886 bool follow(const SCEV *S) { 2887 FoundConstant |= isa<SCEVConstant>(S); 2888 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2889 } 2890 2891 bool isDone() const { 2892 return FoundConstant; 2893 } 2894 }; 2895 2896 FindConstantInAddMulChain F; 2897 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2898 ST.visitAll(StartExpr); 2899 return F.FoundConstant; 2900 } 2901 2902 /// Get a canonical multiply expression, or something simpler if possible. 2903 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2904 SCEV::NoWrapFlags Flags, 2905 unsigned Depth) { 2906 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2907 "only nuw or nsw allowed"); 2908 assert(!Ops.empty() && "Cannot get empty mul!"); 2909 if (Ops.size() == 1) return Ops[0]; 2910 #ifndef NDEBUG 2911 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2912 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2913 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2914 "SCEVMulExpr operand types don't match!"); 2915 #endif 2916 2917 // Sort by complexity, this groups all similar expression types together. 2918 GroupByComplexity(Ops, &LI, DT); 2919 2920 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2921 2922 // Limit recursion calls depth. 2923 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2924 return getOrCreateMulExpr(Ops, Flags); 2925 2926 // If there are any constants, fold them together. 2927 unsigned Idx = 0; 2928 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2929 2930 if (Ops.size() == 2) 2931 // C1*(C2+V) -> C1*C2 + C1*V 2932 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2933 // If any of Add's ops are Adds or Muls with a constant, apply this 2934 // transformation as well. 2935 // 2936 // TODO: There are some cases where this transformation is not 2937 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2938 // this transformation should be narrowed down. 2939 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2940 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2941 SCEV::FlagAnyWrap, Depth + 1), 2942 getMulExpr(LHSC, Add->getOperand(1), 2943 SCEV::FlagAnyWrap, Depth + 1), 2944 SCEV::FlagAnyWrap, Depth + 1); 2945 2946 ++Idx; 2947 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2948 // We found two constants, fold them together! 2949 ConstantInt *Fold = 2950 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2951 Ops[0] = getConstant(Fold); 2952 Ops.erase(Ops.begin()+1); // Erase the folded element 2953 if (Ops.size() == 1) return Ops[0]; 2954 LHSC = cast<SCEVConstant>(Ops[0]); 2955 } 2956 2957 // If we are left with a constant one being multiplied, strip it off. 2958 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2959 Ops.erase(Ops.begin()); 2960 --Idx; 2961 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2962 // If we have a multiply of zero, it will always be zero. 2963 return Ops[0]; 2964 } else if (Ops[0]->isAllOnesValue()) { 2965 // If we have a mul by -1 of an add, try distributing the -1 among the 2966 // add operands. 2967 if (Ops.size() == 2) { 2968 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2969 SmallVector<const SCEV *, 4> NewOps; 2970 bool AnyFolded = false; 2971 for (const SCEV *AddOp : Add->operands()) { 2972 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2973 Depth + 1); 2974 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2975 NewOps.push_back(Mul); 2976 } 2977 if (AnyFolded) 2978 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2979 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2980 // Negation preserves a recurrence's no self-wrap property. 2981 SmallVector<const SCEV *, 4> Operands; 2982 for (const SCEV *AddRecOp : AddRec->operands()) 2983 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2984 Depth + 1)); 2985 2986 return getAddRecExpr(Operands, AddRec->getLoop(), 2987 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2988 } 2989 } 2990 } 2991 2992 if (Ops.size() == 1) 2993 return Ops[0]; 2994 } 2995 2996 // Skip over the add expression until we get to a multiply. 2997 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2998 ++Idx; 2999 3000 // If there are mul operands inline them all into this expression. 3001 if (Idx < Ops.size()) { 3002 bool DeletedMul = false; 3003 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3004 if (Ops.size() > MulOpsInlineThreshold) 3005 break; 3006 // If we have an mul, expand the mul operands onto the end of the 3007 // operands list. 3008 Ops.erase(Ops.begin()+Idx); 3009 Ops.append(Mul->op_begin(), Mul->op_end()); 3010 DeletedMul = true; 3011 } 3012 3013 // If we deleted at least one mul, we added operands to the end of the 3014 // list, and they are not necessarily sorted. Recurse to resort and 3015 // resimplify any operands we just acquired. 3016 if (DeletedMul) 3017 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3018 } 3019 3020 // If there are any add recurrences in the operands list, see if any other 3021 // added values are loop invariant. If so, we can fold them into the 3022 // recurrence. 3023 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3024 ++Idx; 3025 3026 // Scan over all recurrences, trying to fold loop invariants into them. 3027 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3028 // Scan all of the other operands to this mul and add them to the vector 3029 // if they are loop invariant w.r.t. the recurrence. 3030 SmallVector<const SCEV *, 8> LIOps; 3031 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3032 const Loop *AddRecLoop = AddRec->getLoop(); 3033 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3034 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3035 LIOps.push_back(Ops[i]); 3036 Ops.erase(Ops.begin()+i); 3037 --i; --e; 3038 } 3039 3040 // If we found some loop invariants, fold them into the recurrence. 3041 if (!LIOps.empty()) { 3042 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3043 SmallVector<const SCEV *, 4> NewOps; 3044 NewOps.reserve(AddRec->getNumOperands()); 3045 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3047 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3048 SCEV::FlagAnyWrap, Depth + 1)); 3049 3050 // Build the new addrec. Propagate the NUW and NSW flags if both the 3051 // outer mul and the inner addrec are guaranteed to have no overflow. 3052 // 3053 // No self-wrap cannot be guaranteed after changing the step size, but 3054 // will be inferred if either NUW or NSW is true. 3055 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3056 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3057 3058 // If all of the other operands were loop invariant, we are done. 3059 if (Ops.size() == 1) return NewRec; 3060 3061 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3062 for (unsigned i = 0;; ++i) 3063 if (Ops[i] == AddRec) { 3064 Ops[i] = NewRec; 3065 break; 3066 } 3067 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3068 } 3069 3070 // Okay, if there weren't any loop invariants to be folded, check to see 3071 // if there are multiple AddRec's with the same loop induction variable 3072 // being multiplied together. If so, we can fold them. 3073 3074 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3075 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3076 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3077 // ]]],+,...up to x=2n}. 3078 // Note that the arguments to choose() are always integers with values 3079 // known at compile time, never SCEV objects. 3080 // 3081 // The implementation avoids pointless extra computations when the two 3082 // addrec's are of different length (mathematically, it's equivalent to 3083 // an infinite stream of zeros on the right). 3084 bool OpsModified = false; 3085 for (unsigned OtherIdx = Idx+1; 3086 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3087 ++OtherIdx) { 3088 const SCEVAddRecExpr *OtherAddRec = 3089 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3090 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3091 continue; 3092 3093 // Limit max number of arguments to avoid creation of unreasonably big 3094 // SCEVAddRecs with very complex operands. 3095 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3096 MaxAddRecSize || isHugeExpression(AddRec) || 3097 isHugeExpression(OtherAddRec)) 3098 continue; 3099 3100 bool Overflow = false; 3101 Type *Ty = AddRec->getType(); 3102 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3103 SmallVector<const SCEV*, 7> AddRecOps; 3104 for (int x = 0, xe = AddRec->getNumOperands() + 3105 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3106 SmallVector <const SCEV *, 7> SumOps; 3107 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3108 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3109 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3110 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3111 z < ze && !Overflow; ++z) { 3112 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3113 uint64_t Coeff; 3114 if (LargerThan64Bits) 3115 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3116 else 3117 Coeff = Coeff1*Coeff2; 3118 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3119 const SCEV *Term1 = AddRec->getOperand(y-z); 3120 const SCEV *Term2 = OtherAddRec->getOperand(z); 3121 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3122 SCEV::FlagAnyWrap, Depth + 1)); 3123 } 3124 } 3125 if (SumOps.empty()) 3126 SumOps.push_back(getZero(Ty)); 3127 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3128 } 3129 if (!Overflow) { 3130 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3131 SCEV::FlagAnyWrap); 3132 if (Ops.size() == 2) return NewAddRec; 3133 Ops[Idx] = NewAddRec; 3134 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3135 OpsModified = true; 3136 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3137 if (!AddRec) 3138 break; 3139 } 3140 } 3141 if (OpsModified) 3142 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3143 3144 // Otherwise couldn't fold anything into this recurrence. Move onto the 3145 // next one. 3146 } 3147 3148 // Okay, it looks like we really DO need an mul expr. Check to see if we 3149 // already have one, otherwise create a new one. 3150 return getOrCreateMulExpr(Ops, Flags); 3151 } 3152 3153 /// Represents an unsigned remainder expression based on unsigned division. 3154 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3155 const SCEV *RHS) { 3156 assert(getEffectiveSCEVType(LHS->getType()) == 3157 getEffectiveSCEVType(RHS->getType()) && 3158 "SCEVURemExpr operand types don't match!"); 3159 3160 // Short-circuit easy cases 3161 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3162 // If constant is one, the result is trivial 3163 if (RHSC->getValue()->isOne()) 3164 return getZero(LHS->getType()); // X urem 1 --> 0 3165 3166 // If constant is a power of two, fold into a zext(trunc(LHS)). 3167 if (RHSC->getAPInt().isPowerOf2()) { 3168 Type *FullTy = LHS->getType(); 3169 Type *TruncTy = 3170 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3171 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3172 } 3173 } 3174 3175 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3176 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3177 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3178 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3179 } 3180 3181 /// Get a canonical unsigned division expression, or something simpler if 3182 /// possible. 3183 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3184 const SCEV *RHS) { 3185 assert(getEffectiveSCEVType(LHS->getType()) == 3186 getEffectiveSCEVType(RHS->getType()) && 3187 "SCEVUDivExpr operand types don't match!"); 3188 3189 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3190 if (RHSC->getValue()->isOne()) 3191 return LHS; // X udiv 1 --> x 3192 // If the denominator is zero, the result of the udiv is undefined. Don't 3193 // try to analyze it, because the resolution chosen here may differ from 3194 // the resolution chosen in other parts of the compiler. 3195 if (!RHSC->getValue()->isZero()) { 3196 // Determine if the division can be folded into the operands of 3197 // its operands. 3198 // TODO: Generalize this to non-constants by using known-bits information. 3199 Type *Ty = LHS->getType(); 3200 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3201 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3202 // For non-power-of-two values, effectively round the value up to the 3203 // nearest power of two. 3204 if (!RHSC->getAPInt().isPowerOf2()) 3205 ++MaxShiftAmt; 3206 IntegerType *ExtTy = 3207 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3208 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3209 if (const SCEVConstant *Step = 3210 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3211 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3212 const APInt &StepInt = Step->getAPInt(); 3213 const APInt &DivInt = RHSC->getAPInt(); 3214 if (!StepInt.urem(DivInt) && 3215 getZeroExtendExpr(AR, ExtTy) == 3216 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3217 getZeroExtendExpr(Step, ExtTy), 3218 AR->getLoop(), SCEV::FlagAnyWrap)) { 3219 SmallVector<const SCEV *, 4> Operands; 3220 for (const SCEV *Op : AR->operands()) 3221 Operands.push_back(getUDivExpr(Op, RHS)); 3222 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3223 } 3224 /// Get a canonical UDivExpr for a recurrence. 3225 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3226 // We can currently only fold X%N if X is constant. 3227 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3228 if (StartC && !DivInt.urem(StepInt) && 3229 getZeroExtendExpr(AR, ExtTy) == 3230 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3231 getZeroExtendExpr(Step, ExtTy), 3232 AR->getLoop(), SCEV::FlagAnyWrap)) { 3233 const APInt &StartInt = StartC->getAPInt(); 3234 const APInt &StartRem = StartInt.urem(StepInt); 3235 if (StartRem != 0) 3236 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3237 AR->getLoop(), SCEV::FlagNW); 3238 } 3239 } 3240 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3241 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3242 SmallVector<const SCEV *, 4> Operands; 3243 for (const SCEV *Op : M->operands()) 3244 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3245 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3246 // Find an operand that's safely divisible. 3247 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3248 const SCEV *Op = M->getOperand(i); 3249 const SCEV *Div = getUDivExpr(Op, RHSC); 3250 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3251 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3252 M->op_end()); 3253 Operands[i] = Div; 3254 return getMulExpr(Operands); 3255 } 3256 } 3257 } 3258 3259 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3260 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3261 if (auto *DivisorConstant = 3262 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3263 bool Overflow = false; 3264 APInt NewRHS = 3265 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3266 if (Overflow) { 3267 return getConstant(RHSC->getType(), 0, false); 3268 } 3269 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3270 } 3271 } 3272 3273 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3274 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3275 SmallVector<const SCEV *, 4> Operands; 3276 for (const SCEV *Op : A->operands()) 3277 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3278 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3279 Operands.clear(); 3280 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3281 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3282 if (isa<SCEVUDivExpr>(Op) || 3283 getMulExpr(Op, RHS) != A->getOperand(i)) 3284 break; 3285 Operands.push_back(Op); 3286 } 3287 if (Operands.size() == A->getNumOperands()) 3288 return getAddExpr(Operands); 3289 } 3290 } 3291 3292 // Fold if both operands are constant. 3293 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3294 Constant *LHSCV = LHSC->getValue(); 3295 Constant *RHSCV = RHSC->getValue(); 3296 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3297 RHSCV))); 3298 } 3299 } 3300 } 3301 3302 FoldingSetNodeID ID; 3303 ID.AddInteger(scUDivExpr); 3304 ID.AddPointer(LHS); 3305 ID.AddPointer(RHS); 3306 void *IP = nullptr; 3307 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3308 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3309 LHS, RHS); 3310 UniqueSCEVs.InsertNode(S, IP); 3311 addToLoopUseLists(S); 3312 return S; 3313 } 3314 3315 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3316 APInt A = C1->getAPInt().abs(); 3317 APInt B = C2->getAPInt().abs(); 3318 uint32_t ABW = A.getBitWidth(); 3319 uint32_t BBW = B.getBitWidth(); 3320 3321 if (ABW > BBW) 3322 B = B.zext(ABW); 3323 else if (ABW < BBW) 3324 A = A.zext(BBW); 3325 3326 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3327 } 3328 3329 /// Get a canonical unsigned division expression, or something simpler if 3330 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3331 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3332 /// it's not exact because the udiv may be clearing bits. 3333 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3334 const SCEV *RHS) { 3335 // TODO: we could try to find factors in all sorts of things, but for now we 3336 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3337 // end of this file for inspiration. 3338 3339 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3340 if (!Mul || !Mul->hasNoUnsignedWrap()) 3341 return getUDivExpr(LHS, RHS); 3342 3343 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3344 // If the mulexpr multiplies by a constant, then that constant must be the 3345 // first element of the mulexpr. 3346 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3347 if (LHSCst == RHSCst) { 3348 SmallVector<const SCEV *, 2> Operands; 3349 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3350 return getMulExpr(Operands); 3351 } 3352 3353 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3354 // that there's a factor provided by one of the other terms. We need to 3355 // check. 3356 APInt Factor = gcd(LHSCst, RHSCst); 3357 if (!Factor.isIntN(1)) { 3358 LHSCst = 3359 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3360 RHSCst = 3361 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3362 SmallVector<const SCEV *, 2> Operands; 3363 Operands.push_back(LHSCst); 3364 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3365 LHS = getMulExpr(Operands); 3366 RHS = RHSCst; 3367 Mul = dyn_cast<SCEVMulExpr>(LHS); 3368 if (!Mul) 3369 return getUDivExactExpr(LHS, RHS); 3370 } 3371 } 3372 } 3373 3374 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3375 if (Mul->getOperand(i) == RHS) { 3376 SmallVector<const SCEV *, 2> Operands; 3377 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3378 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3379 return getMulExpr(Operands); 3380 } 3381 } 3382 3383 return getUDivExpr(LHS, RHS); 3384 } 3385 3386 /// Get an add recurrence expression for the specified loop. Simplify the 3387 /// expression as much as possible. 3388 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3389 const Loop *L, 3390 SCEV::NoWrapFlags Flags) { 3391 SmallVector<const SCEV *, 4> Operands; 3392 Operands.push_back(Start); 3393 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3394 if (StepChrec->getLoop() == L) { 3395 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3396 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3397 } 3398 3399 Operands.push_back(Step); 3400 return getAddRecExpr(Operands, L, Flags); 3401 } 3402 3403 /// Get an add recurrence expression for the specified loop. Simplify the 3404 /// expression as much as possible. 3405 const SCEV * 3406 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3407 const Loop *L, SCEV::NoWrapFlags Flags) { 3408 if (Operands.size() == 1) return Operands[0]; 3409 #ifndef NDEBUG 3410 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3411 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3412 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3413 "SCEVAddRecExpr operand types don't match!"); 3414 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3415 assert(isLoopInvariant(Operands[i], L) && 3416 "SCEVAddRecExpr operand is not loop-invariant!"); 3417 #endif 3418 3419 if (Operands.back()->isZero()) { 3420 Operands.pop_back(); 3421 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3422 } 3423 3424 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3425 // use that information to infer NUW and NSW flags. However, computing a 3426 // BE count requires calling getAddRecExpr, so we may not yet have a 3427 // meaningful BE count at this point (and if we don't, we'd be stuck 3428 // with a SCEVCouldNotCompute as the cached BE count). 3429 3430 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3431 3432 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3433 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3434 const Loop *NestedLoop = NestedAR->getLoop(); 3435 if (L->contains(NestedLoop) 3436 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3437 : (!NestedLoop->contains(L) && 3438 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3439 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3440 NestedAR->op_end()); 3441 Operands[0] = NestedAR->getStart(); 3442 // AddRecs require their operands be loop-invariant with respect to their 3443 // loops. Don't perform this transformation if it would break this 3444 // requirement. 3445 bool AllInvariant = all_of( 3446 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3447 3448 if (AllInvariant) { 3449 // Create a recurrence for the outer loop with the same step size. 3450 // 3451 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3452 // inner recurrence has the same property. 3453 SCEV::NoWrapFlags OuterFlags = 3454 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3455 3456 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3457 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3458 return isLoopInvariant(Op, NestedLoop); 3459 }); 3460 3461 if (AllInvariant) { 3462 // Ok, both add recurrences are valid after the transformation. 3463 // 3464 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3465 // the outer recurrence has the same property. 3466 SCEV::NoWrapFlags InnerFlags = 3467 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3468 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3469 } 3470 } 3471 // Reset Operands to its original state. 3472 Operands[0] = NestedAR; 3473 } 3474 } 3475 3476 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3477 // already have one, otherwise create a new one. 3478 return getOrCreateAddRecExpr(Operands, L, Flags); 3479 } 3480 3481 const SCEV * 3482 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3483 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3484 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3485 // getSCEV(Base)->getType() has the same address space as Base->getType() 3486 // because SCEV::getType() preserves the address space. 3487 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3488 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3489 // instruction to its SCEV, because the Instruction may be guarded by control 3490 // flow and the no-overflow bits may not be valid for the expression in any 3491 // context. This can be fixed similarly to how these flags are handled for 3492 // adds. 3493 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3494 : SCEV::FlagAnyWrap; 3495 3496 const SCEV *TotalOffset = getZero(IntPtrTy); 3497 // The array size is unimportant. The first thing we do on CurTy is getting 3498 // its element type. 3499 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3500 for (const SCEV *IndexExpr : IndexExprs) { 3501 // Compute the (potentially symbolic) offset in bytes for this index. 3502 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3503 // For a struct, add the member offset. 3504 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3505 unsigned FieldNo = Index->getZExtValue(); 3506 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3507 3508 // Add the field offset to the running total offset. 3509 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3510 3511 // Update CurTy to the type of the field at Index. 3512 CurTy = STy->getTypeAtIndex(Index); 3513 } else { 3514 // Update CurTy to its element type. 3515 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3516 // For an array, add the element offset, explicitly scaled. 3517 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3518 // Getelementptr indices are signed. 3519 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3520 3521 // Multiply the index by the element size to compute the element offset. 3522 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3523 3524 // Add the element offset to the running total offset. 3525 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3526 } 3527 } 3528 3529 // Add the total offset from all the GEP indices to the base. 3530 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3531 } 3532 3533 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3534 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3535 ArrayRef<const SCEV *> Ops) { 3536 FoldingSetNodeID ID; 3537 void *IP = nullptr; 3538 ID.AddInteger(SCEVType); 3539 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3540 ID.AddPointer(Ops[i]); 3541 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3542 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3543 } 3544 3545 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3546 SmallVectorImpl<const SCEV *> &Ops) { 3547 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3548 if (Ops.size() == 1) return Ops[0]; 3549 #ifndef NDEBUG 3550 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3551 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3552 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3553 "Operand types don't match!"); 3554 #endif 3555 3556 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3557 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3558 3559 // Sort by complexity, this groups all similar expression types together. 3560 GroupByComplexity(Ops, &LI, DT); 3561 3562 // Check if we have created the same expression before. 3563 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3564 return S; 3565 } 3566 3567 // If there are any constants, fold them together. 3568 unsigned Idx = 0; 3569 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3570 ++Idx; 3571 assert(Idx < Ops.size()); 3572 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3573 if (Kind == scSMaxExpr) 3574 return APIntOps::smax(LHS, RHS); 3575 else if (Kind == scSMinExpr) 3576 return APIntOps::smin(LHS, RHS); 3577 else if (Kind == scUMaxExpr) 3578 return APIntOps::umax(LHS, RHS); 3579 else if (Kind == scUMinExpr) 3580 return APIntOps::umin(LHS, RHS); 3581 llvm_unreachable("Unknown SCEV min/max opcode"); 3582 }; 3583 3584 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3585 // We found two constants, fold them together! 3586 ConstantInt *Fold = ConstantInt::get( 3587 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3588 Ops[0] = getConstant(Fold); 3589 Ops.erase(Ops.begin()+1); // Erase the folded element 3590 if (Ops.size() == 1) return Ops[0]; 3591 LHSC = cast<SCEVConstant>(Ops[0]); 3592 } 3593 3594 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3595 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3596 3597 if (IsMax ? IsMinV : IsMaxV) { 3598 // If we are left with a constant minimum(/maximum)-int, strip it off. 3599 Ops.erase(Ops.begin()); 3600 --Idx; 3601 } else if (IsMax ? IsMaxV : IsMinV) { 3602 // If we have a max(/min) with a constant maximum(/minimum)-int, 3603 // it will always be the extremum. 3604 return LHSC; 3605 } 3606 3607 if (Ops.size() == 1) return Ops[0]; 3608 } 3609 3610 // Find the first operation of the same kind 3611 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3612 ++Idx; 3613 3614 // Check to see if one of the operands is of the same kind. If so, expand its 3615 // operands onto our operand list, and recurse to simplify. 3616 if (Idx < Ops.size()) { 3617 bool DeletedAny = false; 3618 while (Ops[Idx]->getSCEVType() == Kind) { 3619 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3620 Ops.erase(Ops.begin()+Idx); 3621 Ops.append(SMME->op_begin(), SMME->op_end()); 3622 DeletedAny = true; 3623 } 3624 3625 if (DeletedAny) 3626 return getMinMaxExpr(Kind, Ops); 3627 } 3628 3629 // Okay, check to see if the same value occurs in the operand list twice. If 3630 // so, delete one. Since we sorted the list, these values are required to 3631 // be adjacent. 3632 llvm::CmpInst::Predicate GEPred = 3633 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3634 llvm::CmpInst::Predicate LEPred = 3635 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3636 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3637 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3638 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3639 if (Ops[i] == Ops[i + 1] || 3640 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3641 // X op Y op Y --> X op Y 3642 // X op Y --> X, if we know X, Y are ordered appropriately 3643 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3644 --i; 3645 --e; 3646 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3647 Ops[i + 1])) { 3648 // X op Y --> Y, if we know X, Y are ordered appropriately 3649 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3650 --i; 3651 --e; 3652 } 3653 } 3654 3655 if (Ops.size() == 1) return Ops[0]; 3656 3657 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3658 3659 // Okay, it looks like we really DO need an expr. Check to see if we 3660 // already have one, otherwise create a new one. 3661 const SCEV *ExistingSCEV; 3662 FoldingSetNodeID ID; 3663 void *IP; 3664 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3665 if (ExistingSCEV) 3666 return ExistingSCEV; 3667 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3668 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3669 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3670 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3671 3672 UniqueSCEVs.InsertNode(S, IP); 3673 addToLoopUseLists(S); 3674 return S; 3675 } 3676 3677 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3678 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3679 return getSMaxExpr(Ops); 3680 } 3681 3682 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3683 return getMinMaxExpr(scSMaxExpr, Ops); 3684 } 3685 3686 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3687 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3688 return getUMaxExpr(Ops); 3689 } 3690 3691 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3692 return getMinMaxExpr(scUMaxExpr, Ops); 3693 } 3694 3695 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3696 const SCEV *RHS) { 3697 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3698 return getSMinExpr(Ops); 3699 } 3700 3701 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3702 return getMinMaxExpr(scSMinExpr, Ops); 3703 } 3704 3705 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3706 const SCEV *RHS) { 3707 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3708 return getUMinExpr(Ops); 3709 } 3710 3711 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3712 return getMinMaxExpr(scUMinExpr, Ops); 3713 } 3714 3715 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3716 // We can bypass creating a target-independent 3717 // constant expression and then folding it back into a ConstantInt. 3718 // This is just a compile-time optimization. 3719 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3720 } 3721 3722 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3723 StructType *STy, 3724 unsigned FieldNo) { 3725 // We can bypass creating a target-independent 3726 // constant expression and then folding it back into a ConstantInt. 3727 // This is just a compile-time optimization. 3728 return getConstant( 3729 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3730 } 3731 3732 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3733 // Don't attempt to do anything other than create a SCEVUnknown object 3734 // here. createSCEV only calls getUnknown after checking for all other 3735 // interesting possibilities, and any other code that calls getUnknown 3736 // is doing so in order to hide a value from SCEV canonicalization. 3737 3738 FoldingSetNodeID ID; 3739 ID.AddInteger(scUnknown); 3740 ID.AddPointer(V); 3741 void *IP = nullptr; 3742 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3743 assert(cast<SCEVUnknown>(S)->getValue() == V && 3744 "Stale SCEVUnknown in uniquing map!"); 3745 return S; 3746 } 3747 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3748 FirstUnknown); 3749 FirstUnknown = cast<SCEVUnknown>(S); 3750 UniqueSCEVs.InsertNode(S, IP); 3751 return S; 3752 } 3753 3754 //===----------------------------------------------------------------------===// 3755 // Basic SCEV Analysis and PHI Idiom Recognition Code 3756 // 3757 3758 /// Test if values of the given type are analyzable within the SCEV 3759 /// framework. This primarily includes integer types, and it can optionally 3760 /// include pointer types if the ScalarEvolution class has access to 3761 /// target-specific information. 3762 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3763 // Integers and pointers are always SCEVable. 3764 return Ty->isIntOrPtrTy(); 3765 } 3766 3767 /// Return the size in bits of the specified type, for which isSCEVable must 3768 /// return true. 3769 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3770 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3771 if (Ty->isPointerTy()) 3772 return getDataLayout().getIndexTypeSizeInBits(Ty); 3773 return getDataLayout().getTypeSizeInBits(Ty); 3774 } 3775 3776 /// Return a type with the same bitwidth as the given type and which represents 3777 /// how SCEV will treat the given type, for which isSCEVable must return 3778 /// true. For pointer types, this is the pointer-sized integer type. 3779 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3780 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3781 3782 if (Ty->isIntegerTy()) 3783 return Ty; 3784 3785 // The only other support type is pointer. 3786 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3787 return getDataLayout().getIntPtrType(Ty); 3788 } 3789 3790 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3791 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3792 } 3793 3794 const SCEV *ScalarEvolution::getCouldNotCompute() { 3795 return CouldNotCompute.get(); 3796 } 3797 3798 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3799 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3800 auto *SU = dyn_cast<SCEVUnknown>(S); 3801 return SU && SU->getValue() == nullptr; 3802 }); 3803 3804 return !ContainsNulls; 3805 } 3806 3807 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3808 HasRecMapType::iterator I = HasRecMap.find(S); 3809 if (I != HasRecMap.end()) 3810 return I->second; 3811 3812 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3813 HasRecMap.insert({S, FoundAddRec}); 3814 return FoundAddRec; 3815 } 3816 3817 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3818 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3819 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3820 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3821 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3822 if (!Add) 3823 return {S, nullptr}; 3824 3825 if (Add->getNumOperands() != 2) 3826 return {S, nullptr}; 3827 3828 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3829 if (!ConstOp) 3830 return {S, nullptr}; 3831 3832 return {Add->getOperand(1), ConstOp->getValue()}; 3833 } 3834 3835 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3836 /// by the value and offset from any ValueOffsetPair in the set. 3837 SetVector<ScalarEvolution::ValueOffsetPair> * 3838 ScalarEvolution::getSCEVValues(const SCEV *S) { 3839 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3840 if (SI == ExprValueMap.end()) 3841 return nullptr; 3842 #ifndef NDEBUG 3843 if (VerifySCEVMap) { 3844 // Check there is no dangling Value in the set returned. 3845 for (const auto &VE : SI->second) 3846 assert(ValueExprMap.count(VE.first)); 3847 } 3848 #endif 3849 return &SI->second; 3850 } 3851 3852 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3853 /// cannot be used separately. eraseValueFromMap should be used to remove 3854 /// V from ValueExprMap and ExprValueMap at the same time. 3855 void ScalarEvolution::eraseValueFromMap(Value *V) { 3856 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3857 if (I != ValueExprMap.end()) { 3858 const SCEV *S = I->second; 3859 // Remove {V, 0} from the set of ExprValueMap[S] 3860 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3861 SV->remove({V, nullptr}); 3862 3863 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3864 const SCEV *Stripped; 3865 ConstantInt *Offset; 3866 std::tie(Stripped, Offset) = splitAddExpr(S); 3867 if (Offset != nullptr) { 3868 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3869 SV->remove({V, Offset}); 3870 } 3871 ValueExprMap.erase(V); 3872 } 3873 } 3874 3875 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3876 /// TODO: In reality it is better to check the poison recursively 3877 /// but this is better than nothing. 3878 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3879 if (auto *I = dyn_cast<Instruction>(V)) { 3880 if (isa<OverflowingBinaryOperator>(I)) { 3881 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3882 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3883 return true; 3884 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3885 return true; 3886 } 3887 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3888 return true; 3889 } 3890 return false; 3891 } 3892 3893 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3894 /// create a new one. 3895 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3896 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3897 3898 const SCEV *S = getExistingSCEV(V); 3899 if (S == nullptr) { 3900 S = createSCEV(V); 3901 // During PHI resolution, it is possible to create two SCEVs for the same 3902 // V, so it is needed to double check whether V->S is inserted into 3903 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3904 std::pair<ValueExprMapType::iterator, bool> Pair = 3905 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3906 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3907 ExprValueMap[S].insert({V, nullptr}); 3908 3909 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3910 // ExprValueMap. 3911 const SCEV *Stripped = S; 3912 ConstantInt *Offset = nullptr; 3913 std::tie(Stripped, Offset) = splitAddExpr(S); 3914 // If stripped is SCEVUnknown, don't bother to save 3915 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3916 // increase the complexity of the expansion code. 3917 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3918 // because it may generate add/sub instead of GEP in SCEV expansion. 3919 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3920 !isa<GetElementPtrInst>(V)) 3921 ExprValueMap[Stripped].insert({V, Offset}); 3922 } 3923 } 3924 return S; 3925 } 3926 3927 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3928 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3929 3930 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3931 if (I != ValueExprMap.end()) { 3932 const SCEV *S = I->second; 3933 if (checkValidity(S)) 3934 return S; 3935 eraseValueFromMap(V); 3936 forgetMemoizedResults(S); 3937 } 3938 return nullptr; 3939 } 3940 3941 /// Return a SCEV corresponding to -V = -1*V 3942 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3943 SCEV::NoWrapFlags Flags) { 3944 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3945 return getConstant( 3946 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3947 3948 Type *Ty = V->getType(); 3949 Ty = getEffectiveSCEVType(Ty); 3950 return getMulExpr( 3951 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3952 } 3953 3954 /// If Expr computes ~A, return A else return nullptr 3955 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3956 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3957 if (!Add || Add->getNumOperands() != 2 || 3958 !Add->getOperand(0)->isAllOnesValue()) 3959 return nullptr; 3960 3961 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3962 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3963 !AddRHS->getOperand(0)->isAllOnesValue()) 3964 return nullptr; 3965 3966 return AddRHS->getOperand(1); 3967 } 3968 3969 /// Return a SCEV corresponding to ~V = -1-V 3970 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3971 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3972 return getConstant( 3973 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3974 3975 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3976 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3977 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3978 SmallVector<const SCEV *, 2> MatchedOperands; 3979 for (const SCEV *Operand : MME->operands()) { 3980 const SCEV *Matched = MatchNotExpr(Operand); 3981 if (!Matched) 3982 return (const SCEV *)nullptr; 3983 MatchedOperands.push_back(Matched); 3984 } 3985 return getMinMaxExpr( 3986 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3987 MatchedOperands); 3988 }; 3989 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3990 return Replaced; 3991 } 3992 3993 Type *Ty = V->getType(); 3994 Ty = getEffectiveSCEVType(Ty); 3995 const SCEV *AllOnes = 3996 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3997 return getMinusSCEV(AllOnes, V); 3998 } 3999 4000 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4001 SCEV::NoWrapFlags Flags, 4002 unsigned Depth) { 4003 // Fast path: X - X --> 0. 4004 if (LHS == RHS) 4005 return getZero(LHS->getType()); 4006 4007 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4008 // makes it so that we cannot make much use of NUW. 4009 auto AddFlags = SCEV::FlagAnyWrap; 4010 const bool RHSIsNotMinSigned = 4011 !getSignedRangeMin(RHS).isMinSignedValue(); 4012 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4013 // Let M be the minimum representable signed value. Then (-1)*RHS 4014 // signed-wraps if and only if RHS is M. That can happen even for 4015 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4016 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4017 // (-1)*RHS, we need to prove that RHS != M. 4018 // 4019 // If LHS is non-negative and we know that LHS - RHS does not 4020 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4021 // either by proving that RHS > M or that LHS >= 0. 4022 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4023 AddFlags = SCEV::FlagNSW; 4024 } 4025 } 4026 4027 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4028 // RHS is NSW and LHS >= 0. 4029 // 4030 // The difficulty here is that the NSW flag may have been proven 4031 // relative to a loop that is to be found in a recurrence in LHS and 4032 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4033 // larger scope than intended. 4034 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4035 4036 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4037 } 4038 4039 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4040 unsigned Depth) { 4041 Type *SrcTy = V->getType(); 4042 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4043 "Cannot truncate or zero extend with non-integer arguments!"); 4044 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4045 return V; // No conversion 4046 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4047 return getTruncateExpr(V, Ty, Depth); 4048 return getZeroExtendExpr(V, Ty, Depth); 4049 } 4050 4051 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4052 unsigned Depth) { 4053 Type *SrcTy = V->getType(); 4054 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4055 "Cannot truncate or zero extend with non-integer arguments!"); 4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4057 return V; // No conversion 4058 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4059 return getTruncateExpr(V, Ty, Depth); 4060 return getSignExtendExpr(V, Ty, Depth); 4061 } 4062 4063 const SCEV * 4064 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4065 Type *SrcTy = V->getType(); 4066 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4067 "Cannot noop or zero extend with non-integer arguments!"); 4068 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4069 "getNoopOrZeroExtend cannot truncate!"); 4070 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4071 return V; // No conversion 4072 return getZeroExtendExpr(V, Ty); 4073 } 4074 4075 const SCEV * 4076 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4077 Type *SrcTy = V->getType(); 4078 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4079 "Cannot noop or sign extend with non-integer arguments!"); 4080 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4081 "getNoopOrSignExtend cannot truncate!"); 4082 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4083 return V; // No conversion 4084 return getSignExtendExpr(V, Ty); 4085 } 4086 4087 const SCEV * 4088 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4089 Type *SrcTy = V->getType(); 4090 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4091 "Cannot noop or any extend with non-integer arguments!"); 4092 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4093 "getNoopOrAnyExtend cannot truncate!"); 4094 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4095 return V; // No conversion 4096 return getAnyExtendExpr(V, Ty); 4097 } 4098 4099 const SCEV * 4100 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4101 Type *SrcTy = V->getType(); 4102 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4103 "Cannot truncate or noop with non-integer arguments!"); 4104 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4105 "getTruncateOrNoop cannot extend!"); 4106 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4107 return V; // No conversion 4108 return getTruncateExpr(V, Ty); 4109 } 4110 4111 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4112 const SCEV *RHS) { 4113 const SCEV *PromotedLHS = LHS; 4114 const SCEV *PromotedRHS = RHS; 4115 4116 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4117 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4118 else 4119 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4120 4121 return getUMaxExpr(PromotedLHS, PromotedRHS); 4122 } 4123 4124 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4125 const SCEV *RHS) { 4126 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4127 return getUMinFromMismatchedTypes(Ops); 4128 } 4129 4130 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4131 SmallVectorImpl<const SCEV *> &Ops) { 4132 assert(!Ops.empty() && "At least one operand must be!"); 4133 // Trivial case. 4134 if (Ops.size() == 1) 4135 return Ops[0]; 4136 4137 // Find the max type first. 4138 Type *MaxType = nullptr; 4139 for (auto *S : Ops) 4140 if (MaxType) 4141 MaxType = getWiderType(MaxType, S->getType()); 4142 else 4143 MaxType = S->getType(); 4144 4145 // Extend all ops to max type. 4146 SmallVector<const SCEV *, 2> PromotedOps; 4147 for (auto *S : Ops) 4148 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4149 4150 // Generate umin. 4151 return getUMinExpr(PromotedOps); 4152 } 4153 4154 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4155 // A pointer operand may evaluate to a nonpointer expression, such as null. 4156 if (!V->getType()->isPointerTy()) 4157 return V; 4158 4159 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4160 return getPointerBase(Cast->getOperand()); 4161 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4162 const SCEV *PtrOp = nullptr; 4163 for (const SCEV *NAryOp : NAry->operands()) { 4164 if (NAryOp->getType()->isPointerTy()) { 4165 // Cannot find the base of an expression with multiple pointer operands. 4166 if (PtrOp) 4167 return V; 4168 PtrOp = NAryOp; 4169 } 4170 } 4171 if (!PtrOp) 4172 return V; 4173 return getPointerBase(PtrOp); 4174 } 4175 return V; 4176 } 4177 4178 /// Push users of the given Instruction onto the given Worklist. 4179 static void 4180 PushDefUseChildren(Instruction *I, 4181 SmallVectorImpl<Instruction *> &Worklist) { 4182 // Push the def-use children onto the Worklist stack. 4183 for (User *U : I->users()) 4184 Worklist.push_back(cast<Instruction>(U)); 4185 } 4186 4187 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4188 SmallVector<Instruction *, 16> Worklist; 4189 PushDefUseChildren(PN, Worklist); 4190 4191 SmallPtrSet<Instruction *, 8> Visited; 4192 Visited.insert(PN); 4193 while (!Worklist.empty()) { 4194 Instruction *I = Worklist.pop_back_val(); 4195 if (!Visited.insert(I).second) 4196 continue; 4197 4198 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4199 if (It != ValueExprMap.end()) { 4200 const SCEV *Old = It->second; 4201 4202 // Short-circuit the def-use traversal if the symbolic name 4203 // ceases to appear in expressions. 4204 if (Old != SymName && !hasOperand(Old, SymName)) 4205 continue; 4206 4207 // SCEVUnknown for a PHI either means that it has an unrecognized 4208 // structure, it's a PHI that's in the progress of being computed 4209 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4210 // additional loop trip count information isn't going to change anything. 4211 // In the second case, createNodeForPHI will perform the necessary 4212 // updates on its own when it gets to that point. In the third, we do 4213 // want to forget the SCEVUnknown. 4214 if (!isa<PHINode>(I) || 4215 !isa<SCEVUnknown>(Old) || 4216 (I != PN && Old == SymName)) { 4217 eraseValueFromMap(It->first); 4218 forgetMemoizedResults(Old); 4219 } 4220 } 4221 4222 PushDefUseChildren(I, Worklist); 4223 } 4224 } 4225 4226 namespace { 4227 4228 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4229 /// expression in case its Loop is L. If it is not L then 4230 /// if IgnoreOtherLoops is true then use AddRec itself 4231 /// otherwise rewrite cannot be done. 4232 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4233 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4234 public: 4235 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4236 bool IgnoreOtherLoops = true) { 4237 SCEVInitRewriter Rewriter(L, SE); 4238 const SCEV *Result = Rewriter.visit(S); 4239 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4240 return SE.getCouldNotCompute(); 4241 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4242 ? SE.getCouldNotCompute() 4243 : Result; 4244 } 4245 4246 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4247 if (!SE.isLoopInvariant(Expr, L)) 4248 SeenLoopVariantSCEVUnknown = true; 4249 return Expr; 4250 } 4251 4252 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4253 // Only re-write AddRecExprs for this loop. 4254 if (Expr->getLoop() == L) 4255 return Expr->getStart(); 4256 SeenOtherLoops = true; 4257 return Expr; 4258 } 4259 4260 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4261 4262 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4263 4264 private: 4265 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4266 : SCEVRewriteVisitor(SE), L(L) {} 4267 4268 const Loop *L; 4269 bool SeenLoopVariantSCEVUnknown = false; 4270 bool SeenOtherLoops = false; 4271 }; 4272 4273 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4274 /// increment expression in case its Loop is L. If it is not L then 4275 /// use AddRec itself. 4276 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4277 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4278 public: 4279 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4280 SCEVPostIncRewriter Rewriter(L, SE); 4281 const SCEV *Result = Rewriter.visit(S); 4282 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4283 ? SE.getCouldNotCompute() 4284 : Result; 4285 } 4286 4287 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4288 if (!SE.isLoopInvariant(Expr, L)) 4289 SeenLoopVariantSCEVUnknown = true; 4290 return Expr; 4291 } 4292 4293 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4294 // Only re-write AddRecExprs for this loop. 4295 if (Expr->getLoop() == L) 4296 return Expr->getPostIncExpr(SE); 4297 SeenOtherLoops = true; 4298 return Expr; 4299 } 4300 4301 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4302 4303 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4304 4305 private: 4306 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4307 : SCEVRewriteVisitor(SE), L(L) {} 4308 4309 const Loop *L; 4310 bool SeenLoopVariantSCEVUnknown = false; 4311 bool SeenOtherLoops = false; 4312 }; 4313 4314 /// This class evaluates the compare condition by matching it against the 4315 /// condition of loop latch. If there is a match we assume a true value 4316 /// for the condition while building SCEV nodes. 4317 class SCEVBackedgeConditionFolder 4318 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4319 public: 4320 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4321 ScalarEvolution &SE) { 4322 bool IsPosBECond = false; 4323 Value *BECond = nullptr; 4324 if (BasicBlock *Latch = L->getLoopLatch()) { 4325 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4326 if (BI && BI->isConditional()) { 4327 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4328 "Both outgoing branches should not target same header!"); 4329 BECond = BI->getCondition(); 4330 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4331 } else { 4332 return S; 4333 } 4334 } 4335 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4336 return Rewriter.visit(S); 4337 } 4338 4339 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4340 const SCEV *Result = Expr; 4341 bool InvariantF = SE.isLoopInvariant(Expr, L); 4342 4343 if (!InvariantF) { 4344 Instruction *I = cast<Instruction>(Expr->getValue()); 4345 switch (I->getOpcode()) { 4346 case Instruction::Select: { 4347 SelectInst *SI = cast<SelectInst>(I); 4348 Optional<const SCEV *> Res = 4349 compareWithBackedgeCondition(SI->getCondition()); 4350 if (Res.hasValue()) { 4351 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4352 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4353 } 4354 break; 4355 } 4356 default: { 4357 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4358 if (Res.hasValue()) 4359 Result = Res.getValue(); 4360 break; 4361 } 4362 } 4363 } 4364 return Result; 4365 } 4366 4367 private: 4368 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4369 bool IsPosBECond, ScalarEvolution &SE) 4370 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4371 IsPositiveBECond(IsPosBECond) {} 4372 4373 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4374 4375 const Loop *L; 4376 /// Loop back condition. 4377 Value *BackedgeCond = nullptr; 4378 /// Set to true if loop back is on positive branch condition. 4379 bool IsPositiveBECond; 4380 }; 4381 4382 Optional<const SCEV *> 4383 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4384 4385 // If value matches the backedge condition for loop latch, 4386 // then return a constant evolution node based on loopback 4387 // branch taken. 4388 if (BackedgeCond == IC) 4389 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4390 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4391 return None; 4392 } 4393 4394 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4395 public: 4396 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4397 ScalarEvolution &SE) { 4398 SCEVShiftRewriter Rewriter(L, SE); 4399 const SCEV *Result = Rewriter.visit(S); 4400 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4401 } 4402 4403 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4404 // Only allow AddRecExprs for this loop. 4405 if (!SE.isLoopInvariant(Expr, L)) 4406 Valid = false; 4407 return Expr; 4408 } 4409 4410 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4411 if (Expr->getLoop() == L && Expr->isAffine()) 4412 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4413 Valid = false; 4414 return Expr; 4415 } 4416 4417 bool isValid() { return Valid; } 4418 4419 private: 4420 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4421 : SCEVRewriteVisitor(SE), L(L) {} 4422 4423 const Loop *L; 4424 bool Valid = true; 4425 }; 4426 4427 } // end anonymous namespace 4428 4429 SCEV::NoWrapFlags 4430 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4431 if (!AR->isAffine()) 4432 return SCEV::FlagAnyWrap; 4433 4434 using OBO = OverflowingBinaryOperator; 4435 4436 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4437 4438 if (!AR->hasNoSignedWrap()) { 4439 ConstantRange AddRecRange = getSignedRange(AR); 4440 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4441 4442 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4443 Instruction::Add, IncRange, OBO::NoSignedWrap); 4444 if (NSWRegion.contains(AddRecRange)) 4445 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4446 } 4447 4448 if (!AR->hasNoUnsignedWrap()) { 4449 ConstantRange AddRecRange = getUnsignedRange(AR); 4450 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4451 4452 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4453 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4454 if (NUWRegion.contains(AddRecRange)) 4455 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4456 } 4457 4458 return Result; 4459 } 4460 4461 namespace { 4462 4463 /// Represents an abstract binary operation. This may exist as a 4464 /// normal instruction or constant expression, or may have been 4465 /// derived from an expression tree. 4466 struct BinaryOp { 4467 unsigned Opcode; 4468 Value *LHS; 4469 Value *RHS; 4470 bool IsNSW = false; 4471 bool IsNUW = false; 4472 4473 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4474 /// constant expression. 4475 Operator *Op = nullptr; 4476 4477 explicit BinaryOp(Operator *Op) 4478 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4479 Op(Op) { 4480 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4481 IsNSW = OBO->hasNoSignedWrap(); 4482 IsNUW = OBO->hasNoUnsignedWrap(); 4483 } 4484 } 4485 4486 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4487 bool IsNUW = false) 4488 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4489 }; 4490 4491 } // end anonymous namespace 4492 4493 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4494 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4495 auto *Op = dyn_cast<Operator>(V); 4496 if (!Op) 4497 return None; 4498 4499 // Implementation detail: all the cleverness here should happen without 4500 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4501 // SCEV expressions when possible, and we should not break that. 4502 4503 switch (Op->getOpcode()) { 4504 case Instruction::Add: 4505 case Instruction::Sub: 4506 case Instruction::Mul: 4507 case Instruction::UDiv: 4508 case Instruction::URem: 4509 case Instruction::And: 4510 case Instruction::Or: 4511 case Instruction::AShr: 4512 case Instruction::Shl: 4513 return BinaryOp(Op); 4514 4515 case Instruction::Xor: 4516 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4517 // If the RHS of the xor is a signmask, then this is just an add. 4518 // Instcombine turns add of signmask into xor as a strength reduction step. 4519 if (RHSC->getValue().isSignMask()) 4520 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4521 return BinaryOp(Op); 4522 4523 case Instruction::LShr: 4524 // Turn logical shift right of a constant into a unsigned divide. 4525 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4526 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4527 4528 // If the shift count is not less than the bitwidth, the result of 4529 // the shift is undefined. Don't try to analyze it, because the 4530 // resolution chosen here may differ from the resolution chosen in 4531 // other parts of the compiler. 4532 if (SA->getValue().ult(BitWidth)) { 4533 Constant *X = 4534 ConstantInt::get(SA->getContext(), 4535 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4536 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4537 } 4538 } 4539 return BinaryOp(Op); 4540 4541 case Instruction::ExtractValue: { 4542 auto *EVI = cast<ExtractValueInst>(Op); 4543 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4544 break; 4545 4546 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4547 if (!WO) 4548 break; 4549 4550 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4551 bool Signed = WO->isSigned(); 4552 // TODO: Should add nuw/nsw flags for mul as well. 4553 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4554 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4555 4556 // Now that we know that all uses of the arithmetic-result component of 4557 // CI are guarded by the overflow check, we can go ahead and pretend 4558 // that the arithmetic is non-overflowing. 4559 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4560 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4561 } 4562 4563 default: 4564 break; 4565 } 4566 4567 return None; 4568 } 4569 4570 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4571 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4572 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4573 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4574 /// follows one of the following patterns: 4575 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4576 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4577 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4578 /// we return the type of the truncation operation, and indicate whether the 4579 /// truncated type should be treated as signed/unsigned by setting 4580 /// \p Signed to true/false, respectively. 4581 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4582 bool &Signed, ScalarEvolution &SE) { 4583 // The case where Op == SymbolicPHI (that is, with no type conversions on 4584 // the way) is handled by the regular add recurrence creating logic and 4585 // would have already been triggered in createAddRecForPHI. Reaching it here 4586 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4587 // because one of the other operands of the SCEVAddExpr updating this PHI is 4588 // not invariant). 4589 // 4590 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4591 // this case predicates that allow us to prove that Op == SymbolicPHI will 4592 // be added. 4593 if (Op == SymbolicPHI) 4594 return nullptr; 4595 4596 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4597 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4598 if (SourceBits != NewBits) 4599 return nullptr; 4600 4601 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4602 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4603 if (!SExt && !ZExt) 4604 return nullptr; 4605 const SCEVTruncateExpr *Trunc = 4606 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4607 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4608 if (!Trunc) 4609 return nullptr; 4610 const SCEV *X = Trunc->getOperand(); 4611 if (X != SymbolicPHI) 4612 return nullptr; 4613 Signed = SExt != nullptr; 4614 return Trunc->getType(); 4615 } 4616 4617 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4618 if (!PN->getType()->isIntegerTy()) 4619 return nullptr; 4620 const Loop *L = LI.getLoopFor(PN->getParent()); 4621 if (!L || L->getHeader() != PN->getParent()) 4622 return nullptr; 4623 return L; 4624 } 4625 4626 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4627 // computation that updates the phi follows the following pattern: 4628 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4629 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4630 // If so, try to see if it can be rewritten as an AddRecExpr under some 4631 // Predicates. If successful, return them as a pair. Also cache the results 4632 // of the analysis. 4633 // 4634 // Example usage scenario: 4635 // Say the Rewriter is called for the following SCEV: 4636 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4637 // where: 4638 // %X = phi i64 (%Start, %BEValue) 4639 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4640 // and call this function with %SymbolicPHI = %X. 4641 // 4642 // The analysis will find that the value coming around the backedge has 4643 // the following SCEV: 4644 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4645 // Upon concluding that this matches the desired pattern, the function 4646 // will return the pair {NewAddRec, SmallPredsVec} where: 4647 // NewAddRec = {%Start,+,%Step} 4648 // SmallPredsVec = {P1, P2, P3} as follows: 4649 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4650 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4651 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4652 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4653 // under the predicates {P1,P2,P3}. 4654 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4655 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4656 // 4657 // TODO's: 4658 // 4659 // 1) Extend the Induction descriptor to also support inductions that involve 4660 // casts: When needed (namely, when we are called in the context of the 4661 // vectorizer induction analysis), a Set of cast instructions will be 4662 // populated by this method, and provided back to isInductionPHI. This is 4663 // needed to allow the vectorizer to properly record them to be ignored by 4664 // the cost model and to avoid vectorizing them (otherwise these casts, 4665 // which are redundant under the runtime overflow checks, will be 4666 // vectorized, which can be costly). 4667 // 4668 // 2) Support additional induction/PHISCEV patterns: We also want to support 4669 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4670 // after the induction update operation (the induction increment): 4671 // 4672 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4673 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4674 // 4675 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4676 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4677 // 4678 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4679 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4680 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4681 SmallVector<const SCEVPredicate *, 3> Predicates; 4682 4683 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4684 // return an AddRec expression under some predicate. 4685 4686 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4687 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4688 assert(L && "Expecting an integer loop header phi"); 4689 4690 // The loop may have multiple entrances or multiple exits; we can analyze 4691 // this phi as an addrec if it has a unique entry value and a unique 4692 // backedge value. 4693 Value *BEValueV = nullptr, *StartValueV = nullptr; 4694 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4695 Value *V = PN->getIncomingValue(i); 4696 if (L->contains(PN->getIncomingBlock(i))) { 4697 if (!BEValueV) { 4698 BEValueV = V; 4699 } else if (BEValueV != V) { 4700 BEValueV = nullptr; 4701 break; 4702 } 4703 } else if (!StartValueV) { 4704 StartValueV = V; 4705 } else if (StartValueV != V) { 4706 StartValueV = nullptr; 4707 break; 4708 } 4709 } 4710 if (!BEValueV || !StartValueV) 4711 return None; 4712 4713 const SCEV *BEValue = getSCEV(BEValueV); 4714 4715 // If the value coming around the backedge is an add with the symbolic 4716 // value we just inserted, possibly with casts that we can ignore under 4717 // an appropriate runtime guard, then we found a simple induction variable! 4718 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4719 if (!Add) 4720 return None; 4721 4722 // If there is a single occurrence of the symbolic value, possibly 4723 // casted, replace it with a recurrence. 4724 unsigned FoundIndex = Add->getNumOperands(); 4725 Type *TruncTy = nullptr; 4726 bool Signed; 4727 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4728 if ((TruncTy = 4729 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4730 if (FoundIndex == e) { 4731 FoundIndex = i; 4732 break; 4733 } 4734 4735 if (FoundIndex == Add->getNumOperands()) 4736 return None; 4737 4738 // Create an add with everything but the specified operand. 4739 SmallVector<const SCEV *, 8> Ops; 4740 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4741 if (i != FoundIndex) 4742 Ops.push_back(Add->getOperand(i)); 4743 const SCEV *Accum = getAddExpr(Ops); 4744 4745 // The runtime checks will not be valid if the step amount is 4746 // varying inside the loop. 4747 if (!isLoopInvariant(Accum, L)) 4748 return None; 4749 4750 // *** Part2: Create the predicates 4751 4752 // Analysis was successful: we have a phi-with-cast pattern for which we 4753 // can return an AddRec expression under the following predicates: 4754 // 4755 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4756 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4757 // P2: An Equal predicate that guarantees that 4758 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4759 // P3: An Equal predicate that guarantees that 4760 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4761 // 4762 // As we next prove, the above predicates guarantee that: 4763 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4764 // 4765 // 4766 // More formally, we want to prove that: 4767 // Expr(i+1) = Start + (i+1) * Accum 4768 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4769 // 4770 // Given that: 4771 // 1) Expr(0) = Start 4772 // 2) Expr(1) = Start + Accum 4773 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4774 // 3) Induction hypothesis (step i): 4775 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4776 // 4777 // Proof: 4778 // Expr(i+1) = 4779 // = Start + (i+1)*Accum 4780 // = (Start + i*Accum) + Accum 4781 // = Expr(i) + Accum 4782 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4783 // :: from step i 4784 // 4785 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4786 // 4787 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4788 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4789 // + Accum :: from P3 4790 // 4791 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4792 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4793 // 4794 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4795 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4796 // 4797 // By induction, the same applies to all iterations 1<=i<n: 4798 // 4799 4800 // Create a truncated addrec for which we will add a no overflow check (P1). 4801 const SCEV *StartVal = getSCEV(StartValueV); 4802 const SCEV *PHISCEV = 4803 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4804 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4805 4806 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4807 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4808 // will be constant. 4809 // 4810 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4811 // add P1. 4812 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4813 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4814 Signed ? SCEVWrapPredicate::IncrementNSSW 4815 : SCEVWrapPredicate::IncrementNUSW; 4816 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4817 Predicates.push_back(AddRecPred); 4818 } 4819 4820 // Create the Equal Predicates P2,P3: 4821 4822 // It is possible that the predicates P2 and/or P3 are computable at 4823 // compile time due to StartVal and/or Accum being constants. 4824 // If either one is, then we can check that now and escape if either P2 4825 // or P3 is false. 4826 4827 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4828 // for each of StartVal and Accum 4829 auto getExtendedExpr = [&](const SCEV *Expr, 4830 bool CreateSignExtend) -> const SCEV * { 4831 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4832 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4833 const SCEV *ExtendedExpr = 4834 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4835 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4836 return ExtendedExpr; 4837 }; 4838 4839 // Given: 4840 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4841 // = getExtendedExpr(Expr) 4842 // Determine whether the predicate P: Expr == ExtendedExpr 4843 // is known to be false at compile time 4844 auto PredIsKnownFalse = [&](const SCEV *Expr, 4845 const SCEV *ExtendedExpr) -> bool { 4846 return Expr != ExtendedExpr && 4847 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4848 }; 4849 4850 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4851 if (PredIsKnownFalse(StartVal, StartExtended)) { 4852 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4853 return None; 4854 } 4855 4856 // The Step is always Signed (because the overflow checks are either 4857 // NSSW or NUSW) 4858 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4859 if (PredIsKnownFalse(Accum, AccumExtended)) { 4860 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4861 return None; 4862 } 4863 4864 auto AppendPredicate = [&](const SCEV *Expr, 4865 const SCEV *ExtendedExpr) -> void { 4866 if (Expr != ExtendedExpr && 4867 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4868 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4869 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4870 Predicates.push_back(Pred); 4871 } 4872 }; 4873 4874 AppendPredicate(StartVal, StartExtended); 4875 AppendPredicate(Accum, AccumExtended); 4876 4877 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4878 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4879 // into NewAR if it will also add the runtime overflow checks specified in 4880 // Predicates. 4881 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4882 4883 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4884 std::make_pair(NewAR, Predicates); 4885 // Remember the result of the analysis for this SCEV at this locayyytion. 4886 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4887 return PredRewrite; 4888 } 4889 4890 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4891 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4892 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4893 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4894 if (!L) 4895 return None; 4896 4897 // Check to see if we already analyzed this PHI. 4898 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4899 if (I != PredicatedSCEVRewrites.end()) { 4900 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4901 I->second; 4902 // Analysis was done before and failed to create an AddRec: 4903 if (Rewrite.first == SymbolicPHI) 4904 return None; 4905 // Analysis was done before and succeeded to create an AddRec under 4906 // a predicate: 4907 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4908 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4909 return Rewrite; 4910 } 4911 4912 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4913 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4914 4915 // Record in the cache that the analysis failed 4916 if (!Rewrite) { 4917 SmallVector<const SCEVPredicate *, 3> Predicates; 4918 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4919 return None; 4920 } 4921 4922 return Rewrite; 4923 } 4924 4925 // FIXME: This utility is currently required because the Rewriter currently 4926 // does not rewrite this expression: 4927 // {0, +, (sext ix (trunc iy to ix) to iy)} 4928 // into {0, +, %step}, 4929 // even when the following Equal predicate exists: 4930 // "%step == (sext ix (trunc iy to ix) to iy)". 4931 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4932 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4933 if (AR1 == AR2) 4934 return true; 4935 4936 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4937 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4938 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4939 return false; 4940 return true; 4941 }; 4942 4943 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4944 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4945 return false; 4946 return true; 4947 } 4948 4949 /// A helper function for createAddRecFromPHI to handle simple cases. 4950 /// 4951 /// This function tries to find an AddRec expression for the simplest (yet most 4952 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4953 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4954 /// technique for finding the AddRec expression. 4955 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4956 Value *BEValueV, 4957 Value *StartValueV) { 4958 const Loop *L = LI.getLoopFor(PN->getParent()); 4959 assert(L && L->getHeader() == PN->getParent()); 4960 assert(BEValueV && StartValueV); 4961 4962 auto BO = MatchBinaryOp(BEValueV, DT); 4963 if (!BO) 4964 return nullptr; 4965 4966 if (BO->Opcode != Instruction::Add) 4967 return nullptr; 4968 4969 const SCEV *Accum = nullptr; 4970 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4971 Accum = getSCEV(BO->RHS); 4972 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4973 Accum = getSCEV(BO->LHS); 4974 4975 if (!Accum) 4976 return nullptr; 4977 4978 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4979 if (BO->IsNUW) 4980 Flags = setFlags(Flags, SCEV::FlagNUW); 4981 if (BO->IsNSW) 4982 Flags = setFlags(Flags, SCEV::FlagNSW); 4983 4984 const SCEV *StartVal = getSCEV(StartValueV); 4985 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4986 4987 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4988 4989 // We can add Flags to the post-inc expression only if we 4990 // know that it is *undefined behavior* for BEValueV to 4991 // overflow. 4992 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4993 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4994 (void)getAddRecExpr(getAddExpr(StartVal, Accum, Flags), Accum, L, Flags); 4995 4996 return PHISCEV; 4997 } 4998 4999 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5000 const Loop *L = LI.getLoopFor(PN->getParent()); 5001 if (!L || L->getHeader() != PN->getParent()) 5002 return nullptr; 5003 5004 // The loop may have multiple entrances or multiple exits; we can analyze 5005 // this phi as an addrec if it has a unique entry value and a unique 5006 // backedge value. 5007 Value *BEValueV = nullptr, *StartValueV = nullptr; 5008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5009 Value *V = PN->getIncomingValue(i); 5010 if (L->contains(PN->getIncomingBlock(i))) { 5011 if (!BEValueV) { 5012 BEValueV = V; 5013 } else if (BEValueV != V) { 5014 BEValueV = nullptr; 5015 break; 5016 } 5017 } else if (!StartValueV) { 5018 StartValueV = V; 5019 } else if (StartValueV != V) { 5020 StartValueV = nullptr; 5021 break; 5022 } 5023 } 5024 if (!BEValueV || !StartValueV) 5025 return nullptr; 5026 5027 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5028 "PHI node already processed?"); 5029 5030 // First, try to find AddRec expression without creating a fictituos symbolic 5031 // value for PN. 5032 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5033 return S; 5034 5035 // Handle PHI node value symbolically. 5036 const SCEV *SymbolicName = getUnknown(PN); 5037 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5038 5039 // Using this symbolic name for the PHI, analyze the value coming around 5040 // the back-edge. 5041 const SCEV *BEValue = getSCEV(BEValueV); 5042 5043 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5044 // has a special value for the first iteration of the loop. 5045 5046 // If the value coming around the backedge is an add with the symbolic 5047 // value we just inserted, then we found a simple induction variable! 5048 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5049 // If there is a single occurrence of the symbolic value, replace it 5050 // with a recurrence. 5051 unsigned FoundIndex = Add->getNumOperands(); 5052 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5053 if (Add->getOperand(i) == SymbolicName) 5054 if (FoundIndex == e) { 5055 FoundIndex = i; 5056 break; 5057 } 5058 5059 if (FoundIndex != Add->getNumOperands()) { 5060 // Create an add with everything but the specified operand. 5061 SmallVector<const SCEV *, 8> Ops; 5062 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5063 if (i != FoundIndex) 5064 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5065 L, *this)); 5066 const SCEV *Accum = getAddExpr(Ops); 5067 5068 // This is not a valid addrec if the step amount is varying each 5069 // loop iteration, but is not itself an addrec in this loop. 5070 if (isLoopInvariant(Accum, L) || 5071 (isa<SCEVAddRecExpr>(Accum) && 5072 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5073 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5074 5075 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5076 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5077 if (BO->IsNUW) 5078 Flags = setFlags(Flags, SCEV::FlagNUW); 5079 if (BO->IsNSW) 5080 Flags = setFlags(Flags, SCEV::FlagNSW); 5081 } 5082 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5083 // If the increment is an inbounds GEP, then we know the address 5084 // space cannot be wrapped around. We cannot make any guarantee 5085 // about signed or unsigned overflow because pointers are 5086 // unsigned but we may have a negative index from the base 5087 // pointer. We can guarantee that no unsigned wrap occurs if the 5088 // indices form a positive value. 5089 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5090 Flags = setFlags(Flags, SCEV::FlagNW); 5091 5092 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5093 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5094 Flags = setFlags(Flags, SCEV::FlagNUW); 5095 } 5096 5097 // We cannot transfer nuw and nsw flags from subtraction 5098 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5099 // for instance. 5100 } 5101 5102 const SCEV *StartVal = getSCEV(StartValueV); 5103 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5104 5105 // Okay, for the entire analysis of this edge we assumed the PHI 5106 // to be symbolic. We now need to go back and purge all of the 5107 // entries for the scalars that use the symbolic expression. 5108 forgetSymbolicName(PN, SymbolicName); 5109 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5110 5111 // We can add Flags to the post-inc expression only if we 5112 // know that it is *undefined behavior* for BEValueV to 5113 // overflow. 5114 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5115 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5116 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5117 5118 return PHISCEV; 5119 } 5120 } 5121 } else { 5122 // Otherwise, this could be a loop like this: 5123 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5124 // In this case, j = {1,+,1} and BEValue is j. 5125 // Because the other in-value of i (0) fits the evolution of BEValue 5126 // i really is an addrec evolution. 5127 // 5128 // We can generalize this saying that i is the shifted value of BEValue 5129 // by one iteration: 5130 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5131 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5132 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5133 if (Shifted != getCouldNotCompute() && 5134 Start != getCouldNotCompute()) { 5135 const SCEV *StartVal = getSCEV(StartValueV); 5136 if (Start == StartVal) { 5137 // Okay, for the entire analysis of this edge we assumed the PHI 5138 // to be symbolic. We now need to go back and purge all of the 5139 // entries for the scalars that use the symbolic expression. 5140 forgetSymbolicName(PN, SymbolicName); 5141 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5142 return Shifted; 5143 } 5144 } 5145 } 5146 5147 // Remove the temporary PHI node SCEV that has been inserted while intending 5148 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5149 // as it will prevent later (possibly simpler) SCEV expressions to be added 5150 // to the ValueExprMap. 5151 eraseValueFromMap(PN); 5152 5153 return nullptr; 5154 } 5155 5156 // Checks if the SCEV S is available at BB. S is considered available at BB 5157 // if S can be materialized at BB without introducing a fault. 5158 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5159 BasicBlock *BB) { 5160 struct CheckAvailable { 5161 bool TraversalDone = false; 5162 bool Available = true; 5163 5164 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5165 BasicBlock *BB = nullptr; 5166 DominatorTree &DT; 5167 5168 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5169 : L(L), BB(BB), DT(DT) {} 5170 5171 bool setUnavailable() { 5172 TraversalDone = true; 5173 Available = false; 5174 return false; 5175 } 5176 5177 bool follow(const SCEV *S) { 5178 switch (S->getSCEVType()) { 5179 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5180 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5181 case scUMinExpr: 5182 case scSMinExpr: 5183 // These expressions are available if their operand(s) is/are. 5184 return true; 5185 5186 case scAddRecExpr: { 5187 // We allow add recurrences that are on the loop BB is in, or some 5188 // outer loop. This guarantees availability because the value of the 5189 // add recurrence at BB is simply the "current" value of the induction 5190 // variable. We can relax this in the future; for instance an add 5191 // recurrence on a sibling dominating loop is also available at BB. 5192 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5193 if (L && (ARLoop == L || ARLoop->contains(L))) 5194 return true; 5195 5196 return setUnavailable(); 5197 } 5198 5199 case scUnknown: { 5200 // For SCEVUnknown, we check for simple dominance. 5201 const auto *SU = cast<SCEVUnknown>(S); 5202 Value *V = SU->getValue(); 5203 5204 if (isa<Argument>(V)) 5205 return false; 5206 5207 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5208 return false; 5209 5210 return setUnavailable(); 5211 } 5212 5213 case scUDivExpr: 5214 case scCouldNotCompute: 5215 // We do not try to smart about these at all. 5216 return setUnavailable(); 5217 } 5218 llvm_unreachable("switch should be fully covered!"); 5219 } 5220 5221 bool isDone() { return TraversalDone; } 5222 }; 5223 5224 CheckAvailable CA(L, BB, DT); 5225 SCEVTraversal<CheckAvailable> ST(CA); 5226 5227 ST.visitAll(S); 5228 return CA.Available; 5229 } 5230 5231 // Try to match a control flow sequence that branches out at BI and merges back 5232 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5233 // match. 5234 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5235 Value *&C, Value *&LHS, Value *&RHS) { 5236 C = BI->getCondition(); 5237 5238 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5239 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5240 5241 if (!LeftEdge.isSingleEdge()) 5242 return false; 5243 5244 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5245 5246 Use &LeftUse = Merge->getOperandUse(0); 5247 Use &RightUse = Merge->getOperandUse(1); 5248 5249 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5250 LHS = LeftUse; 5251 RHS = RightUse; 5252 return true; 5253 } 5254 5255 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5256 LHS = RightUse; 5257 RHS = LeftUse; 5258 return true; 5259 } 5260 5261 return false; 5262 } 5263 5264 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5265 auto IsReachable = 5266 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5267 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5268 const Loop *L = LI.getLoopFor(PN->getParent()); 5269 5270 // We don't want to break LCSSA, even in a SCEV expression tree. 5271 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5272 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5273 return nullptr; 5274 5275 // Try to match 5276 // 5277 // br %cond, label %left, label %right 5278 // left: 5279 // br label %merge 5280 // right: 5281 // br label %merge 5282 // merge: 5283 // V = phi [ %x, %left ], [ %y, %right ] 5284 // 5285 // as "select %cond, %x, %y" 5286 5287 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5288 assert(IDom && "At least the entry block should dominate PN"); 5289 5290 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5291 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5292 5293 if (BI && BI->isConditional() && 5294 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5295 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5296 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5297 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5298 } 5299 5300 return nullptr; 5301 } 5302 5303 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5304 if (const SCEV *S = createAddRecFromPHI(PN)) 5305 return S; 5306 5307 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5308 return S; 5309 5310 // If the PHI has a single incoming value, follow that value, unless the 5311 // PHI's incoming blocks are in a different loop, in which case doing so 5312 // risks breaking LCSSA form. Instcombine would normally zap these, but 5313 // it doesn't have DominatorTree information, so it may miss cases. 5314 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5315 if (LI.replacementPreservesLCSSAForm(PN, V)) 5316 return getSCEV(V); 5317 5318 // If it's not a loop phi, we can't handle it yet. 5319 return getUnknown(PN); 5320 } 5321 5322 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5323 Value *Cond, 5324 Value *TrueVal, 5325 Value *FalseVal) { 5326 // Handle "constant" branch or select. This can occur for instance when a 5327 // loop pass transforms an inner loop and moves on to process the outer loop. 5328 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5329 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5330 5331 // Try to match some simple smax or umax patterns. 5332 auto *ICI = dyn_cast<ICmpInst>(Cond); 5333 if (!ICI) 5334 return getUnknown(I); 5335 5336 Value *LHS = ICI->getOperand(0); 5337 Value *RHS = ICI->getOperand(1); 5338 5339 switch (ICI->getPredicate()) { 5340 case ICmpInst::ICMP_SLT: 5341 case ICmpInst::ICMP_SLE: 5342 std::swap(LHS, RHS); 5343 LLVM_FALLTHROUGH; 5344 case ICmpInst::ICMP_SGT: 5345 case ICmpInst::ICMP_SGE: 5346 // a >s b ? a+x : b+x -> smax(a, b)+x 5347 // a >s b ? b+x : a+x -> smin(a, b)+x 5348 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5349 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5350 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5351 const SCEV *LA = getSCEV(TrueVal); 5352 const SCEV *RA = getSCEV(FalseVal); 5353 const SCEV *LDiff = getMinusSCEV(LA, LS); 5354 const SCEV *RDiff = getMinusSCEV(RA, RS); 5355 if (LDiff == RDiff) 5356 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5357 LDiff = getMinusSCEV(LA, RS); 5358 RDiff = getMinusSCEV(RA, LS); 5359 if (LDiff == RDiff) 5360 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5361 } 5362 break; 5363 case ICmpInst::ICMP_ULT: 5364 case ICmpInst::ICMP_ULE: 5365 std::swap(LHS, RHS); 5366 LLVM_FALLTHROUGH; 5367 case ICmpInst::ICMP_UGT: 5368 case ICmpInst::ICMP_UGE: 5369 // a >u b ? a+x : b+x -> umax(a, b)+x 5370 // a >u b ? b+x : a+x -> umin(a, b)+x 5371 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5372 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5373 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5374 const SCEV *LA = getSCEV(TrueVal); 5375 const SCEV *RA = getSCEV(FalseVal); 5376 const SCEV *LDiff = getMinusSCEV(LA, LS); 5377 const SCEV *RDiff = getMinusSCEV(RA, RS); 5378 if (LDiff == RDiff) 5379 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5380 LDiff = getMinusSCEV(LA, RS); 5381 RDiff = getMinusSCEV(RA, LS); 5382 if (LDiff == RDiff) 5383 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5384 } 5385 break; 5386 case ICmpInst::ICMP_NE: 5387 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5388 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5389 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5390 const SCEV *One = getOne(I->getType()); 5391 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5392 const SCEV *LA = getSCEV(TrueVal); 5393 const SCEV *RA = getSCEV(FalseVal); 5394 const SCEV *LDiff = getMinusSCEV(LA, LS); 5395 const SCEV *RDiff = getMinusSCEV(RA, One); 5396 if (LDiff == RDiff) 5397 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5398 } 5399 break; 5400 case ICmpInst::ICMP_EQ: 5401 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5402 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5403 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5404 const SCEV *One = getOne(I->getType()); 5405 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5406 const SCEV *LA = getSCEV(TrueVal); 5407 const SCEV *RA = getSCEV(FalseVal); 5408 const SCEV *LDiff = getMinusSCEV(LA, One); 5409 const SCEV *RDiff = getMinusSCEV(RA, LS); 5410 if (LDiff == RDiff) 5411 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5412 } 5413 break; 5414 default: 5415 break; 5416 } 5417 5418 return getUnknown(I); 5419 } 5420 5421 /// Expand GEP instructions into add and multiply operations. This allows them 5422 /// to be analyzed by regular SCEV code. 5423 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5424 // Don't attempt to analyze GEPs over unsized objects. 5425 if (!GEP->getSourceElementType()->isSized()) 5426 return getUnknown(GEP); 5427 5428 SmallVector<const SCEV *, 4> IndexExprs; 5429 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5430 IndexExprs.push_back(getSCEV(*Index)); 5431 return getGEPExpr(GEP, IndexExprs); 5432 } 5433 5434 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5435 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5436 return C->getAPInt().countTrailingZeros(); 5437 5438 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5439 return std::min(GetMinTrailingZeros(T->getOperand()), 5440 (uint32_t)getTypeSizeInBits(T->getType())); 5441 5442 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5443 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5444 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5445 ? getTypeSizeInBits(E->getType()) 5446 : OpRes; 5447 } 5448 5449 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5450 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5451 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5452 ? getTypeSizeInBits(E->getType()) 5453 : OpRes; 5454 } 5455 5456 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5457 // The result is the min of all operands results. 5458 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5459 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5460 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5461 return MinOpRes; 5462 } 5463 5464 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5465 // The result is the sum of all operands results. 5466 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5467 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5468 for (unsigned i = 1, e = M->getNumOperands(); 5469 SumOpRes != BitWidth && i != e; ++i) 5470 SumOpRes = 5471 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5472 return SumOpRes; 5473 } 5474 5475 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5476 // The result is the min of all operands results. 5477 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5478 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5479 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5480 return MinOpRes; 5481 } 5482 5483 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5484 // The result is the min of all operands results. 5485 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5486 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5487 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5488 return MinOpRes; 5489 } 5490 5491 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5492 // The result is the min of all operands results. 5493 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5494 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5495 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5496 return MinOpRes; 5497 } 5498 5499 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5500 // For a SCEVUnknown, ask ValueTracking. 5501 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5502 return Known.countMinTrailingZeros(); 5503 } 5504 5505 // SCEVUDivExpr 5506 return 0; 5507 } 5508 5509 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5510 auto I = MinTrailingZerosCache.find(S); 5511 if (I != MinTrailingZerosCache.end()) 5512 return I->second; 5513 5514 uint32_t Result = GetMinTrailingZerosImpl(S); 5515 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5516 assert(InsertPair.second && "Should insert a new key"); 5517 return InsertPair.first->second; 5518 } 5519 5520 /// Helper method to assign a range to V from metadata present in the IR. 5521 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5522 if (Instruction *I = dyn_cast<Instruction>(V)) 5523 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5524 return getConstantRangeFromMetadata(*MD); 5525 5526 return None; 5527 } 5528 5529 /// Determine the range for a particular SCEV. If SignHint is 5530 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5531 /// with a "cleaner" unsigned (resp. signed) representation. 5532 const ConstantRange & 5533 ScalarEvolution::getRangeRef(const SCEV *S, 5534 ScalarEvolution::RangeSignHint SignHint) { 5535 DenseMap<const SCEV *, ConstantRange> &Cache = 5536 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5537 : SignedRanges; 5538 ConstantRange::PreferredRangeType RangeType = 5539 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5540 ? ConstantRange::Unsigned : ConstantRange::Signed; 5541 5542 // See if we've computed this range already. 5543 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5544 if (I != Cache.end()) 5545 return I->second; 5546 5547 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5548 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5549 5550 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5551 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5552 5553 // If the value has known zeros, the maximum value will have those known zeros 5554 // as well. 5555 uint32_t TZ = GetMinTrailingZeros(S); 5556 if (TZ != 0) { 5557 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5558 ConservativeResult = 5559 ConstantRange(APInt::getMinValue(BitWidth), 5560 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5561 else 5562 ConservativeResult = ConstantRange( 5563 APInt::getSignedMinValue(BitWidth), 5564 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5565 } 5566 5567 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5568 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5569 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5570 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5571 return setRange(Add, SignHint, 5572 ConservativeResult.intersectWith(X, RangeType)); 5573 } 5574 5575 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5576 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5577 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5578 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5579 return setRange(Mul, SignHint, 5580 ConservativeResult.intersectWith(X, RangeType)); 5581 } 5582 5583 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5584 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5585 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5586 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5587 return setRange(SMax, SignHint, 5588 ConservativeResult.intersectWith(X, RangeType)); 5589 } 5590 5591 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5592 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5593 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5594 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5595 return setRange(UMax, SignHint, 5596 ConservativeResult.intersectWith(X, RangeType)); 5597 } 5598 5599 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5600 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5601 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5602 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5603 return setRange(SMin, SignHint, 5604 ConservativeResult.intersectWith(X, RangeType)); 5605 } 5606 5607 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5608 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5609 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5610 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5611 return setRange(UMin, SignHint, 5612 ConservativeResult.intersectWith(X, RangeType)); 5613 } 5614 5615 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5616 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5617 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5618 return setRange(UDiv, SignHint, 5619 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5620 } 5621 5622 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5623 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5624 return setRange(ZExt, SignHint, 5625 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5626 RangeType)); 5627 } 5628 5629 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5630 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5631 return setRange(SExt, SignHint, 5632 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5633 RangeType)); 5634 } 5635 5636 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5637 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5638 return setRange(Trunc, SignHint, 5639 ConservativeResult.intersectWith(X.truncate(BitWidth), 5640 RangeType)); 5641 } 5642 5643 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5644 // If there's no unsigned wrap, the value will never be less than its 5645 // initial value. 5646 if (AddRec->hasNoUnsignedWrap()) 5647 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5648 if (!C->getValue()->isZero()) 5649 ConservativeResult = ConservativeResult.intersectWith( 5650 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5651 5652 // If there's no signed wrap, and all the operands have the same sign or 5653 // zero, the value won't ever change sign. 5654 if (AddRec->hasNoSignedWrap()) { 5655 bool AllNonNeg = true; 5656 bool AllNonPos = true; 5657 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5658 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5659 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5660 } 5661 if (AllNonNeg) 5662 ConservativeResult = ConservativeResult.intersectWith( 5663 ConstantRange(APInt(BitWidth, 0), 5664 APInt::getSignedMinValue(BitWidth)), RangeType); 5665 else if (AllNonPos) 5666 ConservativeResult = ConservativeResult.intersectWith( 5667 ConstantRange(APInt::getSignedMinValue(BitWidth), 5668 APInt(BitWidth, 1)), RangeType); 5669 } 5670 5671 // TODO: non-affine addrec 5672 if (AddRec->isAffine()) { 5673 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5674 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5675 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5676 auto RangeFromAffine = getRangeForAffineAR( 5677 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5678 BitWidth); 5679 if (!RangeFromAffine.isFullSet()) 5680 ConservativeResult = 5681 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5682 5683 auto RangeFromFactoring = getRangeViaFactoring( 5684 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5685 BitWidth); 5686 if (!RangeFromFactoring.isFullSet()) 5687 ConservativeResult = 5688 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5689 } 5690 } 5691 5692 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5693 } 5694 5695 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5696 // Check if the IR explicitly contains !range metadata. 5697 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5698 if (MDRange.hasValue()) 5699 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5700 RangeType); 5701 5702 // Split here to avoid paying the compile-time cost of calling both 5703 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5704 // if needed. 5705 const DataLayout &DL = getDataLayout(); 5706 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5707 // For a SCEVUnknown, ask ValueTracking. 5708 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5709 if (Known.One != ~Known.Zero + 1) 5710 ConservativeResult = 5711 ConservativeResult.intersectWith( 5712 ConstantRange(Known.One, ~Known.Zero + 1), RangeType); 5713 } else { 5714 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5715 "generalize as needed!"); 5716 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5717 if (NS > 1) 5718 ConservativeResult = ConservativeResult.intersectWith( 5719 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5720 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5721 RangeType); 5722 } 5723 5724 // A range of Phi is a subset of union of all ranges of its input. 5725 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5726 // Make sure that we do not run over cycled Phis. 5727 if (PendingPhiRanges.insert(Phi).second) { 5728 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5729 for (auto &Op : Phi->operands()) { 5730 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5731 RangeFromOps = RangeFromOps.unionWith(OpRange); 5732 // No point to continue if we already have a full set. 5733 if (RangeFromOps.isFullSet()) 5734 break; 5735 } 5736 ConservativeResult = 5737 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5738 bool Erased = PendingPhiRanges.erase(Phi); 5739 assert(Erased && "Failed to erase Phi properly?"); 5740 (void) Erased; 5741 } 5742 } 5743 5744 return setRange(U, SignHint, std::move(ConservativeResult)); 5745 } 5746 5747 return setRange(S, SignHint, std::move(ConservativeResult)); 5748 } 5749 5750 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5751 // values that the expression can take. Initially, the expression has a value 5752 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5753 // argument defines if we treat Step as signed or unsigned. 5754 static ConstantRange getRangeForAffineARHelper(APInt Step, 5755 const ConstantRange &StartRange, 5756 const APInt &MaxBECount, 5757 unsigned BitWidth, bool Signed) { 5758 // If either Step or MaxBECount is 0, then the expression won't change, and we 5759 // just need to return the initial range. 5760 if (Step == 0 || MaxBECount == 0) 5761 return StartRange; 5762 5763 // If we don't know anything about the initial value (i.e. StartRange is 5764 // FullRange), then we don't know anything about the final range either. 5765 // Return FullRange. 5766 if (StartRange.isFullSet()) 5767 return ConstantRange::getFull(BitWidth); 5768 5769 // If Step is signed and negative, then we use its absolute value, but we also 5770 // note that we're moving in the opposite direction. 5771 bool Descending = Signed && Step.isNegative(); 5772 5773 if (Signed) 5774 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5775 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5776 // This equations hold true due to the well-defined wrap-around behavior of 5777 // APInt. 5778 Step = Step.abs(); 5779 5780 // Check if Offset is more than full span of BitWidth. If it is, the 5781 // expression is guaranteed to overflow. 5782 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5783 return ConstantRange::getFull(BitWidth); 5784 5785 // Offset is by how much the expression can change. Checks above guarantee no 5786 // overflow here. 5787 APInt Offset = Step * MaxBECount; 5788 5789 // Minimum value of the final range will match the minimal value of StartRange 5790 // if the expression is increasing and will be decreased by Offset otherwise. 5791 // Maximum value of the final range will match the maximal value of StartRange 5792 // if the expression is decreasing and will be increased by Offset otherwise. 5793 APInt StartLower = StartRange.getLower(); 5794 APInt StartUpper = StartRange.getUpper() - 1; 5795 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5796 : (StartUpper + std::move(Offset)); 5797 5798 // It's possible that the new minimum/maximum value will fall into the initial 5799 // range (due to wrap around). This means that the expression can take any 5800 // value in this bitwidth, and we have to return full range. 5801 if (StartRange.contains(MovedBoundary)) 5802 return ConstantRange::getFull(BitWidth); 5803 5804 APInt NewLower = 5805 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5806 APInt NewUpper = 5807 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5808 NewUpper += 1; 5809 5810 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5811 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5812 } 5813 5814 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5815 const SCEV *Step, 5816 const SCEV *MaxBECount, 5817 unsigned BitWidth) { 5818 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5819 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5820 "Precondition!"); 5821 5822 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5823 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5824 5825 // First, consider step signed. 5826 ConstantRange StartSRange = getSignedRange(Start); 5827 ConstantRange StepSRange = getSignedRange(Step); 5828 5829 // If Step can be both positive and negative, we need to find ranges for the 5830 // maximum absolute step values in both directions and union them. 5831 ConstantRange SR = 5832 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5833 MaxBECountValue, BitWidth, /* Signed = */ true); 5834 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5835 StartSRange, MaxBECountValue, 5836 BitWidth, /* Signed = */ true)); 5837 5838 // Next, consider step unsigned. 5839 ConstantRange UR = getRangeForAffineARHelper( 5840 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5841 MaxBECountValue, BitWidth, /* Signed = */ false); 5842 5843 // Finally, intersect signed and unsigned ranges. 5844 return SR.intersectWith(UR, ConstantRange::Smallest); 5845 } 5846 5847 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5848 const SCEV *Step, 5849 const SCEV *MaxBECount, 5850 unsigned BitWidth) { 5851 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5852 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5853 5854 struct SelectPattern { 5855 Value *Condition = nullptr; 5856 APInt TrueValue; 5857 APInt FalseValue; 5858 5859 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5860 const SCEV *S) { 5861 Optional<unsigned> CastOp; 5862 APInt Offset(BitWidth, 0); 5863 5864 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5865 "Should be!"); 5866 5867 // Peel off a constant offset: 5868 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5869 // In the future we could consider being smarter here and handle 5870 // {Start+Step,+,Step} too. 5871 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5872 return; 5873 5874 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5875 S = SA->getOperand(1); 5876 } 5877 5878 // Peel off a cast operation 5879 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5880 CastOp = SCast->getSCEVType(); 5881 S = SCast->getOperand(); 5882 } 5883 5884 using namespace llvm::PatternMatch; 5885 5886 auto *SU = dyn_cast<SCEVUnknown>(S); 5887 const APInt *TrueVal, *FalseVal; 5888 if (!SU || 5889 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5890 m_APInt(FalseVal)))) { 5891 Condition = nullptr; 5892 return; 5893 } 5894 5895 TrueValue = *TrueVal; 5896 FalseValue = *FalseVal; 5897 5898 // Re-apply the cast we peeled off earlier 5899 if (CastOp.hasValue()) 5900 switch (*CastOp) { 5901 default: 5902 llvm_unreachable("Unknown SCEV cast type!"); 5903 5904 case scTruncate: 5905 TrueValue = TrueValue.trunc(BitWidth); 5906 FalseValue = FalseValue.trunc(BitWidth); 5907 break; 5908 case scZeroExtend: 5909 TrueValue = TrueValue.zext(BitWidth); 5910 FalseValue = FalseValue.zext(BitWidth); 5911 break; 5912 case scSignExtend: 5913 TrueValue = TrueValue.sext(BitWidth); 5914 FalseValue = FalseValue.sext(BitWidth); 5915 break; 5916 } 5917 5918 // Re-apply the constant offset we peeled off earlier 5919 TrueValue += Offset; 5920 FalseValue += Offset; 5921 } 5922 5923 bool isRecognized() { return Condition != nullptr; } 5924 }; 5925 5926 SelectPattern StartPattern(*this, BitWidth, Start); 5927 if (!StartPattern.isRecognized()) 5928 return ConstantRange::getFull(BitWidth); 5929 5930 SelectPattern StepPattern(*this, BitWidth, Step); 5931 if (!StepPattern.isRecognized()) 5932 return ConstantRange::getFull(BitWidth); 5933 5934 if (StartPattern.Condition != StepPattern.Condition) { 5935 // We don't handle this case today; but we could, by considering four 5936 // possibilities below instead of two. I'm not sure if there are cases where 5937 // that will help over what getRange already does, though. 5938 return ConstantRange::getFull(BitWidth); 5939 } 5940 5941 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5942 // construct arbitrary general SCEV expressions here. This function is called 5943 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5944 // say) can end up caching a suboptimal value. 5945 5946 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5947 // C2352 and C2512 (otherwise it isn't needed). 5948 5949 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5950 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5951 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5952 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5953 5954 ConstantRange TrueRange = 5955 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5956 ConstantRange FalseRange = 5957 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5958 5959 return TrueRange.unionWith(FalseRange); 5960 } 5961 5962 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5963 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5964 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5965 5966 // Return early if there are no flags to propagate to the SCEV. 5967 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5968 if (BinOp->hasNoUnsignedWrap()) 5969 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5970 if (BinOp->hasNoSignedWrap()) 5971 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5972 if (Flags == SCEV::FlagAnyWrap) 5973 return SCEV::FlagAnyWrap; 5974 5975 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5976 } 5977 5978 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5979 // Here we check that I is in the header of the innermost loop containing I, 5980 // since we only deal with instructions in the loop header. The actual loop we 5981 // need to check later will come from an add recurrence, but getting that 5982 // requires computing the SCEV of the operands, which can be expensive. This 5983 // check we can do cheaply to rule out some cases early. 5984 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5985 if (InnermostContainingLoop == nullptr || 5986 InnermostContainingLoop->getHeader() != I->getParent()) 5987 return false; 5988 5989 // Only proceed if we can prove that I does not yield poison. 5990 if (!programUndefinedIfFullPoison(I)) 5991 return false; 5992 5993 // At this point we know that if I is executed, then it does not wrap 5994 // according to at least one of NSW or NUW. If I is not executed, then we do 5995 // not know if the calculation that I represents would wrap. Multiple 5996 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5997 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5998 // derived from other instructions that map to the same SCEV. We cannot make 5999 // that guarantee for cases where I is not executed. So we need to find the 6000 // loop that I is considered in relation to and prove that I is executed for 6001 // every iteration of that loop. That implies that the value that I 6002 // calculates does not wrap anywhere in the loop, so then we can apply the 6003 // flags to the SCEV. 6004 // 6005 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6006 // from different loops, so that we know which loop to prove that I is 6007 // executed in. 6008 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6009 // I could be an extractvalue from a call to an overflow intrinsic. 6010 // TODO: We can do better here in some cases. 6011 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6012 return false; 6013 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6014 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6015 bool AllOtherOpsLoopInvariant = true; 6016 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6017 ++OtherOpIndex) { 6018 if (OtherOpIndex != OpIndex) { 6019 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6020 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6021 AllOtherOpsLoopInvariant = false; 6022 break; 6023 } 6024 } 6025 } 6026 if (AllOtherOpsLoopInvariant && 6027 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6028 return true; 6029 } 6030 } 6031 return false; 6032 } 6033 6034 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6035 // If we know that \c I can never be poison period, then that's enough. 6036 if (isSCEVExprNeverPoison(I)) 6037 return true; 6038 6039 // For an add recurrence specifically, we assume that infinite loops without 6040 // side effects are undefined behavior, and then reason as follows: 6041 // 6042 // If the add recurrence is poison in any iteration, it is poison on all 6043 // future iterations (since incrementing poison yields poison). If the result 6044 // of the add recurrence is fed into the loop latch condition and the loop 6045 // does not contain any throws or exiting blocks other than the latch, we now 6046 // have the ability to "choose" whether the backedge is taken or not (by 6047 // choosing a sufficiently evil value for the poison feeding into the branch) 6048 // for every iteration including and after the one in which \p I first became 6049 // poison. There are two possibilities (let's call the iteration in which \p 6050 // I first became poison as K): 6051 // 6052 // 1. In the set of iterations including and after K, the loop body executes 6053 // no side effects. In this case executing the backege an infinte number 6054 // of times will yield undefined behavior. 6055 // 6056 // 2. In the set of iterations including and after K, the loop body executes 6057 // at least one side effect. In this case, that specific instance of side 6058 // effect is control dependent on poison, which also yields undefined 6059 // behavior. 6060 6061 auto *ExitingBB = L->getExitingBlock(); 6062 auto *LatchBB = L->getLoopLatch(); 6063 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6064 return false; 6065 6066 SmallPtrSet<const Instruction *, 16> Pushed; 6067 SmallVector<const Instruction *, 8> PoisonStack; 6068 6069 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6070 // things that are known to be fully poison under that assumption go on the 6071 // PoisonStack. 6072 Pushed.insert(I); 6073 PoisonStack.push_back(I); 6074 6075 bool LatchControlDependentOnPoison = false; 6076 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6077 const Instruction *Poison = PoisonStack.pop_back_val(); 6078 6079 for (auto *PoisonUser : Poison->users()) { 6080 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6081 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6082 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6083 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6084 assert(BI->isConditional() && "Only possibility!"); 6085 if (BI->getParent() == LatchBB) { 6086 LatchControlDependentOnPoison = true; 6087 break; 6088 } 6089 } 6090 } 6091 } 6092 6093 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6094 } 6095 6096 ScalarEvolution::LoopProperties 6097 ScalarEvolution::getLoopProperties(const Loop *L) { 6098 using LoopProperties = ScalarEvolution::LoopProperties; 6099 6100 auto Itr = LoopPropertiesCache.find(L); 6101 if (Itr == LoopPropertiesCache.end()) { 6102 auto HasSideEffects = [](Instruction *I) { 6103 if (auto *SI = dyn_cast<StoreInst>(I)) 6104 return !SI->isSimple(); 6105 6106 return I->mayHaveSideEffects(); 6107 }; 6108 6109 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6110 /*HasNoSideEffects*/ true}; 6111 6112 for (auto *BB : L->getBlocks()) 6113 for (auto &I : *BB) { 6114 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6115 LP.HasNoAbnormalExits = false; 6116 if (HasSideEffects(&I)) 6117 LP.HasNoSideEffects = false; 6118 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6119 break; // We're already as pessimistic as we can get. 6120 } 6121 6122 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6123 assert(InsertPair.second && "We just checked!"); 6124 Itr = InsertPair.first; 6125 } 6126 6127 return Itr->second; 6128 } 6129 6130 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6131 if (!isSCEVable(V->getType())) 6132 return getUnknown(V); 6133 6134 if (Instruction *I = dyn_cast<Instruction>(V)) { 6135 // Don't attempt to analyze instructions in blocks that aren't 6136 // reachable. Such instructions don't matter, and they aren't required 6137 // to obey basic rules for definitions dominating uses which this 6138 // analysis depends on. 6139 if (!DT.isReachableFromEntry(I->getParent())) 6140 return getUnknown(UndefValue::get(V->getType())); 6141 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6142 return getConstant(CI); 6143 else if (isa<ConstantPointerNull>(V)) 6144 return getZero(V->getType()); 6145 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6146 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6147 else if (!isa<ConstantExpr>(V)) 6148 return getUnknown(V); 6149 6150 Operator *U = cast<Operator>(V); 6151 if (auto BO = MatchBinaryOp(U, DT)) { 6152 switch (BO->Opcode) { 6153 case Instruction::Add: { 6154 // The simple thing to do would be to just call getSCEV on both operands 6155 // and call getAddExpr with the result. However if we're looking at a 6156 // bunch of things all added together, this can be quite inefficient, 6157 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6158 // Instead, gather up all the operands and make a single getAddExpr call. 6159 // LLVM IR canonical form means we need only traverse the left operands. 6160 SmallVector<const SCEV *, 4> AddOps; 6161 do { 6162 if (BO->Op) { 6163 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6164 AddOps.push_back(OpSCEV); 6165 break; 6166 } 6167 6168 // If a NUW or NSW flag can be applied to the SCEV for this 6169 // addition, then compute the SCEV for this addition by itself 6170 // with a separate call to getAddExpr. We need to do that 6171 // instead of pushing the operands of the addition onto AddOps, 6172 // since the flags are only known to apply to this particular 6173 // addition - they may not apply to other additions that can be 6174 // formed with operands from AddOps. 6175 const SCEV *RHS = getSCEV(BO->RHS); 6176 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6177 if (Flags != SCEV::FlagAnyWrap) { 6178 const SCEV *LHS = getSCEV(BO->LHS); 6179 if (BO->Opcode == Instruction::Sub) 6180 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6181 else 6182 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6183 break; 6184 } 6185 } 6186 6187 if (BO->Opcode == Instruction::Sub) 6188 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6189 else 6190 AddOps.push_back(getSCEV(BO->RHS)); 6191 6192 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6193 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6194 NewBO->Opcode != Instruction::Sub)) { 6195 AddOps.push_back(getSCEV(BO->LHS)); 6196 break; 6197 } 6198 BO = NewBO; 6199 } while (true); 6200 6201 return getAddExpr(AddOps); 6202 } 6203 6204 case Instruction::Mul: { 6205 SmallVector<const SCEV *, 4> MulOps; 6206 do { 6207 if (BO->Op) { 6208 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6209 MulOps.push_back(OpSCEV); 6210 break; 6211 } 6212 6213 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6214 if (Flags != SCEV::FlagAnyWrap) { 6215 MulOps.push_back( 6216 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6217 break; 6218 } 6219 } 6220 6221 MulOps.push_back(getSCEV(BO->RHS)); 6222 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6223 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6224 MulOps.push_back(getSCEV(BO->LHS)); 6225 break; 6226 } 6227 BO = NewBO; 6228 } while (true); 6229 6230 return getMulExpr(MulOps); 6231 } 6232 case Instruction::UDiv: 6233 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6234 case Instruction::URem: 6235 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6236 case Instruction::Sub: { 6237 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6238 if (BO->Op) 6239 Flags = getNoWrapFlagsFromUB(BO->Op); 6240 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6241 } 6242 case Instruction::And: 6243 // For an expression like x&255 that merely masks off the high bits, 6244 // use zext(trunc(x)) as the SCEV expression. 6245 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6246 if (CI->isZero()) 6247 return getSCEV(BO->RHS); 6248 if (CI->isMinusOne()) 6249 return getSCEV(BO->LHS); 6250 const APInt &A = CI->getValue(); 6251 6252 // Instcombine's ShrinkDemandedConstant may strip bits out of 6253 // constants, obscuring what would otherwise be a low-bits mask. 6254 // Use computeKnownBits to compute what ShrinkDemandedConstant 6255 // knew about to reconstruct a low-bits mask value. 6256 unsigned LZ = A.countLeadingZeros(); 6257 unsigned TZ = A.countTrailingZeros(); 6258 unsigned BitWidth = A.getBitWidth(); 6259 KnownBits Known(BitWidth); 6260 computeKnownBits(BO->LHS, Known, getDataLayout(), 6261 0, &AC, nullptr, &DT); 6262 6263 APInt EffectiveMask = 6264 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6265 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6266 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6267 const SCEV *LHS = getSCEV(BO->LHS); 6268 const SCEV *ShiftedLHS = nullptr; 6269 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6270 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6271 // For an expression like (x * 8) & 8, simplify the multiply. 6272 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6273 unsigned GCD = std::min(MulZeros, TZ); 6274 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6275 SmallVector<const SCEV*, 4> MulOps; 6276 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6277 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6278 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6279 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6280 } 6281 } 6282 if (!ShiftedLHS) 6283 ShiftedLHS = getUDivExpr(LHS, MulCount); 6284 return getMulExpr( 6285 getZeroExtendExpr( 6286 getTruncateExpr(ShiftedLHS, 6287 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6288 BO->LHS->getType()), 6289 MulCount); 6290 } 6291 } 6292 break; 6293 6294 case Instruction::Or: 6295 // If the RHS of the Or is a constant, we may have something like: 6296 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6297 // optimizations will transparently handle this case. 6298 // 6299 // In order for this transformation to be safe, the LHS must be of the 6300 // form X*(2^n) and the Or constant must be less than 2^n. 6301 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6302 const SCEV *LHS = getSCEV(BO->LHS); 6303 const APInt &CIVal = CI->getValue(); 6304 if (GetMinTrailingZeros(LHS) >= 6305 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6306 // Build a plain add SCEV. 6307 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6308 // If the LHS of the add was an addrec and it has no-wrap flags, 6309 // transfer the no-wrap flags, since an or won't introduce a wrap. 6310 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6311 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6312 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6313 OldAR->getNoWrapFlags()); 6314 } 6315 return S; 6316 } 6317 } 6318 break; 6319 6320 case Instruction::Xor: 6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6322 // If the RHS of xor is -1, then this is a not operation. 6323 if (CI->isMinusOne()) 6324 return getNotSCEV(getSCEV(BO->LHS)); 6325 6326 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6327 // This is a variant of the check for xor with -1, and it handles 6328 // the case where instcombine has trimmed non-demanded bits out 6329 // of an xor with -1. 6330 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6331 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6332 if (LBO->getOpcode() == Instruction::And && 6333 LCI->getValue() == CI->getValue()) 6334 if (const SCEVZeroExtendExpr *Z = 6335 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6336 Type *UTy = BO->LHS->getType(); 6337 const SCEV *Z0 = Z->getOperand(); 6338 Type *Z0Ty = Z0->getType(); 6339 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6340 6341 // If C is a low-bits mask, the zero extend is serving to 6342 // mask off the high bits. Complement the operand and 6343 // re-apply the zext. 6344 if (CI->getValue().isMask(Z0TySize)) 6345 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6346 6347 // If C is a single bit, it may be in the sign-bit position 6348 // before the zero-extend. In this case, represent the xor 6349 // using an add, which is equivalent, and re-apply the zext. 6350 APInt Trunc = CI->getValue().trunc(Z0TySize); 6351 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6352 Trunc.isSignMask()) 6353 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6354 UTy); 6355 } 6356 } 6357 break; 6358 6359 case Instruction::Shl: 6360 // Turn shift left of a constant amount into a multiply. 6361 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6362 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6363 6364 // If the shift count is not less than the bitwidth, the result of 6365 // the shift is undefined. Don't try to analyze it, because the 6366 // resolution chosen here may differ from the resolution chosen in 6367 // other parts of the compiler. 6368 if (SA->getValue().uge(BitWidth)) 6369 break; 6370 6371 // It is currently not resolved how to interpret NSW for left 6372 // shift by BitWidth - 1, so we avoid applying flags in that 6373 // case. Remove this check (or this comment) once the situation 6374 // is resolved. See 6375 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6376 // and http://reviews.llvm.org/D8890 . 6377 auto Flags = SCEV::FlagAnyWrap; 6378 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6379 Flags = getNoWrapFlagsFromUB(BO->Op); 6380 6381 Constant *X = ConstantInt::get( 6382 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6383 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6384 } 6385 break; 6386 6387 case Instruction::AShr: { 6388 // AShr X, C, where C is a constant. 6389 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6390 if (!CI) 6391 break; 6392 6393 Type *OuterTy = BO->LHS->getType(); 6394 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6395 // If the shift count is not less than the bitwidth, the result of 6396 // the shift is undefined. Don't try to analyze it, because the 6397 // resolution chosen here may differ from the resolution chosen in 6398 // other parts of the compiler. 6399 if (CI->getValue().uge(BitWidth)) 6400 break; 6401 6402 if (CI->isZero()) 6403 return getSCEV(BO->LHS); // shift by zero --> noop 6404 6405 uint64_t AShrAmt = CI->getZExtValue(); 6406 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6407 6408 Operator *L = dyn_cast<Operator>(BO->LHS); 6409 if (L && L->getOpcode() == Instruction::Shl) { 6410 // X = Shl A, n 6411 // Y = AShr X, m 6412 // Both n and m are constant. 6413 6414 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6415 if (L->getOperand(1) == BO->RHS) 6416 // For a two-shift sext-inreg, i.e. n = m, 6417 // use sext(trunc(x)) as the SCEV expression. 6418 return getSignExtendExpr( 6419 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6420 6421 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6422 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6423 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6424 if (ShlAmt > AShrAmt) { 6425 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6426 // expression. We already checked that ShlAmt < BitWidth, so 6427 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6428 // ShlAmt - AShrAmt < Amt. 6429 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6430 ShlAmt - AShrAmt); 6431 return getSignExtendExpr( 6432 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6433 getConstant(Mul)), OuterTy); 6434 } 6435 } 6436 } 6437 break; 6438 } 6439 } 6440 } 6441 6442 switch (U->getOpcode()) { 6443 case Instruction::Trunc: 6444 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6445 6446 case Instruction::ZExt: 6447 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6448 6449 case Instruction::SExt: 6450 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6451 // The NSW flag of a subtract does not always survive the conversion to 6452 // A + (-1)*B. By pushing sign extension onto its operands we are much 6453 // more likely to preserve NSW and allow later AddRec optimisations. 6454 // 6455 // NOTE: This is effectively duplicating this logic from getSignExtend: 6456 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6457 // but by that point the NSW information has potentially been lost. 6458 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6459 Type *Ty = U->getType(); 6460 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6461 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6462 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6463 } 6464 } 6465 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6466 6467 case Instruction::BitCast: 6468 // BitCasts are no-op casts so we just eliminate the cast. 6469 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6470 return getSCEV(U->getOperand(0)); 6471 break; 6472 6473 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6474 // lead to pointer expressions which cannot safely be expanded to GEPs, 6475 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6476 // simplifying integer expressions. 6477 6478 case Instruction::GetElementPtr: 6479 return createNodeForGEP(cast<GEPOperator>(U)); 6480 6481 case Instruction::PHI: 6482 return createNodeForPHI(cast<PHINode>(U)); 6483 6484 case Instruction::Select: 6485 // U can also be a select constant expr, which let fall through. Since 6486 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6487 // constant expressions cannot have instructions as operands, we'd have 6488 // returned getUnknown for a select constant expressions anyway. 6489 if (isa<Instruction>(U)) 6490 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6491 U->getOperand(1), U->getOperand(2)); 6492 break; 6493 6494 case Instruction::Call: 6495 case Instruction::Invoke: 6496 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6497 return getSCEV(RV); 6498 break; 6499 } 6500 6501 return getUnknown(V); 6502 } 6503 6504 //===----------------------------------------------------------------------===// 6505 // Iteration Count Computation Code 6506 // 6507 6508 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6509 if (!ExitCount) 6510 return 0; 6511 6512 ConstantInt *ExitConst = ExitCount->getValue(); 6513 6514 // Guard against huge trip counts. 6515 if (ExitConst->getValue().getActiveBits() > 32) 6516 return 0; 6517 6518 // In case of integer overflow, this returns 0, which is correct. 6519 return ((unsigned)ExitConst->getZExtValue()) + 1; 6520 } 6521 6522 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6523 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6524 return getSmallConstantTripCount(L, ExitingBB); 6525 6526 // No trip count information for multiple exits. 6527 return 0; 6528 } 6529 6530 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6531 BasicBlock *ExitingBlock) { 6532 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6533 assert(L->isLoopExiting(ExitingBlock) && 6534 "Exiting block must actually branch out of the loop!"); 6535 const SCEVConstant *ExitCount = 6536 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6537 return getConstantTripCount(ExitCount); 6538 } 6539 6540 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6541 const auto *MaxExitCount = 6542 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6543 return getConstantTripCount(MaxExitCount); 6544 } 6545 6546 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6547 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6548 return getSmallConstantTripMultiple(L, ExitingBB); 6549 6550 // No trip multiple information for multiple exits. 6551 return 0; 6552 } 6553 6554 /// Returns the largest constant divisor of the trip count of this loop as a 6555 /// normal unsigned value, if possible. This means that the actual trip count is 6556 /// always a multiple of the returned value (don't forget the trip count could 6557 /// very well be zero as well!). 6558 /// 6559 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6560 /// multiple of a constant (which is also the case if the trip count is simply 6561 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6562 /// if the trip count is very large (>= 2^32). 6563 /// 6564 /// As explained in the comments for getSmallConstantTripCount, this assumes 6565 /// that control exits the loop via ExitingBlock. 6566 unsigned 6567 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6568 BasicBlock *ExitingBlock) { 6569 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6570 assert(L->isLoopExiting(ExitingBlock) && 6571 "Exiting block must actually branch out of the loop!"); 6572 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6573 if (ExitCount == getCouldNotCompute()) 6574 return 1; 6575 6576 // Get the trip count from the BE count by adding 1. 6577 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6578 6579 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6580 if (!TC) 6581 // Attempt to factor more general cases. Returns the greatest power of 6582 // two divisor. If overflow happens, the trip count expression is still 6583 // divisible by the greatest power of 2 divisor returned. 6584 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6585 6586 ConstantInt *Result = TC->getValue(); 6587 6588 // Guard against huge trip counts (this requires checking 6589 // for zero to handle the case where the trip count == -1 and the 6590 // addition wraps). 6591 if (!Result || Result->getValue().getActiveBits() > 32 || 6592 Result->getValue().getActiveBits() == 0) 6593 return 1; 6594 6595 return (unsigned)Result->getZExtValue(); 6596 } 6597 6598 /// Get the expression for the number of loop iterations for which this loop is 6599 /// guaranteed not to exit via ExitingBlock. Otherwise return 6600 /// SCEVCouldNotCompute. 6601 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6602 BasicBlock *ExitingBlock) { 6603 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6604 } 6605 6606 const SCEV * 6607 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6608 SCEVUnionPredicate &Preds) { 6609 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6610 } 6611 6612 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6613 return getBackedgeTakenInfo(L).getExact(L, this); 6614 } 6615 6616 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6617 /// known never to be less than the actual backedge taken count. 6618 const SCEV *ScalarEvolution::getConstantMaxBackedgeTakenCount(const Loop *L) { 6619 return getBackedgeTakenInfo(L).getMax(this); 6620 } 6621 6622 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6623 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6624 } 6625 6626 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6627 static void 6628 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6629 BasicBlock *Header = L->getHeader(); 6630 6631 // Push all Loop-header PHIs onto the Worklist stack. 6632 for (PHINode &PN : Header->phis()) 6633 Worklist.push_back(&PN); 6634 } 6635 6636 const ScalarEvolution::BackedgeTakenInfo & 6637 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6638 auto &BTI = getBackedgeTakenInfo(L); 6639 if (BTI.hasFullInfo()) 6640 return BTI; 6641 6642 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6643 6644 if (!Pair.second) 6645 return Pair.first->second; 6646 6647 BackedgeTakenInfo Result = 6648 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6649 6650 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6651 } 6652 6653 const ScalarEvolution::BackedgeTakenInfo & 6654 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6655 // Initially insert an invalid entry for this loop. If the insertion 6656 // succeeds, proceed to actually compute a backedge-taken count and 6657 // update the value. The temporary CouldNotCompute value tells SCEV 6658 // code elsewhere that it shouldn't attempt to request a new 6659 // backedge-taken count, which could result in infinite recursion. 6660 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6661 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6662 if (!Pair.second) 6663 return Pair.first->second; 6664 6665 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6666 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6667 // must be cleared in this scope. 6668 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6669 6670 // In product build, there are no usage of statistic. 6671 (void)NumTripCountsComputed; 6672 (void)NumTripCountsNotComputed; 6673 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6674 const SCEV *BEExact = Result.getExact(L, this); 6675 if (BEExact != getCouldNotCompute()) { 6676 assert(isLoopInvariant(BEExact, L) && 6677 isLoopInvariant(Result.getMax(this), L) && 6678 "Computed backedge-taken count isn't loop invariant for loop!"); 6679 ++NumTripCountsComputed; 6680 } 6681 else if (Result.getMax(this) == getCouldNotCompute() && 6682 isa<PHINode>(L->getHeader()->begin())) { 6683 // Only count loops that have phi nodes as not being computable. 6684 ++NumTripCountsNotComputed; 6685 } 6686 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6687 6688 // Now that we know more about the trip count for this loop, forget any 6689 // existing SCEV values for PHI nodes in this loop since they are only 6690 // conservative estimates made without the benefit of trip count 6691 // information. This is similar to the code in forgetLoop, except that 6692 // it handles SCEVUnknown PHI nodes specially. 6693 if (Result.hasAnyInfo()) { 6694 SmallVector<Instruction *, 16> Worklist; 6695 PushLoopPHIs(L, Worklist); 6696 6697 SmallPtrSet<Instruction *, 8> Discovered; 6698 while (!Worklist.empty()) { 6699 Instruction *I = Worklist.pop_back_val(); 6700 6701 ValueExprMapType::iterator It = 6702 ValueExprMap.find_as(static_cast<Value *>(I)); 6703 if (It != ValueExprMap.end()) { 6704 const SCEV *Old = It->second; 6705 6706 // SCEVUnknown for a PHI either means that it has an unrecognized 6707 // structure, or it's a PHI that's in the progress of being computed 6708 // by createNodeForPHI. In the former case, additional loop trip 6709 // count information isn't going to change anything. In the later 6710 // case, createNodeForPHI will perform the necessary updates on its 6711 // own when it gets to that point. 6712 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6713 eraseValueFromMap(It->first); 6714 forgetMemoizedResults(Old); 6715 } 6716 if (PHINode *PN = dyn_cast<PHINode>(I)) 6717 ConstantEvolutionLoopExitValue.erase(PN); 6718 } 6719 6720 // Since we don't need to invalidate anything for correctness and we're 6721 // only invalidating to make SCEV's results more precise, we get to stop 6722 // early to avoid invalidating too much. This is especially important in 6723 // cases like: 6724 // 6725 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6726 // loop0: 6727 // %pn0 = phi 6728 // ... 6729 // loop1: 6730 // %pn1 = phi 6731 // ... 6732 // 6733 // where both loop0 and loop1's backedge taken count uses the SCEV 6734 // expression for %v. If we don't have the early stop below then in cases 6735 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6736 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6737 // count for loop1, effectively nullifying SCEV's trip count cache. 6738 for (auto *U : I->users()) 6739 if (auto *I = dyn_cast<Instruction>(U)) { 6740 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6741 if (LoopForUser && L->contains(LoopForUser) && 6742 Discovered.insert(I).second) 6743 Worklist.push_back(I); 6744 } 6745 } 6746 } 6747 6748 // Re-lookup the insert position, since the call to 6749 // computeBackedgeTakenCount above could result in a 6750 // recusive call to getBackedgeTakenInfo (on a different 6751 // loop), which would invalidate the iterator computed 6752 // earlier. 6753 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6754 } 6755 6756 void ScalarEvolution::forgetAllLoops() { 6757 // This method is intended to forget all info about loops. It should 6758 // invalidate caches as if the following happened: 6759 // - The trip counts of all loops have changed arbitrarily 6760 // - Every llvm::Value has been updated in place to produce a different 6761 // result. 6762 BackedgeTakenCounts.clear(); 6763 PredicatedBackedgeTakenCounts.clear(); 6764 LoopPropertiesCache.clear(); 6765 ConstantEvolutionLoopExitValue.clear(); 6766 ValueExprMap.clear(); 6767 ValuesAtScopes.clear(); 6768 LoopDispositions.clear(); 6769 BlockDispositions.clear(); 6770 UnsignedRanges.clear(); 6771 SignedRanges.clear(); 6772 ExprValueMap.clear(); 6773 HasRecMap.clear(); 6774 MinTrailingZerosCache.clear(); 6775 PredicatedSCEVRewrites.clear(); 6776 } 6777 6778 void ScalarEvolution::forgetLoop(const Loop *L) { 6779 // Drop any stored trip count value. 6780 auto RemoveLoopFromBackedgeMap = 6781 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6782 auto BTCPos = Map.find(L); 6783 if (BTCPos != Map.end()) { 6784 BTCPos->second.clear(); 6785 Map.erase(BTCPos); 6786 } 6787 }; 6788 6789 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6790 SmallVector<Instruction *, 32> Worklist; 6791 SmallPtrSet<Instruction *, 16> Visited; 6792 6793 // Iterate over all the loops and sub-loops to drop SCEV information. 6794 while (!LoopWorklist.empty()) { 6795 auto *CurrL = LoopWorklist.pop_back_val(); 6796 6797 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6798 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6799 6800 // Drop information about predicated SCEV rewrites for this loop. 6801 for (auto I = PredicatedSCEVRewrites.begin(); 6802 I != PredicatedSCEVRewrites.end();) { 6803 std::pair<const SCEV *, const Loop *> Entry = I->first; 6804 if (Entry.second == CurrL) 6805 PredicatedSCEVRewrites.erase(I++); 6806 else 6807 ++I; 6808 } 6809 6810 auto LoopUsersItr = LoopUsers.find(CurrL); 6811 if (LoopUsersItr != LoopUsers.end()) { 6812 for (auto *S : LoopUsersItr->second) 6813 forgetMemoizedResults(S); 6814 LoopUsers.erase(LoopUsersItr); 6815 } 6816 6817 // Drop information about expressions based on loop-header PHIs. 6818 PushLoopPHIs(CurrL, Worklist); 6819 6820 while (!Worklist.empty()) { 6821 Instruction *I = Worklist.pop_back_val(); 6822 if (!Visited.insert(I).second) 6823 continue; 6824 6825 ValueExprMapType::iterator It = 6826 ValueExprMap.find_as(static_cast<Value *>(I)); 6827 if (It != ValueExprMap.end()) { 6828 eraseValueFromMap(It->first); 6829 forgetMemoizedResults(It->second); 6830 if (PHINode *PN = dyn_cast<PHINode>(I)) 6831 ConstantEvolutionLoopExitValue.erase(PN); 6832 } 6833 6834 PushDefUseChildren(I, Worklist); 6835 } 6836 6837 LoopPropertiesCache.erase(CurrL); 6838 // Forget all contained loops too, to avoid dangling entries in the 6839 // ValuesAtScopes map. 6840 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6841 } 6842 } 6843 6844 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6845 while (Loop *Parent = L->getParentLoop()) 6846 L = Parent; 6847 forgetLoop(L); 6848 } 6849 6850 void ScalarEvolution::forgetValue(Value *V) { 6851 Instruction *I = dyn_cast<Instruction>(V); 6852 if (!I) return; 6853 6854 // Drop information about expressions based on loop-header PHIs. 6855 SmallVector<Instruction *, 16> Worklist; 6856 Worklist.push_back(I); 6857 6858 SmallPtrSet<Instruction *, 8> Visited; 6859 while (!Worklist.empty()) { 6860 I = Worklist.pop_back_val(); 6861 if (!Visited.insert(I).second) 6862 continue; 6863 6864 ValueExprMapType::iterator It = 6865 ValueExprMap.find_as(static_cast<Value *>(I)); 6866 if (It != ValueExprMap.end()) { 6867 eraseValueFromMap(It->first); 6868 forgetMemoizedResults(It->second); 6869 if (PHINode *PN = dyn_cast<PHINode>(I)) 6870 ConstantEvolutionLoopExitValue.erase(PN); 6871 } 6872 6873 PushDefUseChildren(I, Worklist); 6874 } 6875 } 6876 6877 /// Get the exact loop backedge taken count considering all loop exits. A 6878 /// computable result can only be returned for loops with all exiting blocks 6879 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6880 /// is never skipped. This is a valid assumption as long as the loop exits via 6881 /// that test. For precise results, it is the caller's responsibility to specify 6882 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6883 const SCEV * 6884 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6885 SCEVUnionPredicate *Preds) const { 6886 // If any exits were not computable, the loop is not computable. 6887 if (!isComplete() || ExitNotTaken.empty()) 6888 return SE->getCouldNotCompute(); 6889 6890 const BasicBlock *Latch = L->getLoopLatch(); 6891 // All exiting blocks we have collected must dominate the only backedge. 6892 if (!Latch) 6893 return SE->getCouldNotCompute(); 6894 6895 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6896 // count is simply a minimum out of all these calculated exit counts. 6897 SmallVector<const SCEV *, 2> Ops; 6898 for (auto &ENT : ExitNotTaken) { 6899 const SCEV *BECount = ENT.ExactNotTaken; 6900 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6901 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6902 "We should only have known counts for exiting blocks that dominate " 6903 "latch!"); 6904 6905 Ops.push_back(BECount); 6906 6907 if (Preds && !ENT.hasAlwaysTruePredicate()) 6908 Preds->add(ENT.Predicate.get()); 6909 6910 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6911 "Predicate should be always true!"); 6912 } 6913 6914 return SE->getUMinFromMismatchedTypes(Ops); 6915 } 6916 6917 /// Get the exact not taken count for this loop exit. 6918 const SCEV * 6919 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6920 ScalarEvolution *SE) const { 6921 for (auto &ENT : ExitNotTaken) 6922 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6923 return ENT.ExactNotTaken; 6924 6925 return SE->getCouldNotCompute(); 6926 } 6927 6928 /// getMax - Get the max backedge taken count for the loop. 6929 const SCEV * 6930 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6931 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6932 return !ENT.hasAlwaysTruePredicate(); 6933 }; 6934 6935 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6936 return SE->getCouldNotCompute(); 6937 6938 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6939 "No point in having a non-constant max backedge taken count!"); 6940 return getMax(); 6941 } 6942 6943 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6944 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6945 return !ENT.hasAlwaysTruePredicate(); 6946 }; 6947 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6948 } 6949 6950 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6951 ScalarEvolution *SE) const { 6952 if (getMax() && getMax() != SE->getCouldNotCompute() && 6953 SE->hasOperand(getMax(), S)) 6954 return true; 6955 6956 for (auto &ENT : ExitNotTaken) 6957 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6958 SE->hasOperand(ENT.ExactNotTaken, S)) 6959 return true; 6960 6961 return false; 6962 } 6963 6964 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6965 : ExactNotTaken(E), MaxNotTaken(E) { 6966 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6967 isa<SCEVConstant>(MaxNotTaken)) && 6968 "No point in having a non-constant max backedge taken count!"); 6969 } 6970 6971 ScalarEvolution::ExitLimit::ExitLimit( 6972 const SCEV *E, const SCEV *M, bool MaxOrZero, 6973 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6974 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6975 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6976 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6977 "Exact is not allowed to be less precise than Max"); 6978 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6979 isa<SCEVConstant>(MaxNotTaken)) && 6980 "No point in having a non-constant max backedge taken count!"); 6981 for (auto *PredSet : PredSetList) 6982 for (auto *P : *PredSet) 6983 addPredicate(P); 6984 } 6985 6986 ScalarEvolution::ExitLimit::ExitLimit( 6987 const SCEV *E, const SCEV *M, bool MaxOrZero, 6988 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6989 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6990 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6991 isa<SCEVConstant>(MaxNotTaken)) && 6992 "No point in having a non-constant max backedge taken count!"); 6993 } 6994 6995 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6996 bool MaxOrZero) 6997 : ExitLimit(E, M, MaxOrZero, None) { 6998 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6999 isa<SCEVConstant>(MaxNotTaken)) && 7000 "No point in having a non-constant max backedge taken count!"); 7001 } 7002 7003 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7004 /// computable exit into a persistent ExitNotTakenInfo array. 7005 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7006 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7007 ExitCounts, 7008 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7009 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7010 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7011 7012 ExitNotTaken.reserve(ExitCounts.size()); 7013 std::transform( 7014 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7015 [&](const EdgeExitInfo &EEI) { 7016 BasicBlock *ExitBB = EEI.first; 7017 const ExitLimit &EL = EEI.second; 7018 if (EL.Predicates.empty()) 7019 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 7020 7021 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7022 for (auto *Pred : EL.Predicates) 7023 Predicate->add(Pred); 7024 7025 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 7026 }); 7027 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7028 "No point in having a non-constant max backedge taken count!"); 7029 } 7030 7031 /// Invalidate this result and free the ExitNotTakenInfo array. 7032 void ScalarEvolution::BackedgeTakenInfo::clear() { 7033 ExitNotTaken.clear(); 7034 } 7035 7036 /// Compute the number of times the backedge of the specified loop will execute. 7037 ScalarEvolution::BackedgeTakenInfo 7038 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7039 bool AllowPredicates) { 7040 SmallVector<BasicBlock *, 8> ExitingBlocks; 7041 L->getExitingBlocks(ExitingBlocks); 7042 7043 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7044 7045 SmallVector<EdgeExitInfo, 4> ExitCounts; 7046 bool CouldComputeBECount = true; 7047 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7048 const SCEV *MustExitMaxBECount = nullptr; 7049 const SCEV *MayExitMaxBECount = nullptr; 7050 bool MustExitMaxOrZero = false; 7051 7052 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7053 // and compute maxBECount. 7054 // Do a union of all the predicates here. 7055 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7056 BasicBlock *ExitBB = ExitingBlocks[i]; 7057 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7058 7059 assert((AllowPredicates || EL.Predicates.empty()) && 7060 "Predicated exit limit when predicates are not allowed!"); 7061 7062 // 1. For each exit that can be computed, add an entry to ExitCounts. 7063 // CouldComputeBECount is true only if all exits can be computed. 7064 if (EL.ExactNotTaken == getCouldNotCompute()) 7065 // We couldn't compute an exact value for this exit, so 7066 // we won't be able to compute an exact value for the loop. 7067 CouldComputeBECount = false; 7068 else 7069 ExitCounts.emplace_back(ExitBB, EL); 7070 7071 // 2. Derive the loop's MaxBECount from each exit's max number of 7072 // non-exiting iterations. Partition the loop exits into two kinds: 7073 // LoopMustExits and LoopMayExits. 7074 // 7075 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7076 // is a LoopMayExit. If any computable LoopMustExit is found, then 7077 // MaxBECount is the minimum EL.MaxNotTaken of computable 7078 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7079 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7080 // computable EL.MaxNotTaken. 7081 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7082 DT.dominates(ExitBB, Latch)) { 7083 if (!MustExitMaxBECount) { 7084 MustExitMaxBECount = EL.MaxNotTaken; 7085 MustExitMaxOrZero = EL.MaxOrZero; 7086 } else { 7087 MustExitMaxBECount = 7088 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7089 } 7090 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7091 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7092 MayExitMaxBECount = EL.MaxNotTaken; 7093 else { 7094 MayExitMaxBECount = 7095 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7096 } 7097 } 7098 } 7099 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7100 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7101 // The loop backedge will be taken the maximum or zero times if there's 7102 // a single exit that must be taken the maximum or zero times. 7103 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7104 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7105 MaxBECount, MaxOrZero); 7106 } 7107 7108 ScalarEvolution::ExitLimit 7109 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7110 bool AllowPredicates) { 7111 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7112 // If our exiting block does not dominate the latch, then its connection with 7113 // loop's exit limit may be far from trivial. 7114 const BasicBlock *Latch = L->getLoopLatch(); 7115 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7116 return getCouldNotCompute(); 7117 7118 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7119 Instruction *Term = ExitingBlock->getTerminator(); 7120 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7121 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7122 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7123 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7124 "It should have one successor in loop and one exit block!"); 7125 // Proceed to the next level to examine the exit condition expression. 7126 return computeExitLimitFromCond( 7127 L, BI->getCondition(), ExitIfTrue, 7128 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7129 } 7130 7131 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7132 // For switch, make sure that there is a single exit from the loop. 7133 BasicBlock *Exit = nullptr; 7134 for (auto *SBB : successors(ExitingBlock)) 7135 if (!L->contains(SBB)) { 7136 if (Exit) // Multiple exit successors. 7137 return getCouldNotCompute(); 7138 Exit = SBB; 7139 } 7140 assert(Exit && "Exiting block must have at least one exit"); 7141 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7142 /*ControlsExit=*/IsOnlyExit); 7143 } 7144 7145 return getCouldNotCompute(); 7146 } 7147 7148 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7149 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7150 bool ControlsExit, bool AllowPredicates) { 7151 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7152 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7153 ControlsExit, AllowPredicates); 7154 } 7155 7156 Optional<ScalarEvolution::ExitLimit> 7157 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7158 bool ExitIfTrue, bool ControlsExit, 7159 bool AllowPredicates) { 7160 (void)this->L; 7161 (void)this->ExitIfTrue; 7162 (void)this->AllowPredicates; 7163 7164 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7165 this->AllowPredicates == AllowPredicates && 7166 "Variance in assumed invariant key components!"); 7167 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7168 if (Itr == TripCountMap.end()) 7169 return None; 7170 return Itr->second; 7171 } 7172 7173 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7174 bool ExitIfTrue, 7175 bool ControlsExit, 7176 bool AllowPredicates, 7177 const ExitLimit &EL) { 7178 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7179 this->AllowPredicates == AllowPredicates && 7180 "Variance in assumed invariant key components!"); 7181 7182 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7183 assert(InsertResult.second && "Expected successful insertion!"); 7184 (void)InsertResult; 7185 (void)ExitIfTrue; 7186 } 7187 7188 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7189 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7190 bool ControlsExit, bool AllowPredicates) { 7191 7192 if (auto MaybeEL = 7193 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7194 return *MaybeEL; 7195 7196 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7197 ControlsExit, AllowPredicates); 7198 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7199 return EL; 7200 } 7201 7202 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7203 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7204 bool ControlsExit, bool AllowPredicates) { 7205 // Check if the controlling expression for this loop is an And or Or. 7206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7207 if (BO->getOpcode() == Instruction::And) { 7208 // Recurse on the operands of the and. 7209 bool EitherMayExit = !ExitIfTrue; 7210 ExitLimit EL0 = computeExitLimitFromCondCached( 7211 Cache, L, BO->getOperand(0), ExitIfTrue, 7212 ControlsExit && !EitherMayExit, AllowPredicates); 7213 ExitLimit EL1 = computeExitLimitFromCondCached( 7214 Cache, L, BO->getOperand(1), ExitIfTrue, 7215 ControlsExit && !EitherMayExit, AllowPredicates); 7216 const SCEV *BECount = getCouldNotCompute(); 7217 const SCEV *MaxBECount = getCouldNotCompute(); 7218 if (EitherMayExit) { 7219 // Both conditions must be true for the loop to continue executing. 7220 // Choose the less conservative count. 7221 if (EL0.ExactNotTaken == getCouldNotCompute() || 7222 EL1.ExactNotTaken == getCouldNotCompute()) 7223 BECount = getCouldNotCompute(); 7224 else 7225 BECount = 7226 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7227 if (EL0.MaxNotTaken == getCouldNotCompute()) 7228 MaxBECount = EL1.MaxNotTaken; 7229 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7230 MaxBECount = EL0.MaxNotTaken; 7231 else 7232 MaxBECount = 7233 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7234 } else { 7235 // Both conditions must be true at the same time for the loop to exit. 7236 // For now, be conservative. 7237 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7238 MaxBECount = EL0.MaxNotTaken; 7239 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7240 BECount = EL0.ExactNotTaken; 7241 } 7242 7243 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7244 // to be more aggressive when computing BECount than when computing 7245 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7246 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7247 // to not. 7248 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7249 !isa<SCEVCouldNotCompute>(BECount)) 7250 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7251 7252 return ExitLimit(BECount, MaxBECount, false, 7253 {&EL0.Predicates, &EL1.Predicates}); 7254 } 7255 if (BO->getOpcode() == Instruction::Or) { 7256 // Recurse on the operands of the or. 7257 bool EitherMayExit = ExitIfTrue; 7258 ExitLimit EL0 = computeExitLimitFromCondCached( 7259 Cache, L, BO->getOperand(0), ExitIfTrue, 7260 ControlsExit && !EitherMayExit, AllowPredicates); 7261 ExitLimit EL1 = computeExitLimitFromCondCached( 7262 Cache, L, BO->getOperand(1), ExitIfTrue, 7263 ControlsExit && !EitherMayExit, AllowPredicates); 7264 const SCEV *BECount = getCouldNotCompute(); 7265 const SCEV *MaxBECount = getCouldNotCompute(); 7266 if (EitherMayExit) { 7267 // Both conditions must be false for the loop to continue executing. 7268 // Choose the less conservative count. 7269 if (EL0.ExactNotTaken == getCouldNotCompute() || 7270 EL1.ExactNotTaken == getCouldNotCompute()) 7271 BECount = getCouldNotCompute(); 7272 else 7273 BECount = 7274 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7275 if (EL0.MaxNotTaken == getCouldNotCompute()) 7276 MaxBECount = EL1.MaxNotTaken; 7277 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7278 MaxBECount = EL0.MaxNotTaken; 7279 else 7280 MaxBECount = 7281 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7282 } else { 7283 // Both conditions must be false at the same time for the loop to exit. 7284 // For now, be conservative. 7285 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7286 MaxBECount = EL0.MaxNotTaken; 7287 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7288 BECount = EL0.ExactNotTaken; 7289 } 7290 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7291 // to be more aggressive when computing BECount than when computing 7292 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7293 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7294 // to not. 7295 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7296 !isa<SCEVCouldNotCompute>(BECount)) 7297 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7298 7299 return ExitLimit(BECount, MaxBECount, false, 7300 {&EL0.Predicates, &EL1.Predicates}); 7301 } 7302 } 7303 7304 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7305 // Proceed to the next level to examine the icmp. 7306 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7307 ExitLimit EL = 7308 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7309 if (EL.hasFullInfo() || !AllowPredicates) 7310 return EL; 7311 7312 // Try again, but use SCEV predicates this time. 7313 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7314 /*AllowPredicates=*/true); 7315 } 7316 7317 // Check for a constant condition. These are normally stripped out by 7318 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7319 // preserve the CFG and is temporarily leaving constant conditions 7320 // in place. 7321 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7322 if (ExitIfTrue == !CI->getZExtValue()) 7323 // The backedge is always taken. 7324 return getCouldNotCompute(); 7325 else 7326 // The backedge is never taken. 7327 return getZero(CI->getType()); 7328 } 7329 7330 // If it's not an integer or pointer comparison then compute it the hard way. 7331 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7332 } 7333 7334 ScalarEvolution::ExitLimit 7335 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7336 ICmpInst *ExitCond, 7337 bool ExitIfTrue, 7338 bool ControlsExit, 7339 bool AllowPredicates) { 7340 // If the condition was exit on true, convert the condition to exit on false 7341 ICmpInst::Predicate Pred; 7342 if (!ExitIfTrue) 7343 Pred = ExitCond->getPredicate(); 7344 else 7345 Pred = ExitCond->getInversePredicate(); 7346 const ICmpInst::Predicate OriginalPred = Pred; 7347 7348 // Handle common loops like: for (X = "string"; *X; ++X) 7349 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7350 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7351 ExitLimit ItCnt = 7352 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7353 if (ItCnt.hasAnyInfo()) 7354 return ItCnt; 7355 } 7356 7357 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7358 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7359 7360 // Try to evaluate any dependencies out of the loop. 7361 LHS = getSCEVAtScope(LHS, L); 7362 RHS = getSCEVAtScope(RHS, L); 7363 7364 // At this point, we would like to compute how many iterations of the 7365 // loop the predicate will return true for these inputs. 7366 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7367 // If there is a loop-invariant, force it into the RHS. 7368 std::swap(LHS, RHS); 7369 Pred = ICmpInst::getSwappedPredicate(Pred); 7370 } 7371 7372 // Simplify the operands before analyzing them. 7373 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7374 7375 // If we have a comparison of a chrec against a constant, try to use value 7376 // ranges to answer this query. 7377 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7378 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7379 if (AddRec->getLoop() == L) { 7380 // Form the constant range. 7381 ConstantRange CompRange = 7382 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7383 7384 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7385 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7386 } 7387 7388 switch (Pred) { 7389 case ICmpInst::ICMP_NE: { // while (X != Y) 7390 // Convert to: while (X-Y != 0) 7391 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7392 AllowPredicates); 7393 if (EL.hasAnyInfo()) return EL; 7394 break; 7395 } 7396 case ICmpInst::ICMP_EQ: { // while (X == Y) 7397 // Convert to: while (X-Y == 0) 7398 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7399 if (EL.hasAnyInfo()) return EL; 7400 break; 7401 } 7402 case ICmpInst::ICMP_SLT: 7403 case ICmpInst::ICMP_ULT: { // while (X < Y) 7404 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7405 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7406 AllowPredicates); 7407 if (EL.hasAnyInfo()) return EL; 7408 break; 7409 } 7410 case ICmpInst::ICMP_SGT: 7411 case ICmpInst::ICMP_UGT: { // while (X > Y) 7412 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7413 ExitLimit EL = 7414 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7415 AllowPredicates); 7416 if (EL.hasAnyInfo()) return EL; 7417 break; 7418 } 7419 default: 7420 break; 7421 } 7422 7423 auto *ExhaustiveCount = 7424 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7425 7426 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7427 return ExhaustiveCount; 7428 7429 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7430 ExitCond->getOperand(1), L, OriginalPred); 7431 } 7432 7433 ScalarEvolution::ExitLimit 7434 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7435 SwitchInst *Switch, 7436 BasicBlock *ExitingBlock, 7437 bool ControlsExit) { 7438 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7439 7440 // Give up if the exit is the default dest of a switch. 7441 if (Switch->getDefaultDest() == ExitingBlock) 7442 return getCouldNotCompute(); 7443 7444 assert(L->contains(Switch->getDefaultDest()) && 7445 "Default case must not exit the loop!"); 7446 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7447 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7448 7449 // while (X != Y) --> while (X-Y != 0) 7450 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7451 if (EL.hasAnyInfo()) 7452 return EL; 7453 7454 return getCouldNotCompute(); 7455 } 7456 7457 static ConstantInt * 7458 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7459 ScalarEvolution &SE) { 7460 const SCEV *InVal = SE.getConstant(C); 7461 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7462 assert(isa<SCEVConstant>(Val) && 7463 "Evaluation of SCEV at constant didn't fold correctly?"); 7464 return cast<SCEVConstant>(Val)->getValue(); 7465 } 7466 7467 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7468 /// compute the backedge execution count. 7469 ScalarEvolution::ExitLimit 7470 ScalarEvolution::computeLoadConstantCompareExitLimit( 7471 LoadInst *LI, 7472 Constant *RHS, 7473 const Loop *L, 7474 ICmpInst::Predicate predicate) { 7475 if (LI->isVolatile()) return getCouldNotCompute(); 7476 7477 // Check to see if the loaded pointer is a getelementptr of a global. 7478 // TODO: Use SCEV instead of manually grubbing with GEPs. 7479 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7480 if (!GEP) return getCouldNotCompute(); 7481 7482 // Make sure that it is really a constant global we are gepping, with an 7483 // initializer, and make sure the first IDX is really 0. 7484 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7485 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7486 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7487 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7488 return getCouldNotCompute(); 7489 7490 // Okay, we allow one non-constant index into the GEP instruction. 7491 Value *VarIdx = nullptr; 7492 std::vector<Constant*> Indexes; 7493 unsigned VarIdxNum = 0; 7494 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7495 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7496 Indexes.push_back(CI); 7497 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7498 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7499 VarIdx = GEP->getOperand(i); 7500 VarIdxNum = i-2; 7501 Indexes.push_back(nullptr); 7502 } 7503 7504 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7505 if (!VarIdx) 7506 return getCouldNotCompute(); 7507 7508 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7509 // Check to see if X is a loop variant variable value now. 7510 const SCEV *Idx = getSCEV(VarIdx); 7511 Idx = getSCEVAtScope(Idx, L); 7512 7513 // We can only recognize very limited forms of loop index expressions, in 7514 // particular, only affine AddRec's like {C1,+,C2}. 7515 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7516 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7517 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7518 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7519 return getCouldNotCompute(); 7520 7521 unsigned MaxSteps = MaxBruteForceIterations; 7522 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7523 ConstantInt *ItCst = ConstantInt::get( 7524 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7525 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7526 7527 // Form the GEP offset. 7528 Indexes[VarIdxNum] = Val; 7529 7530 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7531 Indexes); 7532 if (!Result) break; // Cannot compute! 7533 7534 // Evaluate the condition for this iteration. 7535 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7536 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7537 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7538 ++NumArrayLenItCounts; 7539 return getConstant(ItCst); // Found terminating iteration! 7540 } 7541 } 7542 return getCouldNotCompute(); 7543 } 7544 7545 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7546 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7547 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7548 if (!RHS) 7549 return getCouldNotCompute(); 7550 7551 const BasicBlock *Latch = L->getLoopLatch(); 7552 if (!Latch) 7553 return getCouldNotCompute(); 7554 7555 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7556 if (!Predecessor) 7557 return getCouldNotCompute(); 7558 7559 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7560 // Return LHS in OutLHS and shift_opt in OutOpCode. 7561 auto MatchPositiveShift = 7562 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7563 7564 using namespace PatternMatch; 7565 7566 ConstantInt *ShiftAmt; 7567 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7568 OutOpCode = Instruction::LShr; 7569 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7570 OutOpCode = Instruction::AShr; 7571 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7572 OutOpCode = Instruction::Shl; 7573 else 7574 return false; 7575 7576 return ShiftAmt->getValue().isStrictlyPositive(); 7577 }; 7578 7579 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7580 // 7581 // loop: 7582 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7583 // %iv.shifted = lshr i32 %iv, <positive constant> 7584 // 7585 // Return true on a successful match. Return the corresponding PHI node (%iv 7586 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7587 auto MatchShiftRecurrence = 7588 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7589 Optional<Instruction::BinaryOps> PostShiftOpCode; 7590 7591 { 7592 Instruction::BinaryOps OpC; 7593 Value *V; 7594 7595 // If we encounter a shift instruction, "peel off" the shift operation, 7596 // and remember that we did so. Later when we inspect %iv's backedge 7597 // value, we will make sure that the backedge value uses the same 7598 // operation. 7599 // 7600 // Note: the peeled shift operation does not have to be the same 7601 // instruction as the one feeding into the PHI's backedge value. We only 7602 // really care about it being the same *kind* of shift instruction -- 7603 // that's all that is required for our later inferences to hold. 7604 if (MatchPositiveShift(LHS, V, OpC)) { 7605 PostShiftOpCode = OpC; 7606 LHS = V; 7607 } 7608 } 7609 7610 PNOut = dyn_cast<PHINode>(LHS); 7611 if (!PNOut || PNOut->getParent() != L->getHeader()) 7612 return false; 7613 7614 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7615 Value *OpLHS; 7616 7617 return 7618 // The backedge value for the PHI node must be a shift by a positive 7619 // amount 7620 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7621 7622 // of the PHI node itself 7623 OpLHS == PNOut && 7624 7625 // and the kind of shift should be match the kind of shift we peeled 7626 // off, if any. 7627 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7628 }; 7629 7630 PHINode *PN; 7631 Instruction::BinaryOps OpCode; 7632 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7633 return getCouldNotCompute(); 7634 7635 const DataLayout &DL = getDataLayout(); 7636 7637 // The key rationale for this optimization is that for some kinds of shift 7638 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7639 // within a finite number of iterations. If the condition guarding the 7640 // backedge (in the sense that the backedge is taken if the condition is true) 7641 // is false for the value the shift recurrence stabilizes to, then we know 7642 // that the backedge is taken only a finite number of times. 7643 7644 ConstantInt *StableValue = nullptr; 7645 switch (OpCode) { 7646 default: 7647 llvm_unreachable("Impossible case!"); 7648 7649 case Instruction::AShr: { 7650 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7651 // bitwidth(K) iterations. 7652 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7653 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7654 Predecessor->getTerminator(), &DT); 7655 auto *Ty = cast<IntegerType>(RHS->getType()); 7656 if (Known.isNonNegative()) 7657 StableValue = ConstantInt::get(Ty, 0); 7658 else if (Known.isNegative()) 7659 StableValue = ConstantInt::get(Ty, -1, true); 7660 else 7661 return getCouldNotCompute(); 7662 7663 break; 7664 } 7665 case Instruction::LShr: 7666 case Instruction::Shl: 7667 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7668 // stabilize to 0 in at most bitwidth(K) iterations. 7669 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7670 break; 7671 } 7672 7673 auto *Result = 7674 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7675 assert(Result->getType()->isIntegerTy(1) && 7676 "Otherwise cannot be an operand to a branch instruction"); 7677 7678 if (Result->isZeroValue()) { 7679 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7680 const SCEV *UpperBound = 7681 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7682 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7683 } 7684 7685 return getCouldNotCompute(); 7686 } 7687 7688 /// Return true if we can constant fold an instruction of the specified type, 7689 /// assuming that all operands were constants. 7690 static bool CanConstantFold(const Instruction *I) { 7691 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7692 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7693 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7694 return true; 7695 7696 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7697 if (const Function *F = CI->getCalledFunction()) 7698 return canConstantFoldCallTo(CI, F); 7699 return false; 7700 } 7701 7702 /// Determine whether this instruction can constant evolve within this loop 7703 /// assuming its operands can all constant evolve. 7704 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7705 // An instruction outside of the loop can't be derived from a loop PHI. 7706 if (!L->contains(I)) return false; 7707 7708 if (isa<PHINode>(I)) { 7709 // We don't currently keep track of the control flow needed to evaluate 7710 // PHIs, so we cannot handle PHIs inside of loops. 7711 return L->getHeader() == I->getParent(); 7712 } 7713 7714 // If we won't be able to constant fold this expression even if the operands 7715 // are constants, bail early. 7716 return CanConstantFold(I); 7717 } 7718 7719 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7720 /// recursing through each instruction operand until reaching a loop header phi. 7721 static PHINode * 7722 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7723 DenseMap<Instruction *, PHINode *> &PHIMap, 7724 unsigned Depth) { 7725 if (Depth > MaxConstantEvolvingDepth) 7726 return nullptr; 7727 7728 // Otherwise, we can evaluate this instruction if all of its operands are 7729 // constant or derived from a PHI node themselves. 7730 PHINode *PHI = nullptr; 7731 for (Value *Op : UseInst->operands()) { 7732 if (isa<Constant>(Op)) continue; 7733 7734 Instruction *OpInst = dyn_cast<Instruction>(Op); 7735 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7736 7737 PHINode *P = dyn_cast<PHINode>(OpInst); 7738 if (!P) 7739 // If this operand is already visited, reuse the prior result. 7740 // We may have P != PHI if this is the deepest point at which the 7741 // inconsistent paths meet. 7742 P = PHIMap.lookup(OpInst); 7743 if (!P) { 7744 // Recurse and memoize the results, whether a phi is found or not. 7745 // This recursive call invalidates pointers into PHIMap. 7746 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7747 PHIMap[OpInst] = P; 7748 } 7749 if (!P) 7750 return nullptr; // Not evolving from PHI 7751 if (PHI && PHI != P) 7752 return nullptr; // Evolving from multiple different PHIs. 7753 PHI = P; 7754 } 7755 // This is a expression evolving from a constant PHI! 7756 return PHI; 7757 } 7758 7759 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7760 /// in the loop that V is derived from. We allow arbitrary operations along the 7761 /// way, but the operands of an operation must either be constants or a value 7762 /// derived from a constant PHI. If this expression does not fit with these 7763 /// constraints, return null. 7764 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7765 Instruction *I = dyn_cast<Instruction>(V); 7766 if (!I || !canConstantEvolve(I, L)) return nullptr; 7767 7768 if (PHINode *PN = dyn_cast<PHINode>(I)) 7769 return PN; 7770 7771 // Record non-constant instructions contained by the loop. 7772 DenseMap<Instruction *, PHINode *> PHIMap; 7773 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7774 } 7775 7776 /// EvaluateExpression - Given an expression that passes the 7777 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7778 /// in the loop has the value PHIVal. If we can't fold this expression for some 7779 /// reason, return null. 7780 static Constant *EvaluateExpression(Value *V, const Loop *L, 7781 DenseMap<Instruction *, Constant *> &Vals, 7782 const DataLayout &DL, 7783 const TargetLibraryInfo *TLI) { 7784 // Convenient constant check, but redundant for recursive calls. 7785 if (Constant *C = dyn_cast<Constant>(V)) return C; 7786 Instruction *I = dyn_cast<Instruction>(V); 7787 if (!I) return nullptr; 7788 7789 if (Constant *C = Vals.lookup(I)) return C; 7790 7791 // An instruction inside the loop depends on a value outside the loop that we 7792 // weren't given a mapping for, or a value such as a call inside the loop. 7793 if (!canConstantEvolve(I, L)) return nullptr; 7794 7795 // An unmapped PHI can be due to a branch or another loop inside this loop, 7796 // or due to this not being the initial iteration through a loop where we 7797 // couldn't compute the evolution of this particular PHI last time. 7798 if (isa<PHINode>(I)) return nullptr; 7799 7800 std::vector<Constant*> Operands(I->getNumOperands()); 7801 7802 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7803 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7804 if (!Operand) { 7805 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7806 if (!Operands[i]) return nullptr; 7807 continue; 7808 } 7809 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7810 Vals[Operand] = C; 7811 if (!C) return nullptr; 7812 Operands[i] = C; 7813 } 7814 7815 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7816 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7817 Operands[1], DL, TLI); 7818 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7819 if (!LI->isVolatile()) 7820 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7821 } 7822 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7823 } 7824 7825 7826 // If every incoming value to PN except the one for BB is a specific Constant, 7827 // return that, else return nullptr. 7828 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7829 Constant *IncomingVal = nullptr; 7830 7831 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7832 if (PN->getIncomingBlock(i) == BB) 7833 continue; 7834 7835 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7836 if (!CurrentVal) 7837 return nullptr; 7838 7839 if (IncomingVal != CurrentVal) { 7840 if (IncomingVal) 7841 return nullptr; 7842 IncomingVal = CurrentVal; 7843 } 7844 } 7845 7846 return IncomingVal; 7847 } 7848 7849 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7850 /// in the header of its containing loop, we know the loop executes a 7851 /// constant number of times, and the PHI node is just a recurrence 7852 /// involving constants, fold it. 7853 Constant * 7854 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7855 const APInt &BEs, 7856 const Loop *L) { 7857 auto I = ConstantEvolutionLoopExitValue.find(PN); 7858 if (I != ConstantEvolutionLoopExitValue.end()) 7859 return I->second; 7860 7861 if (BEs.ugt(MaxBruteForceIterations)) 7862 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7863 7864 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7865 7866 DenseMap<Instruction *, Constant *> CurrentIterVals; 7867 BasicBlock *Header = L->getHeader(); 7868 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7869 7870 BasicBlock *Latch = L->getLoopLatch(); 7871 if (!Latch) 7872 return nullptr; 7873 7874 for (PHINode &PHI : Header->phis()) { 7875 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7876 CurrentIterVals[&PHI] = StartCST; 7877 } 7878 if (!CurrentIterVals.count(PN)) 7879 return RetVal = nullptr; 7880 7881 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7882 7883 // Execute the loop symbolically to determine the exit value. 7884 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7885 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7886 7887 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7888 unsigned IterationNum = 0; 7889 const DataLayout &DL = getDataLayout(); 7890 for (; ; ++IterationNum) { 7891 if (IterationNum == NumIterations) 7892 return RetVal = CurrentIterVals[PN]; // Got exit value! 7893 7894 // Compute the value of the PHIs for the next iteration. 7895 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7896 DenseMap<Instruction *, Constant *> NextIterVals; 7897 Constant *NextPHI = 7898 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7899 if (!NextPHI) 7900 return nullptr; // Couldn't evaluate! 7901 NextIterVals[PN] = NextPHI; 7902 7903 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7904 7905 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7906 // cease to be able to evaluate one of them or if they stop evolving, 7907 // because that doesn't necessarily prevent us from computing PN. 7908 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7909 for (const auto &I : CurrentIterVals) { 7910 PHINode *PHI = dyn_cast<PHINode>(I.first); 7911 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7912 PHIsToCompute.emplace_back(PHI, I.second); 7913 } 7914 // We use two distinct loops because EvaluateExpression may invalidate any 7915 // iterators into CurrentIterVals. 7916 for (const auto &I : PHIsToCompute) { 7917 PHINode *PHI = I.first; 7918 Constant *&NextPHI = NextIterVals[PHI]; 7919 if (!NextPHI) { // Not already computed. 7920 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7921 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7922 } 7923 if (NextPHI != I.second) 7924 StoppedEvolving = false; 7925 } 7926 7927 // If all entries in CurrentIterVals == NextIterVals then we can stop 7928 // iterating, the loop can't continue to change. 7929 if (StoppedEvolving) 7930 return RetVal = CurrentIterVals[PN]; 7931 7932 CurrentIterVals.swap(NextIterVals); 7933 } 7934 } 7935 7936 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7937 Value *Cond, 7938 bool ExitWhen) { 7939 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7940 if (!PN) return getCouldNotCompute(); 7941 7942 // If the loop is canonicalized, the PHI will have exactly two entries. 7943 // That's the only form we support here. 7944 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7945 7946 DenseMap<Instruction *, Constant *> CurrentIterVals; 7947 BasicBlock *Header = L->getHeader(); 7948 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7949 7950 BasicBlock *Latch = L->getLoopLatch(); 7951 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7952 7953 for (PHINode &PHI : Header->phis()) { 7954 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7955 CurrentIterVals[&PHI] = StartCST; 7956 } 7957 if (!CurrentIterVals.count(PN)) 7958 return getCouldNotCompute(); 7959 7960 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7961 // the loop symbolically to determine when the condition gets a value of 7962 // "ExitWhen". 7963 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7964 const DataLayout &DL = getDataLayout(); 7965 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7966 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7967 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7968 7969 // Couldn't symbolically evaluate. 7970 if (!CondVal) return getCouldNotCompute(); 7971 7972 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7973 ++NumBruteForceTripCountsComputed; 7974 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7975 } 7976 7977 // Update all the PHI nodes for the next iteration. 7978 DenseMap<Instruction *, Constant *> NextIterVals; 7979 7980 // Create a list of which PHIs we need to compute. We want to do this before 7981 // calling EvaluateExpression on them because that may invalidate iterators 7982 // into CurrentIterVals. 7983 SmallVector<PHINode *, 8> PHIsToCompute; 7984 for (const auto &I : CurrentIterVals) { 7985 PHINode *PHI = dyn_cast<PHINode>(I.first); 7986 if (!PHI || PHI->getParent() != Header) continue; 7987 PHIsToCompute.push_back(PHI); 7988 } 7989 for (PHINode *PHI : PHIsToCompute) { 7990 Constant *&NextPHI = NextIterVals[PHI]; 7991 if (NextPHI) continue; // Already computed! 7992 7993 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7994 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7995 } 7996 CurrentIterVals.swap(NextIterVals); 7997 } 7998 7999 // Too many iterations were needed to evaluate. 8000 return getCouldNotCompute(); 8001 } 8002 8003 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8004 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8005 ValuesAtScopes[V]; 8006 // Check to see if we've folded this expression at this loop before. 8007 for (auto &LS : Values) 8008 if (LS.first == L) 8009 return LS.second ? LS.second : V; 8010 8011 Values.emplace_back(L, nullptr); 8012 8013 // Otherwise compute it. 8014 const SCEV *C = computeSCEVAtScope(V, L); 8015 for (auto &LS : reverse(ValuesAtScopes[V])) 8016 if (LS.first == L) { 8017 LS.second = C; 8018 break; 8019 } 8020 return C; 8021 } 8022 8023 /// This builds up a Constant using the ConstantExpr interface. That way, we 8024 /// will return Constants for objects which aren't represented by a 8025 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8026 /// Returns NULL if the SCEV isn't representable as a Constant. 8027 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8028 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8029 case scCouldNotCompute: 8030 case scAddRecExpr: 8031 break; 8032 case scConstant: 8033 return cast<SCEVConstant>(V)->getValue(); 8034 case scUnknown: 8035 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8036 case scSignExtend: { 8037 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8038 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8039 return ConstantExpr::getSExt(CastOp, SS->getType()); 8040 break; 8041 } 8042 case scZeroExtend: { 8043 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8044 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8045 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8046 break; 8047 } 8048 case scTruncate: { 8049 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8050 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8051 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8052 break; 8053 } 8054 case scAddExpr: { 8055 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8056 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8057 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8058 unsigned AS = PTy->getAddressSpace(); 8059 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8060 C = ConstantExpr::getBitCast(C, DestPtrTy); 8061 } 8062 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8063 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8064 if (!C2) return nullptr; 8065 8066 // First pointer! 8067 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8068 unsigned AS = C2->getType()->getPointerAddressSpace(); 8069 std::swap(C, C2); 8070 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8071 // The offsets have been converted to bytes. We can add bytes to an 8072 // i8* by GEP with the byte count in the first index. 8073 C = ConstantExpr::getBitCast(C, DestPtrTy); 8074 } 8075 8076 // Don't bother trying to sum two pointers. We probably can't 8077 // statically compute a load that results from it anyway. 8078 if (C2->getType()->isPointerTy()) 8079 return nullptr; 8080 8081 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8082 if (PTy->getElementType()->isStructTy()) 8083 C2 = ConstantExpr::getIntegerCast( 8084 C2, Type::getInt32Ty(C->getContext()), true); 8085 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8086 } else 8087 C = ConstantExpr::getAdd(C, C2); 8088 } 8089 return C; 8090 } 8091 break; 8092 } 8093 case scMulExpr: { 8094 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8095 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8096 // Don't bother with pointers at all. 8097 if (C->getType()->isPointerTy()) return nullptr; 8098 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8099 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8100 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8101 C = ConstantExpr::getMul(C, C2); 8102 } 8103 return C; 8104 } 8105 break; 8106 } 8107 case scUDivExpr: { 8108 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8109 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8110 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8111 if (LHS->getType() == RHS->getType()) 8112 return ConstantExpr::getUDiv(LHS, RHS); 8113 break; 8114 } 8115 case scSMaxExpr: 8116 case scUMaxExpr: 8117 case scSMinExpr: 8118 case scUMinExpr: 8119 break; // TODO: smax, umax, smin, umax. 8120 } 8121 return nullptr; 8122 } 8123 8124 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8125 if (isa<SCEVConstant>(V)) return V; 8126 8127 // If this instruction is evolved from a constant-evolving PHI, compute the 8128 // exit value from the loop without using SCEVs. 8129 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8130 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8131 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8132 const Loop *LI = this->LI[I->getParent()]; 8133 // Looking for loop exit value. 8134 if (LI && LI->getParentLoop() == L && 8135 PN->getParent() == LI->getHeader()) { 8136 // Okay, there is no closed form solution for the PHI node. Check 8137 // to see if the loop that contains it has a known backedge-taken 8138 // count. If so, we may be able to force computation of the exit 8139 // value. 8140 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8141 // This trivial case can show up in some degenerate cases where 8142 // the incoming IR has not yet been fully simplified. 8143 if (BackedgeTakenCount->isZero()) { 8144 Value *InitValue = nullptr; 8145 bool MultipleInitValues = false; 8146 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8147 if (!LI->contains(PN->getIncomingBlock(i))) { 8148 if (!InitValue) 8149 InitValue = PN->getIncomingValue(i); 8150 else if (InitValue != PN->getIncomingValue(i)) { 8151 MultipleInitValues = true; 8152 break; 8153 } 8154 } 8155 } 8156 if (!MultipleInitValues && InitValue) 8157 return getSCEV(InitValue); 8158 } 8159 // Do we have a loop invariant value flowing around the backedge 8160 // for a loop which must execute the backedge? 8161 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8162 isKnownPositive(BackedgeTakenCount) && 8163 PN->getNumIncomingValues() == 2) { 8164 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8165 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8166 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8167 return OnBackedge; 8168 } 8169 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8170 // Okay, we know how many times the containing loop executes. If 8171 // this is a constant evolving PHI node, get the final value at 8172 // the specified iteration number. 8173 Constant *RV = 8174 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8175 if (RV) return getSCEV(RV); 8176 } 8177 } 8178 8179 // If there is a single-input Phi, evaluate it at our scope. If we can 8180 // prove that this replacement does not break LCSSA form, use new value. 8181 if (PN->getNumOperands() == 1) { 8182 const SCEV *Input = getSCEV(PN->getOperand(0)); 8183 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8184 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8185 // for the simplest case just support constants. 8186 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8187 } 8188 } 8189 8190 // Okay, this is an expression that we cannot symbolically evaluate 8191 // into a SCEV. Check to see if it's possible to symbolically evaluate 8192 // the arguments into constants, and if so, try to constant propagate the 8193 // result. This is particularly useful for computing loop exit values. 8194 if (CanConstantFold(I)) { 8195 SmallVector<Constant *, 4> Operands; 8196 bool MadeImprovement = false; 8197 for (Value *Op : I->operands()) { 8198 if (Constant *C = dyn_cast<Constant>(Op)) { 8199 Operands.push_back(C); 8200 continue; 8201 } 8202 8203 // If any of the operands is non-constant and if they are 8204 // non-integer and non-pointer, don't even try to analyze them 8205 // with scev techniques. 8206 if (!isSCEVable(Op->getType())) 8207 return V; 8208 8209 const SCEV *OrigV = getSCEV(Op); 8210 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8211 MadeImprovement |= OrigV != OpV; 8212 8213 Constant *C = BuildConstantFromSCEV(OpV); 8214 if (!C) return V; 8215 if (C->getType() != Op->getType()) 8216 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8217 Op->getType(), 8218 false), 8219 C, Op->getType()); 8220 Operands.push_back(C); 8221 } 8222 8223 // Check to see if getSCEVAtScope actually made an improvement. 8224 if (MadeImprovement) { 8225 Constant *C = nullptr; 8226 const DataLayout &DL = getDataLayout(); 8227 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8228 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8229 Operands[1], DL, &TLI); 8230 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8231 if (!LI->isVolatile()) 8232 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8233 } else 8234 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8235 if (!C) return V; 8236 return getSCEV(C); 8237 } 8238 } 8239 } 8240 8241 // This is some other type of SCEVUnknown, just return it. 8242 return V; 8243 } 8244 8245 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8246 // Avoid performing the look-up in the common case where the specified 8247 // expression has no loop-variant portions. 8248 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8249 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8250 if (OpAtScope != Comm->getOperand(i)) { 8251 // Okay, at least one of these operands is loop variant but might be 8252 // foldable. Build a new instance of the folded commutative expression. 8253 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8254 Comm->op_begin()+i); 8255 NewOps.push_back(OpAtScope); 8256 8257 for (++i; i != e; ++i) { 8258 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8259 NewOps.push_back(OpAtScope); 8260 } 8261 if (isa<SCEVAddExpr>(Comm)) 8262 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8263 if (isa<SCEVMulExpr>(Comm)) 8264 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8265 if (isa<SCEVMinMaxExpr>(Comm)) 8266 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8267 llvm_unreachable("Unknown commutative SCEV type!"); 8268 } 8269 } 8270 // If we got here, all operands are loop invariant. 8271 return Comm; 8272 } 8273 8274 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8275 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8276 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8277 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8278 return Div; // must be loop invariant 8279 return getUDivExpr(LHS, RHS); 8280 } 8281 8282 // If this is a loop recurrence for a loop that does not contain L, then we 8283 // are dealing with the final value computed by the loop. 8284 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8285 // First, attempt to evaluate each operand. 8286 // Avoid performing the look-up in the common case where the specified 8287 // expression has no loop-variant portions. 8288 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8289 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8290 if (OpAtScope == AddRec->getOperand(i)) 8291 continue; 8292 8293 // Okay, at least one of these operands is loop variant but might be 8294 // foldable. Build a new instance of the folded commutative expression. 8295 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8296 AddRec->op_begin()+i); 8297 NewOps.push_back(OpAtScope); 8298 for (++i; i != e; ++i) 8299 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8300 8301 const SCEV *FoldedRec = 8302 getAddRecExpr(NewOps, AddRec->getLoop(), 8303 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8304 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8305 // The addrec may be folded to a nonrecurrence, for example, if the 8306 // induction variable is multiplied by zero after constant folding. Go 8307 // ahead and return the folded value. 8308 if (!AddRec) 8309 return FoldedRec; 8310 break; 8311 } 8312 8313 // If the scope is outside the addrec's loop, evaluate it by using the 8314 // loop exit value of the addrec. 8315 if (!AddRec->getLoop()->contains(L)) { 8316 // To evaluate this recurrence, we need to know how many times the AddRec 8317 // loop iterates. Compute this now. 8318 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8319 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8320 8321 // Then, evaluate the AddRec. 8322 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8323 } 8324 8325 return AddRec; 8326 } 8327 8328 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8329 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8330 if (Op == Cast->getOperand()) 8331 return Cast; // must be loop invariant 8332 return getZeroExtendExpr(Op, Cast->getType()); 8333 } 8334 8335 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8336 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8337 if (Op == Cast->getOperand()) 8338 return Cast; // must be loop invariant 8339 return getSignExtendExpr(Op, Cast->getType()); 8340 } 8341 8342 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8343 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8344 if (Op == Cast->getOperand()) 8345 return Cast; // must be loop invariant 8346 return getTruncateExpr(Op, Cast->getType()); 8347 } 8348 8349 llvm_unreachable("Unknown SCEV type!"); 8350 } 8351 8352 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8353 return getSCEVAtScope(getSCEV(V), L); 8354 } 8355 8356 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8357 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8358 return stripInjectiveFunctions(ZExt->getOperand()); 8359 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8360 return stripInjectiveFunctions(SExt->getOperand()); 8361 return S; 8362 } 8363 8364 /// Finds the minimum unsigned root of the following equation: 8365 /// 8366 /// A * X = B (mod N) 8367 /// 8368 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8369 /// A and B isn't important. 8370 /// 8371 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8372 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8373 ScalarEvolution &SE) { 8374 uint32_t BW = A.getBitWidth(); 8375 assert(BW == SE.getTypeSizeInBits(B->getType())); 8376 assert(A != 0 && "A must be non-zero."); 8377 8378 // 1. D = gcd(A, N) 8379 // 8380 // The gcd of A and N may have only one prime factor: 2. The number of 8381 // trailing zeros in A is its multiplicity 8382 uint32_t Mult2 = A.countTrailingZeros(); 8383 // D = 2^Mult2 8384 8385 // 2. Check if B is divisible by D. 8386 // 8387 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8388 // is not less than multiplicity of this prime factor for D. 8389 if (SE.GetMinTrailingZeros(B) < Mult2) 8390 return SE.getCouldNotCompute(); 8391 8392 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8393 // modulo (N / D). 8394 // 8395 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8396 // (N / D) in general. The inverse itself always fits into BW bits, though, 8397 // so we immediately truncate it. 8398 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8399 APInt Mod(BW + 1, 0); 8400 Mod.setBit(BW - Mult2); // Mod = N / D 8401 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8402 8403 // 4. Compute the minimum unsigned root of the equation: 8404 // I * (B / D) mod (N / D) 8405 // To simplify the computation, we factor out the divide by D: 8406 // (I * B mod N) / D 8407 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8408 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8409 } 8410 8411 /// For a given quadratic addrec, generate coefficients of the corresponding 8412 /// quadratic equation, multiplied by a common value to ensure that they are 8413 /// integers. 8414 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8415 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8416 /// were multiplied by, and BitWidth is the bit width of the original addrec 8417 /// coefficients. 8418 /// This function returns None if the addrec coefficients are not compile- 8419 /// time constants. 8420 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8421 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8422 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8423 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8424 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8425 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8426 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8427 << *AddRec << '\n'); 8428 8429 // We currently can only solve this if the coefficients are constants. 8430 if (!LC || !MC || !NC) { 8431 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8432 return None; 8433 } 8434 8435 APInt L = LC->getAPInt(); 8436 APInt M = MC->getAPInt(); 8437 APInt N = NC->getAPInt(); 8438 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8439 8440 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8441 unsigned NewWidth = BitWidth + 1; 8442 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8443 << BitWidth << '\n'); 8444 // The sign-extension (as opposed to a zero-extension) here matches the 8445 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8446 N = N.sext(NewWidth); 8447 M = M.sext(NewWidth); 8448 L = L.sext(NewWidth); 8449 8450 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8451 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8452 // L+M, L+2M+N, L+3M+3N, ... 8453 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8454 // 8455 // The equation Acc = 0 is then 8456 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8457 // In a quadratic form it becomes: 8458 // N n^2 + (2M-N) n + 2L = 0. 8459 8460 APInt A = N; 8461 APInt B = 2 * M - A; 8462 APInt C = 2 * L; 8463 APInt T = APInt(NewWidth, 2); 8464 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8465 << "x + " << C << ", coeff bw: " << NewWidth 8466 << ", multiplied by " << T << '\n'); 8467 return std::make_tuple(A, B, C, T, BitWidth); 8468 } 8469 8470 /// Helper function to compare optional APInts: 8471 /// (a) if X and Y both exist, return min(X, Y), 8472 /// (b) if neither X nor Y exist, return None, 8473 /// (c) if exactly one of X and Y exists, return that value. 8474 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8475 if (X.hasValue() && Y.hasValue()) { 8476 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8477 APInt XW = X->sextOrSelf(W); 8478 APInt YW = Y->sextOrSelf(W); 8479 return XW.slt(YW) ? *X : *Y; 8480 } 8481 if (!X.hasValue() && !Y.hasValue()) 8482 return None; 8483 return X.hasValue() ? *X : *Y; 8484 } 8485 8486 /// Helper function to truncate an optional APInt to a given BitWidth. 8487 /// When solving addrec-related equations, it is preferable to return a value 8488 /// that has the same bit width as the original addrec's coefficients. If the 8489 /// solution fits in the original bit width, truncate it (except for i1). 8490 /// Returning a value of a different bit width may inhibit some optimizations. 8491 /// 8492 /// In general, a solution to a quadratic equation generated from an addrec 8493 /// may require BW+1 bits, where BW is the bit width of the addrec's 8494 /// coefficients. The reason is that the coefficients of the quadratic 8495 /// equation are BW+1 bits wide (to avoid truncation when converting from 8496 /// the addrec to the equation). 8497 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8498 if (!X.hasValue()) 8499 return None; 8500 unsigned W = X->getBitWidth(); 8501 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8502 return X->trunc(BitWidth); 8503 return X; 8504 } 8505 8506 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8507 /// iterations. The values L, M, N are assumed to be signed, and they 8508 /// should all have the same bit widths. 8509 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8510 /// where BW is the bit width of the addrec's coefficients. 8511 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8512 /// returned as such, otherwise the bit width of the returned value may 8513 /// be greater than BW. 8514 /// 8515 /// This function returns None if 8516 /// (a) the addrec coefficients are not constant, or 8517 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8518 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8519 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8520 static Optional<APInt> 8521 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8522 APInt A, B, C, M; 8523 unsigned BitWidth; 8524 auto T = GetQuadraticEquation(AddRec); 8525 if (!T.hasValue()) 8526 return None; 8527 8528 std::tie(A, B, C, M, BitWidth) = *T; 8529 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8530 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8531 if (!X.hasValue()) 8532 return None; 8533 8534 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8535 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8536 if (!V->isZero()) 8537 return None; 8538 8539 return TruncIfPossible(X, BitWidth); 8540 } 8541 8542 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8543 /// iterations. The values M, N are assumed to be signed, and they 8544 /// should all have the same bit widths. 8545 /// Find the least n such that c(n) does not belong to the given range, 8546 /// while c(n-1) does. 8547 /// 8548 /// This function returns None if 8549 /// (a) the addrec coefficients are not constant, or 8550 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8551 /// bounds of the range. 8552 static Optional<APInt> 8553 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8554 const ConstantRange &Range, ScalarEvolution &SE) { 8555 assert(AddRec->getOperand(0)->isZero() && 8556 "Starting value of addrec should be 0"); 8557 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8558 << Range << ", addrec " << *AddRec << '\n'); 8559 // This case is handled in getNumIterationsInRange. Here we can assume that 8560 // we start in the range. 8561 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8562 "Addrec's initial value should be in range"); 8563 8564 APInt A, B, C, M; 8565 unsigned BitWidth; 8566 auto T = GetQuadraticEquation(AddRec); 8567 if (!T.hasValue()) 8568 return None; 8569 8570 // Be careful about the return value: there can be two reasons for not 8571 // returning an actual number. First, if no solutions to the equations 8572 // were found, and second, if the solutions don't leave the given range. 8573 // The first case means that the actual solution is "unknown", the second 8574 // means that it's known, but not valid. If the solution is unknown, we 8575 // cannot make any conclusions. 8576 // Return a pair: the optional solution and a flag indicating if the 8577 // solution was found. 8578 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8579 // Solve for signed overflow and unsigned overflow, pick the lower 8580 // solution. 8581 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8582 << Bound << " (before multiplying by " << M << ")\n"); 8583 Bound *= M; // The quadratic equation multiplier. 8584 8585 Optional<APInt> SO = None; 8586 if (BitWidth > 1) { 8587 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8588 "signed overflow\n"); 8589 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8590 } 8591 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8592 "unsigned overflow\n"); 8593 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8594 BitWidth+1); 8595 8596 auto LeavesRange = [&] (const APInt &X) { 8597 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8598 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8599 if (Range.contains(V0->getValue())) 8600 return false; 8601 // X should be at least 1, so X-1 is non-negative. 8602 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8603 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8604 if (Range.contains(V1->getValue())) 8605 return true; 8606 return false; 8607 }; 8608 8609 // If SolveQuadraticEquationWrap returns None, it means that there can 8610 // be a solution, but the function failed to find it. We cannot treat it 8611 // as "no solution". 8612 if (!SO.hasValue() || !UO.hasValue()) 8613 return { None, false }; 8614 8615 // Check the smaller value first to see if it leaves the range. 8616 // At this point, both SO and UO must have values. 8617 Optional<APInt> Min = MinOptional(SO, UO); 8618 if (LeavesRange(*Min)) 8619 return { Min, true }; 8620 Optional<APInt> Max = Min == SO ? UO : SO; 8621 if (LeavesRange(*Max)) 8622 return { Max, true }; 8623 8624 // Solutions were found, but were eliminated, hence the "true". 8625 return { None, true }; 8626 }; 8627 8628 std::tie(A, B, C, M, BitWidth) = *T; 8629 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8630 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8631 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8632 auto SL = SolveForBoundary(Lower); 8633 auto SU = SolveForBoundary(Upper); 8634 // If any of the solutions was unknown, no meaninigful conclusions can 8635 // be made. 8636 if (!SL.second || !SU.second) 8637 return None; 8638 8639 // Claim: The correct solution is not some value between Min and Max. 8640 // 8641 // Justification: Assuming that Min and Max are different values, one of 8642 // them is when the first signed overflow happens, the other is when the 8643 // first unsigned overflow happens. Crossing the range boundary is only 8644 // possible via an overflow (treating 0 as a special case of it, modeling 8645 // an overflow as crossing k*2^W for some k). 8646 // 8647 // The interesting case here is when Min was eliminated as an invalid 8648 // solution, but Max was not. The argument is that if there was another 8649 // overflow between Min and Max, it would also have been eliminated if 8650 // it was considered. 8651 // 8652 // For a given boundary, it is possible to have two overflows of the same 8653 // type (signed/unsigned) without having the other type in between: this 8654 // can happen when the vertex of the parabola is between the iterations 8655 // corresponding to the overflows. This is only possible when the two 8656 // overflows cross k*2^W for the same k. In such case, if the second one 8657 // left the range (and was the first one to do so), the first overflow 8658 // would have to enter the range, which would mean that either we had left 8659 // the range before or that we started outside of it. Both of these cases 8660 // are contradictions. 8661 // 8662 // Claim: In the case where SolveForBoundary returns None, the correct 8663 // solution is not some value between the Max for this boundary and the 8664 // Min of the other boundary. 8665 // 8666 // Justification: Assume that we had such Max_A and Min_B corresponding 8667 // to range boundaries A and B and such that Max_A < Min_B. If there was 8668 // a solution between Max_A and Min_B, it would have to be caused by an 8669 // overflow corresponding to either A or B. It cannot correspond to B, 8670 // since Min_B is the first occurrence of such an overflow. If it 8671 // corresponded to A, it would have to be either a signed or an unsigned 8672 // overflow that is larger than both eliminated overflows for A. But 8673 // between the eliminated overflows and this overflow, the values would 8674 // cover the entire value space, thus crossing the other boundary, which 8675 // is a contradiction. 8676 8677 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8678 } 8679 8680 ScalarEvolution::ExitLimit 8681 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8682 bool AllowPredicates) { 8683 8684 // This is only used for loops with a "x != y" exit test. The exit condition 8685 // is now expressed as a single expression, V = x-y. So the exit test is 8686 // effectively V != 0. We know and take advantage of the fact that this 8687 // expression only being used in a comparison by zero context. 8688 8689 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8690 // If the value is a constant 8691 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8692 // If the value is already zero, the branch will execute zero times. 8693 if (C->getValue()->isZero()) return C; 8694 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8695 } 8696 8697 const SCEVAddRecExpr *AddRec = 8698 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8699 8700 if (!AddRec && AllowPredicates) 8701 // Try to make this an AddRec using runtime tests, in the first X 8702 // iterations of this loop, where X is the SCEV expression found by the 8703 // algorithm below. 8704 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8705 8706 if (!AddRec || AddRec->getLoop() != L) 8707 return getCouldNotCompute(); 8708 8709 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8710 // the quadratic equation to solve it. 8711 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8712 // We can only use this value if the chrec ends up with an exact zero 8713 // value at this index. When solving for "X*X != 5", for example, we 8714 // should not accept a root of 2. 8715 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8716 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8717 return ExitLimit(R, R, false, Predicates); 8718 } 8719 return getCouldNotCompute(); 8720 } 8721 8722 // Otherwise we can only handle this if it is affine. 8723 if (!AddRec->isAffine()) 8724 return getCouldNotCompute(); 8725 8726 // If this is an affine expression, the execution count of this branch is 8727 // the minimum unsigned root of the following equation: 8728 // 8729 // Start + Step*N = 0 (mod 2^BW) 8730 // 8731 // equivalent to: 8732 // 8733 // Step*N = -Start (mod 2^BW) 8734 // 8735 // where BW is the common bit width of Start and Step. 8736 8737 // Get the initial value for the loop. 8738 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8739 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8740 8741 // For now we handle only constant steps. 8742 // 8743 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8744 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8745 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8746 // We have not yet seen any such cases. 8747 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8748 if (!StepC || StepC->getValue()->isZero()) 8749 return getCouldNotCompute(); 8750 8751 // For positive steps (counting up until unsigned overflow): 8752 // N = -Start/Step (as unsigned) 8753 // For negative steps (counting down to zero): 8754 // N = Start/-Step 8755 // First compute the unsigned distance from zero in the direction of Step. 8756 bool CountDown = StepC->getAPInt().isNegative(); 8757 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8758 8759 // Handle unitary steps, which cannot wraparound. 8760 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8761 // N = Distance (as unsigned) 8762 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8763 APInt MaxBECount = getUnsignedRangeMax(Distance); 8764 8765 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8766 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8767 // case, and see if we can improve the bound. 8768 // 8769 // Explicitly handling this here is necessary because getUnsignedRange 8770 // isn't context-sensitive; it doesn't know that we only care about the 8771 // range inside the loop. 8772 const SCEV *Zero = getZero(Distance->getType()); 8773 const SCEV *One = getOne(Distance->getType()); 8774 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8775 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8776 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8777 // as "unsigned_max(Distance + 1) - 1". 8778 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8779 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8780 } 8781 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8782 } 8783 8784 // If the condition controls loop exit (the loop exits only if the expression 8785 // is true) and the addition is no-wrap we can use unsigned divide to 8786 // compute the backedge count. In this case, the step may not divide the 8787 // distance, but we don't care because if the condition is "missed" the loop 8788 // will have undefined behavior due to wrapping. 8789 if (ControlsExit && AddRec->hasNoSelfWrap() && 8790 loopHasNoAbnormalExits(AddRec->getLoop())) { 8791 const SCEV *Exact = 8792 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8793 const SCEV *Max = 8794 Exact == getCouldNotCompute() 8795 ? Exact 8796 : getConstant(getUnsignedRangeMax(Exact)); 8797 return ExitLimit(Exact, Max, false, Predicates); 8798 } 8799 8800 // Solve the general equation. 8801 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8802 getNegativeSCEV(Start), *this); 8803 const SCEV *M = E == getCouldNotCompute() 8804 ? E 8805 : getConstant(getUnsignedRangeMax(E)); 8806 return ExitLimit(E, M, false, Predicates); 8807 } 8808 8809 ScalarEvolution::ExitLimit 8810 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8811 // Loops that look like: while (X == 0) are very strange indeed. We don't 8812 // handle them yet except for the trivial case. This could be expanded in the 8813 // future as needed. 8814 8815 // If the value is a constant, check to see if it is known to be non-zero 8816 // already. If so, the backedge will execute zero times. 8817 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8818 if (!C->getValue()->isZero()) 8819 return getZero(C->getType()); 8820 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8821 } 8822 8823 // We could implement others, but I really doubt anyone writes loops like 8824 // this, and if they did, they would already be constant folded. 8825 return getCouldNotCompute(); 8826 } 8827 8828 std::pair<BasicBlock *, BasicBlock *> 8829 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8830 // If the block has a unique predecessor, then there is no path from the 8831 // predecessor to the block that does not go through the direct edge 8832 // from the predecessor to the block. 8833 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8834 return {Pred, BB}; 8835 8836 // A loop's header is defined to be a block that dominates the loop. 8837 // If the header has a unique predecessor outside the loop, it must be 8838 // a block that has exactly one successor that can reach the loop. 8839 if (Loop *L = LI.getLoopFor(BB)) 8840 return {L->getLoopPredecessor(), L->getHeader()}; 8841 8842 return {nullptr, nullptr}; 8843 } 8844 8845 /// SCEV structural equivalence is usually sufficient for testing whether two 8846 /// expressions are equal, however for the purposes of looking for a condition 8847 /// guarding a loop, it can be useful to be a little more general, since a 8848 /// front-end may have replicated the controlling expression. 8849 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8850 // Quick check to see if they are the same SCEV. 8851 if (A == B) return true; 8852 8853 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8854 // Not all instructions that are "identical" compute the same value. For 8855 // instance, two distinct alloca instructions allocating the same type are 8856 // identical and do not read memory; but compute distinct values. 8857 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8858 }; 8859 8860 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8861 // two different instructions with the same value. Check for this case. 8862 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8863 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8864 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8865 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8866 if (ComputesEqualValues(AI, BI)) 8867 return true; 8868 8869 // Otherwise assume they may have a different value. 8870 return false; 8871 } 8872 8873 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8874 const SCEV *&LHS, const SCEV *&RHS, 8875 unsigned Depth) { 8876 bool Changed = false; 8877 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8878 // '0 != 0'. 8879 auto TrivialCase = [&](bool TriviallyTrue) { 8880 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8881 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8882 return true; 8883 }; 8884 // If we hit the max recursion limit bail out. 8885 if (Depth >= 3) 8886 return false; 8887 8888 // Canonicalize a constant to the right side. 8889 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8890 // Check for both operands constant. 8891 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8892 if (ConstantExpr::getICmp(Pred, 8893 LHSC->getValue(), 8894 RHSC->getValue())->isNullValue()) 8895 return TrivialCase(false); 8896 else 8897 return TrivialCase(true); 8898 } 8899 // Otherwise swap the operands to put the constant on the right. 8900 std::swap(LHS, RHS); 8901 Pred = ICmpInst::getSwappedPredicate(Pred); 8902 Changed = true; 8903 } 8904 8905 // If we're comparing an addrec with a value which is loop-invariant in the 8906 // addrec's loop, put the addrec on the left. Also make a dominance check, 8907 // as both operands could be addrecs loop-invariant in each other's loop. 8908 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8909 const Loop *L = AR->getLoop(); 8910 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8911 std::swap(LHS, RHS); 8912 Pred = ICmpInst::getSwappedPredicate(Pred); 8913 Changed = true; 8914 } 8915 } 8916 8917 // If there's a constant operand, canonicalize comparisons with boundary 8918 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8919 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8920 const APInt &RA = RC->getAPInt(); 8921 8922 bool SimplifiedByConstantRange = false; 8923 8924 if (!ICmpInst::isEquality(Pred)) { 8925 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8926 if (ExactCR.isFullSet()) 8927 return TrivialCase(true); 8928 else if (ExactCR.isEmptySet()) 8929 return TrivialCase(false); 8930 8931 APInt NewRHS; 8932 CmpInst::Predicate NewPred; 8933 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8934 ICmpInst::isEquality(NewPred)) { 8935 // We were able to convert an inequality to an equality. 8936 Pred = NewPred; 8937 RHS = getConstant(NewRHS); 8938 Changed = SimplifiedByConstantRange = true; 8939 } 8940 } 8941 8942 if (!SimplifiedByConstantRange) { 8943 switch (Pred) { 8944 default: 8945 break; 8946 case ICmpInst::ICMP_EQ: 8947 case ICmpInst::ICMP_NE: 8948 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8949 if (!RA) 8950 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8951 if (const SCEVMulExpr *ME = 8952 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8953 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8954 ME->getOperand(0)->isAllOnesValue()) { 8955 RHS = AE->getOperand(1); 8956 LHS = ME->getOperand(1); 8957 Changed = true; 8958 } 8959 break; 8960 8961 8962 // The "Should have been caught earlier!" messages refer to the fact 8963 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8964 // should have fired on the corresponding cases, and canonicalized the 8965 // check to trivial case. 8966 8967 case ICmpInst::ICMP_UGE: 8968 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8969 Pred = ICmpInst::ICMP_UGT; 8970 RHS = getConstant(RA - 1); 8971 Changed = true; 8972 break; 8973 case ICmpInst::ICMP_ULE: 8974 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8975 Pred = ICmpInst::ICMP_ULT; 8976 RHS = getConstant(RA + 1); 8977 Changed = true; 8978 break; 8979 case ICmpInst::ICMP_SGE: 8980 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8981 Pred = ICmpInst::ICMP_SGT; 8982 RHS = getConstant(RA - 1); 8983 Changed = true; 8984 break; 8985 case ICmpInst::ICMP_SLE: 8986 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8987 Pred = ICmpInst::ICMP_SLT; 8988 RHS = getConstant(RA + 1); 8989 Changed = true; 8990 break; 8991 } 8992 } 8993 } 8994 8995 // Check for obvious equality. 8996 if (HasSameValue(LHS, RHS)) { 8997 if (ICmpInst::isTrueWhenEqual(Pred)) 8998 return TrivialCase(true); 8999 if (ICmpInst::isFalseWhenEqual(Pred)) 9000 return TrivialCase(false); 9001 } 9002 9003 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9004 // adding or subtracting 1 from one of the operands. 9005 switch (Pred) { 9006 case ICmpInst::ICMP_SLE: 9007 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9008 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9009 SCEV::FlagNSW); 9010 Pred = ICmpInst::ICMP_SLT; 9011 Changed = true; 9012 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9013 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9014 SCEV::FlagNSW); 9015 Pred = ICmpInst::ICMP_SLT; 9016 Changed = true; 9017 } 9018 break; 9019 case ICmpInst::ICMP_SGE: 9020 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9021 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9022 SCEV::FlagNSW); 9023 Pred = ICmpInst::ICMP_SGT; 9024 Changed = true; 9025 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9026 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9027 SCEV::FlagNSW); 9028 Pred = ICmpInst::ICMP_SGT; 9029 Changed = true; 9030 } 9031 break; 9032 case ICmpInst::ICMP_ULE: 9033 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9034 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9035 SCEV::FlagNUW); 9036 Pred = ICmpInst::ICMP_ULT; 9037 Changed = true; 9038 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9039 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9040 Pred = ICmpInst::ICMP_ULT; 9041 Changed = true; 9042 } 9043 break; 9044 case ICmpInst::ICMP_UGE: 9045 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9046 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9047 Pred = ICmpInst::ICMP_UGT; 9048 Changed = true; 9049 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9050 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9051 SCEV::FlagNUW); 9052 Pred = ICmpInst::ICMP_UGT; 9053 Changed = true; 9054 } 9055 break; 9056 default: 9057 break; 9058 } 9059 9060 // TODO: More simplifications are possible here. 9061 9062 // Recursively simplify until we either hit a recursion limit or nothing 9063 // changes. 9064 if (Changed) 9065 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9066 9067 return Changed; 9068 } 9069 9070 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9071 return getSignedRangeMax(S).isNegative(); 9072 } 9073 9074 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9075 return getSignedRangeMin(S).isStrictlyPositive(); 9076 } 9077 9078 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9079 return !getSignedRangeMin(S).isNegative(); 9080 } 9081 9082 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9083 return !getSignedRangeMax(S).isStrictlyPositive(); 9084 } 9085 9086 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9087 return isKnownNegative(S) || isKnownPositive(S); 9088 } 9089 9090 std::pair<const SCEV *, const SCEV *> 9091 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9092 // Compute SCEV on entry of loop L. 9093 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9094 if (Start == getCouldNotCompute()) 9095 return { Start, Start }; 9096 // Compute post increment SCEV for loop L. 9097 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9098 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9099 return { Start, PostInc }; 9100 } 9101 9102 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9103 const SCEV *LHS, const SCEV *RHS) { 9104 // First collect all loops. 9105 SmallPtrSet<const Loop *, 8> LoopsUsed; 9106 getUsedLoops(LHS, LoopsUsed); 9107 getUsedLoops(RHS, LoopsUsed); 9108 9109 if (LoopsUsed.empty()) 9110 return false; 9111 9112 // Domination relationship must be a linear order on collected loops. 9113 #ifndef NDEBUG 9114 for (auto *L1 : LoopsUsed) 9115 for (auto *L2 : LoopsUsed) 9116 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9117 DT.dominates(L2->getHeader(), L1->getHeader())) && 9118 "Domination relationship is not a linear order"); 9119 #endif 9120 9121 const Loop *MDL = 9122 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9123 [&](const Loop *L1, const Loop *L2) { 9124 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9125 }); 9126 9127 // Get init and post increment value for LHS. 9128 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9129 // if LHS contains unknown non-invariant SCEV then bail out. 9130 if (SplitLHS.first == getCouldNotCompute()) 9131 return false; 9132 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9133 // Get init and post increment value for RHS. 9134 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9135 // if RHS contains unknown non-invariant SCEV then bail out. 9136 if (SplitRHS.first == getCouldNotCompute()) 9137 return false; 9138 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9139 // It is possible that init SCEV contains an invariant load but it does 9140 // not dominate MDL and is not available at MDL loop entry, so we should 9141 // check it here. 9142 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9143 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9144 return false; 9145 9146 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9147 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9148 SplitRHS.second); 9149 } 9150 9151 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9152 const SCEV *LHS, const SCEV *RHS) { 9153 // Canonicalize the inputs first. 9154 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9155 9156 if (isKnownViaInduction(Pred, LHS, RHS)) 9157 return true; 9158 9159 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9160 return true; 9161 9162 // Otherwise see what can be done with some simple reasoning. 9163 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9164 } 9165 9166 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9167 const SCEVAddRecExpr *LHS, 9168 const SCEV *RHS) { 9169 const Loop *L = LHS->getLoop(); 9170 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9171 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9172 } 9173 9174 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9175 ICmpInst::Predicate Pred, 9176 bool &Increasing) { 9177 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9178 9179 #ifndef NDEBUG 9180 // Verify an invariant: inverting the predicate should turn a monotonically 9181 // increasing change to a monotonically decreasing one, and vice versa. 9182 bool IncreasingSwapped; 9183 bool ResultSwapped = isMonotonicPredicateImpl( 9184 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9185 9186 assert(Result == ResultSwapped && "should be able to analyze both!"); 9187 if (ResultSwapped) 9188 assert(Increasing == !IncreasingSwapped && 9189 "monotonicity should flip as we flip the predicate"); 9190 #endif 9191 9192 return Result; 9193 } 9194 9195 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9196 ICmpInst::Predicate Pred, 9197 bool &Increasing) { 9198 9199 // A zero step value for LHS means the induction variable is essentially a 9200 // loop invariant value. We don't really depend on the predicate actually 9201 // flipping from false to true (for increasing predicates, and the other way 9202 // around for decreasing predicates), all we care about is that *if* the 9203 // predicate changes then it only changes from false to true. 9204 // 9205 // A zero step value in itself is not very useful, but there may be places 9206 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9207 // as general as possible. 9208 9209 switch (Pred) { 9210 default: 9211 return false; // Conservative answer 9212 9213 case ICmpInst::ICMP_UGT: 9214 case ICmpInst::ICMP_UGE: 9215 case ICmpInst::ICMP_ULT: 9216 case ICmpInst::ICMP_ULE: 9217 if (!LHS->hasNoUnsignedWrap()) 9218 return false; 9219 9220 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9221 return true; 9222 9223 case ICmpInst::ICMP_SGT: 9224 case ICmpInst::ICMP_SGE: 9225 case ICmpInst::ICMP_SLT: 9226 case ICmpInst::ICMP_SLE: { 9227 if (!LHS->hasNoSignedWrap()) 9228 return false; 9229 9230 const SCEV *Step = LHS->getStepRecurrence(*this); 9231 9232 if (isKnownNonNegative(Step)) { 9233 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9234 return true; 9235 } 9236 9237 if (isKnownNonPositive(Step)) { 9238 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9239 return true; 9240 } 9241 9242 return false; 9243 } 9244 9245 } 9246 9247 llvm_unreachable("switch has default clause!"); 9248 } 9249 9250 bool ScalarEvolution::isLoopInvariantPredicate( 9251 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9252 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9253 const SCEV *&InvariantRHS) { 9254 9255 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9256 if (!isLoopInvariant(RHS, L)) { 9257 if (!isLoopInvariant(LHS, L)) 9258 return false; 9259 9260 std::swap(LHS, RHS); 9261 Pred = ICmpInst::getSwappedPredicate(Pred); 9262 } 9263 9264 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9265 if (!ArLHS || ArLHS->getLoop() != L) 9266 return false; 9267 9268 bool Increasing; 9269 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9270 return false; 9271 9272 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9273 // true as the loop iterates, and the backedge is control dependent on 9274 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9275 // 9276 // * if the predicate was false in the first iteration then the predicate 9277 // is never evaluated again, since the loop exits without taking the 9278 // backedge. 9279 // * if the predicate was true in the first iteration then it will 9280 // continue to be true for all future iterations since it is 9281 // monotonically increasing. 9282 // 9283 // For both the above possibilities, we can replace the loop varying 9284 // predicate with its value on the first iteration of the loop (which is 9285 // loop invariant). 9286 // 9287 // A similar reasoning applies for a monotonically decreasing predicate, by 9288 // replacing true with false and false with true in the above two bullets. 9289 9290 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9291 9292 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9293 return false; 9294 9295 InvariantPred = Pred; 9296 InvariantLHS = ArLHS->getStart(); 9297 InvariantRHS = RHS; 9298 return true; 9299 } 9300 9301 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9302 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9303 if (HasSameValue(LHS, RHS)) 9304 return ICmpInst::isTrueWhenEqual(Pred); 9305 9306 // This code is split out from isKnownPredicate because it is called from 9307 // within isLoopEntryGuardedByCond. 9308 9309 auto CheckRanges = 9310 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9311 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9312 .contains(RangeLHS); 9313 }; 9314 9315 // The check at the top of the function catches the case where the values are 9316 // known to be equal. 9317 if (Pred == CmpInst::ICMP_EQ) 9318 return false; 9319 9320 if (Pred == CmpInst::ICMP_NE) 9321 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9322 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9323 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9324 9325 if (CmpInst::isSigned(Pred)) 9326 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9327 9328 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9329 } 9330 9331 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9332 const SCEV *LHS, 9333 const SCEV *RHS) { 9334 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9335 // Return Y via OutY. 9336 auto MatchBinaryAddToConst = 9337 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9338 SCEV::NoWrapFlags ExpectedFlags) { 9339 const SCEV *NonConstOp, *ConstOp; 9340 SCEV::NoWrapFlags FlagsPresent; 9341 9342 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9343 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9344 return false; 9345 9346 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9347 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9348 }; 9349 9350 APInt C; 9351 9352 switch (Pred) { 9353 default: 9354 break; 9355 9356 case ICmpInst::ICMP_SGE: 9357 std::swap(LHS, RHS); 9358 LLVM_FALLTHROUGH; 9359 case ICmpInst::ICMP_SLE: 9360 // X s<= (X + C)<nsw> if C >= 0 9361 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9362 return true; 9363 9364 // (X + C)<nsw> s<= X if C <= 0 9365 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9366 !C.isStrictlyPositive()) 9367 return true; 9368 break; 9369 9370 case ICmpInst::ICMP_SGT: 9371 std::swap(LHS, RHS); 9372 LLVM_FALLTHROUGH; 9373 case ICmpInst::ICMP_SLT: 9374 // X s< (X + C)<nsw> if C > 0 9375 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9376 C.isStrictlyPositive()) 9377 return true; 9378 9379 // (X + C)<nsw> s< X if C < 0 9380 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9381 return true; 9382 break; 9383 } 9384 9385 return false; 9386 } 9387 9388 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9389 const SCEV *LHS, 9390 const SCEV *RHS) { 9391 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9392 return false; 9393 9394 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9395 // the stack can result in exponential time complexity. 9396 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9397 9398 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9399 // 9400 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9401 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9402 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9403 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9404 // use isKnownPredicate later if needed. 9405 return isKnownNonNegative(RHS) && 9406 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9407 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9408 } 9409 9410 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9411 ICmpInst::Predicate Pred, 9412 const SCEV *LHS, const SCEV *RHS) { 9413 // No need to even try if we know the module has no guards. 9414 if (!HasGuards) 9415 return false; 9416 9417 return any_of(*BB, [&](Instruction &I) { 9418 using namespace llvm::PatternMatch; 9419 9420 Value *Condition; 9421 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9422 m_Value(Condition))) && 9423 isImpliedCond(Pred, LHS, RHS, Condition, false); 9424 }); 9425 } 9426 9427 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9428 /// protected by a conditional between LHS and RHS. This is used to 9429 /// to eliminate casts. 9430 bool 9431 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9432 ICmpInst::Predicate Pred, 9433 const SCEV *LHS, const SCEV *RHS) { 9434 // Interpret a null as meaning no loop, where there is obviously no guard 9435 // (interprocedural conditions notwithstanding). 9436 if (!L) return true; 9437 9438 if (VerifyIR) 9439 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9440 "This cannot be done on broken IR!"); 9441 9442 9443 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9444 return true; 9445 9446 BasicBlock *Latch = L->getLoopLatch(); 9447 if (!Latch) 9448 return false; 9449 9450 BranchInst *LoopContinuePredicate = 9451 dyn_cast<BranchInst>(Latch->getTerminator()); 9452 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9453 isImpliedCond(Pred, LHS, RHS, 9454 LoopContinuePredicate->getCondition(), 9455 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9456 return true; 9457 9458 // We don't want more than one activation of the following loops on the stack 9459 // -- that can lead to O(n!) time complexity. 9460 if (WalkingBEDominatingConds) 9461 return false; 9462 9463 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9464 9465 // See if we can exploit a trip count to prove the predicate. 9466 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9467 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9468 if (LatchBECount != getCouldNotCompute()) { 9469 // We know that Latch branches back to the loop header exactly 9470 // LatchBECount times. This means the backdege condition at Latch is 9471 // equivalent to "{0,+,1} u< LatchBECount". 9472 Type *Ty = LatchBECount->getType(); 9473 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9474 const SCEV *LoopCounter = 9475 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9476 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9477 LatchBECount)) 9478 return true; 9479 } 9480 9481 // Check conditions due to any @llvm.assume intrinsics. 9482 for (auto &AssumeVH : AC.assumptions()) { 9483 if (!AssumeVH) 9484 continue; 9485 auto *CI = cast<CallInst>(AssumeVH); 9486 if (!DT.dominates(CI, Latch->getTerminator())) 9487 continue; 9488 9489 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9490 return true; 9491 } 9492 9493 // If the loop is not reachable from the entry block, we risk running into an 9494 // infinite loop as we walk up into the dom tree. These loops do not matter 9495 // anyway, so we just return a conservative answer when we see them. 9496 if (!DT.isReachableFromEntry(L->getHeader())) 9497 return false; 9498 9499 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9500 return true; 9501 9502 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9503 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9504 assert(DTN && "should reach the loop header before reaching the root!"); 9505 9506 BasicBlock *BB = DTN->getBlock(); 9507 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9508 return true; 9509 9510 BasicBlock *PBB = BB->getSinglePredecessor(); 9511 if (!PBB) 9512 continue; 9513 9514 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9515 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9516 continue; 9517 9518 Value *Condition = ContinuePredicate->getCondition(); 9519 9520 // If we have an edge `E` within the loop body that dominates the only 9521 // latch, the condition guarding `E` also guards the backedge. This 9522 // reasoning works only for loops with a single latch. 9523 9524 BasicBlockEdge DominatingEdge(PBB, BB); 9525 if (DominatingEdge.isSingleEdge()) { 9526 // We're constructively (and conservatively) enumerating edges within the 9527 // loop body that dominate the latch. The dominator tree better agree 9528 // with us on this: 9529 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9530 9531 if (isImpliedCond(Pred, LHS, RHS, Condition, 9532 BB != ContinuePredicate->getSuccessor(0))) 9533 return true; 9534 } 9535 } 9536 9537 return false; 9538 } 9539 9540 bool 9541 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9542 ICmpInst::Predicate Pred, 9543 const SCEV *LHS, const SCEV *RHS) { 9544 // Interpret a null as meaning no loop, where there is obviously no guard 9545 // (interprocedural conditions notwithstanding). 9546 if (!L) return false; 9547 9548 if (VerifyIR) 9549 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9550 "This cannot be done on broken IR!"); 9551 9552 // Both LHS and RHS must be available at loop entry. 9553 assert(isAvailableAtLoopEntry(LHS, L) && 9554 "LHS is not available at Loop Entry"); 9555 assert(isAvailableAtLoopEntry(RHS, L) && 9556 "RHS is not available at Loop Entry"); 9557 9558 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9559 return true; 9560 9561 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9562 // the facts (a >= b && a != b) separately. A typical situation is when the 9563 // non-strict comparison is known from ranges and non-equality is known from 9564 // dominating predicates. If we are proving strict comparison, we always try 9565 // to prove non-equality and non-strict comparison separately. 9566 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9567 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9568 bool ProvedNonStrictComparison = false; 9569 bool ProvedNonEquality = false; 9570 9571 if (ProvingStrictComparison) { 9572 ProvedNonStrictComparison = 9573 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9574 ProvedNonEquality = 9575 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9576 if (ProvedNonStrictComparison && ProvedNonEquality) 9577 return true; 9578 } 9579 9580 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9581 auto ProveViaGuard = [&](BasicBlock *Block) { 9582 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9583 return true; 9584 if (ProvingStrictComparison) { 9585 if (!ProvedNonStrictComparison) 9586 ProvedNonStrictComparison = 9587 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9588 if (!ProvedNonEquality) 9589 ProvedNonEquality = 9590 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9591 if (ProvedNonStrictComparison && ProvedNonEquality) 9592 return true; 9593 } 9594 return false; 9595 }; 9596 9597 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9598 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9599 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9600 return true; 9601 if (ProvingStrictComparison) { 9602 if (!ProvedNonStrictComparison) 9603 ProvedNonStrictComparison = 9604 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9605 if (!ProvedNonEquality) 9606 ProvedNonEquality = 9607 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9608 if (ProvedNonStrictComparison && ProvedNonEquality) 9609 return true; 9610 } 9611 return false; 9612 }; 9613 9614 // Starting at the loop predecessor, climb up the predecessor chain, as long 9615 // as there are predecessors that can be found that have unique successors 9616 // leading to the original header. 9617 for (std::pair<BasicBlock *, BasicBlock *> 9618 Pair(L->getLoopPredecessor(), L->getHeader()); 9619 Pair.first; 9620 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9621 9622 if (ProveViaGuard(Pair.first)) 9623 return true; 9624 9625 BranchInst *LoopEntryPredicate = 9626 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9627 if (!LoopEntryPredicate || 9628 LoopEntryPredicate->isUnconditional()) 9629 continue; 9630 9631 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9632 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9633 return true; 9634 } 9635 9636 // Check conditions due to any @llvm.assume intrinsics. 9637 for (auto &AssumeVH : AC.assumptions()) { 9638 if (!AssumeVH) 9639 continue; 9640 auto *CI = cast<CallInst>(AssumeVH); 9641 if (!DT.dominates(CI, L->getHeader())) 9642 continue; 9643 9644 if (ProveViaCond(CI->getArgOperand(0), false)) 9645 return true; 9646 } 9647 9648 return false; 9649 } 9650 9651 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9652 const SCEV *LHS, const SCEV *RHS, 9653 Value *FoundCondValue, 9654 bool Inverse) { 9655 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9656 return false; 9657 9658 auto ClearOnExit = 9659 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9660 9661 // Recursively handle And and Or conditions. 9662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9663 if (BO->getOpcode() == Instruction::And) { 9664 if (!Inverse) 9665 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9666 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9667 } else if (BO->getOpcode() == Instruction::Or) { 9668 if (Inverse) 9669 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9670 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9671 } 9672 } 9673 9674 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9675 if (!ICI) return false; 9676 9677 // Now that we found a conditional branch that dominates the loop or controls 9678 // the loop latch. Check to see if it is the comparison we are looking for. 9679 ICmpInst::Predicate FoundPred; 9680 if (Inverse) 9681 FoundPred = ICI->getInversePredicate(); 9682 else 9683 FoundPred = ICI->getPredicate(); 9684 9685 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9686 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9687 9688 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9689 } 9690 9691 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9692 const SCEV *RHS, 9693 ICmpInst::Predicate FoundPred, 9694 const SCEV *FoundLHS, 9695 const SCEV *FoundRHS) { 9696 // Balance the types. 9697 if (getTypeSizeInBits(LHS->getType()) < 9698 getTypeSizeInBits(FoundLHS->getType())) { 9699 if (CmpInst::isSigned(Pred)) { 9700 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9701 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9702 } else { 9703 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9704 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9705 } 9706 } else if (getTypeSizeInBits(LHS->getType()) > 9707 getTypeSizeInBits(FoundLHS->getType())) { 9708 if (CmpInst::isSigned(FoundPred)) { 9709 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9710 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9711 } else { 9712 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9713 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9714 } 9715 } 9716 9717 // Canonicalize the query to match the way instcombine will have 9718 // canonicalized the comparison. 9719 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9720 if (LHS == RHS) 9721 return CmpInst::isTrueWhenEqual(Pred); 9722 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9723 if (FoundLHS == FoundRHS) 9724 return CmpInst::isFalseWhenEqual(FoundPred); 9725 9726 // Check to see if we can make the LHS or RHS match. 9727 if (LHS == FoundRHS || RHS == FoundLHS) { 9728 if (isa<SCEVConstant>(RHS)) { 9729 std::swap(FoundLHS, FoundRHS); 9730 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9731 } else { 9732 std::swap(LHS, RHS); 9733 Pred = ICmpInst::getSwappedPredicate(Pred); 9734 } 9735 } 9736 9737 // Check whether the found predicate is the same as the desired predicate. 9738 if (FoundPred == Pred) 9739 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9740 9741 // Check whether swapping the found predicate makes it the same as the 9742 // desired predicate. 9743 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9744 if (isa<SCEVConstant>(RHS)) 9745 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9746 else 9747 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9748 RHS, LHS, FoundLHS, FoundRHS); 9749 } 9750 9751 // Unsigned comparison is the same as signed comparison when both the operands 9752 // are non-negative. 9753 if (CmpInst::isUnsigned(FoundPred) && 9754 CmpInst::getSignedPredicate(FoundPred) == Pred && 9755 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9756 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9757 9758 // Check if we can make progress by sharpening ranges. 9759 if (FoundPred == ICmpInst::ICMP_NE && 9760 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9761 9762 const SCEVConstant *C = nullptr; 9763 const SCEV *V = nullptr; 9764 9765 if (isa<SCEVConstant>(FoundLHS)) { 9766 C = cast<SCEVConstant>(FoundLHS); 9767 V = FoundRHS; 9768 } else { 9769 C = cast<SCEVConstant>(FoundRHS); 9770 V = FoundLHS; 9771 } 9772 9773 // The guarding predicate tells us that C != V. If the known range 9774 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9775 // range we consider has to correspond to same signedness as the 9776 // predicate we're interested in folding. 9777 9778 APInt Min = ICmpInst::isSigned(Pred) ? 9779 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9780 9781 if (Min == C->getAPInt()) { 9782 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9783 // This is true even if (Min + 1) wraps around -- in case of 9784 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9785 9786 APInt SharperMin = Min + 1; 9787 9788 switch (Pred) { 9789 case ICmpInst::ICMP_SGE: 9790 case ICmpInst::ICMP_UGE: 9791 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9792 // RHS, we're done. 9793 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9794 getConstant(SharperMin))) 9795 return true; 9796 LLVM_FALLTHROUGH; 9797 9798 case ICmpInst::ICMP_SGT: 9799 case ICmpInst::ICMP_UGT: 9800 // We know from the range information that (V `Pred` Min || 9801 // V == Min). We know from the guarding condition that !(V 9802 // == Min). This gives us 9803 // 9804 // V `Pred` Min || V == Min && !(V == Min) 9805 // => V `Pred` Min 9806 // 9807 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9808 9809 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9810 return true; 9811 LLVM_FALLTHROUGH; 9812 9813 default: 9814 // No change 9815 break; 9816 } 9817 } 9818 } 9819 9820 // Check whether the actual condition is beyond sufficient. 9821 if (FoundPred == ICmpInst::ICMP_EQ) 9822 if (ICmpInst::isTrueWhenEqual(Pred)) 9823 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9824 return true; 9825 if (Pred == ICmpInst::ICMP_NE) 9826 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9827 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9828 return true; 9829 9830 // Otherwise assume the worst. 9831 return false; 9832 } 9833 9834 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9835 const SCEV *&L, const SCEV *&R, 9836 SCEV::NoWrapFlags &Flags) { 9837 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9838 if (!AE || AE->getNumOperands() != 2) 9839 return false; 9840 9841 L = AE->getOperand(0); 9842 R = AE->getOperand(1); 9843 Flags = AE->getNoWrapFlags(); 9844 return true; 9845 } 9846 9847 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9848 const SCEV *Less) { 9849 // We avoid subtracting expressions here because this function is usually 9850 // fairly deep in the call stack (i.e. is called many times). 9851 9852 // X - X = 0. 9853 if (More == Less) 9854 return APInt(getTypeSizeInBits(More->getType()), 0); 9855 9856 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9857 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9858 const auto *MAR = cast<SCEVAddRecExpr>(More); 9859 9860 if (LAR->getLoop() != MAR->getLoop()) 9861 return None; 9862 9863 // We look at affine expressions only; not for correctness but to keep 9864 // getStepRecurrence cheap. 9865 if (!LAR->isAffine() || !MAR->isAffine()) 9866 return None; 9867 9868 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9869 return None; 9870 9871 Less = LAR->getStart(); 9872 More = MAR->getStart(); 9873 9874 // fall through 9875 } 9876 9877 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9878 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9879 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9880 return M - L; 9881 } 9882 9883 SCEV::NoWrapFlags Flags; 9884 const SCEV *LLess = nullptr, *RLess = nullptr; 9885 const SCEV *LMore = nullptr, *RMore = nullptr; 9886 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9887 // Compare (X + C1) vs X. 9888 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9889 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9890 if (RLess == More) 9891 return -(C1->getAPInt()); 9892 9893 // Compare X vs (X + C2). 9894 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9895 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9896 if (RMore == Less) 9897 return C2->getAPInt(); 9898 9899 // Compare (X + C1) vs (X + C2). 9900 if (C1 && C2 && RLess == RMore) 9901 return C2->getAPInt() - C1->getAPInt(); 9902 9903 return None; 9904 } 9905 9906 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9907 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9908 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9909 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9910 return false; 9911 9912 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9913 if (!AddRecLHS) 9914 return false; 9915 9916 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9917 if (!AddRecFoundLHS) 9918 return false; 9919 9920 // We'd like to let SCEV reason about control dependencies, so we constrain 9921 // both the inequalities to be about add recurrences on the same loop. This 9922 // way we can use isLoopEntryGuardedByCond later. 9923 9924 const Loop *L = AddRecFoundLHS->getLoop(); 9925 if (L != AddRecLHS->getLoop()) 9926 return false; 9927 9928 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9929 // 9930 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9931 // ... (2) 9932 // 9933 // Informal proof for (2), assuming (1) [*]: 9934 // 9935 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9936 // 9937 // Then 9938 // 9939 // FoundLHS s< FoundRHS s< INT_MIN - C 9940 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9941 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9942 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9943 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9944 // <=> FoundLHS + C s< FoundRHS + C 9945 // 9946 // [*]: (1) can be proved by ruling out overflow. 9947 // 9948 // [**]: This can be proved by analyzing all the four possibilities: 9949 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9950 // (A s>= 0, B s>= 0). 9951 // 9952 // Note: 9953 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9954 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9955 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9956 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9957 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9958 // C)". 9959 9960 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9961 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9962 if (!LDiff || !RDiff || *LDiff != *RDiff) 9963 return false; 9964 9965 if (LDiff->isMinValue()) 9966 return true; 9967 9968 APInt FoundRHSLimit; 9969 9970 if (Pred == CmpInst::ICMP_ULT) { 9971 FoundRHSLimit = -(*RDiff); 9972 } else { 9973 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9974 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9975 } 9976 9977 // Try to prove (1) or (2), as needed. 9978 return isAvailableAtLoopEntry(FoundRHS, L) && 9979 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9980 getConstant(FoundRHSLimit)); 9981 } 9982 9983 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9984 const SCEV *LHS, const SCEV *RHS, 9985 const SCEV *FoundLHS, 9986 const SCEV *FoundRHS, unsigned Depth) { 9987 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9988 9989 auto ClearOnExit = make_scope_exit([&]() { 9990 if (LPhi) { 9991 bool Erased = PendingMerges.erase(LPhi); 9992 assert(Erased && "Failed to erase LPhi!"); 9993 (void)Erased; 9994 } 9995 if (RPhi) { 9996 bool Erased = PendingMerges.erase(RPhi); 9997 assert(Erased && "Failed to erase RPhi!"); 9998 (void)Erased; 9999 } 10000 }); 10001 10002 // Find respective Phis and check that they are not being pending. 10003 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10004 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10005 if (!PendingMerges.insert(Phi).second) 10006 return false; 10007 LPhi = Phi; 10008 } 10009 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10010 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10011 // If we detect a loop of Phi nodes being processed by this method, for 10012 // example: 10013 // 10014 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10015 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10016 // 10017 // we don't want to deal with a case that complex, so return conservative 10018 // answer false. 10019 if (!PendingMerges.insert(Phi).second) 10020 return false; 10021 RPhi = Phi; 10022 } 10023 10024 // If none of LHS, RHS is a Phi, nothing to do here. 10025 if (!LPhi && !RPhi) 10026 return false; 10027 10028 // If there is a SCEVUnknown Phi we are interested in, make it left. 10029 if (!LPhi) { 10030 std::swap(LHS, RHS); 10031 std::swap(FoundLHS, FoundRHS); 10032 std::swap(LPhi, RPhi); 10033 Pred = ICmpInst::getSwappedPredicate(Pred); 10034 } 10035 10036 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10037 const BasicBlock *LBB = LPhi->getParent(); 10038 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10039 10040 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10041 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10042 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10043 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10044 }; 10045 10046 if (RPhi && RPhi->getParent() == LBB) { 10047 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10048 // If we compare two Phis from the same block, and for each entry block 10049 // the predicate is true for incoming values from this block, then the 10050 // predicate is also true for the Phis. 10051 for (const BasicBlock *IncBB : predecessors(LBB)) { 10052 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10053 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10054 if (!ProvedEasily(L, R)) 10055 return false; 10056 } 10057 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10058 // Case two: RHS is also a Phi from the same basic block, and it is an 10059 // AddRec. It means that there is a loop which has both AddRec and Unknown 10060 // PHIs, for it we can compare incoming values of AddRec from above the loop 10061 // and latch with their respective incoming values of LPhi. 10062 // TODO: Generalize to handle loops with many inputs in a header. 10063 if (LPhi->getNumIncomingValues() != 2) return false; 10064 10065 auto *RLoop = RAR->getLoop(); 10066 auto *Predecessor = RLoop->getLoopPredecessor(); 10067 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10068 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10069 if (!ProvedEasily(L1, RAR->getStart())) 10070 return false; 10071 auto *Latch = RLoop->getLoopLatch(); 10072 assert(Latch && "Loop with AddRec with no latch?"); 10073 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10074 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10075 return false; 10076 } else { 10077 // In all other cases go over inputs of LHS and compare each of them to RHS, 10078 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10079 // At this point RHS is either a non-Phi, or it is a Phi from some block 10080 // different from LBB. 10081 for (const BasicBlock *IncBB : predecessors(LBB)) { 10082 // Check that RHS is available in this block. 10083 if (!dominates(RHS, IncBB)) 10084 return false; 10085 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10086 if (!ProvedEasily(L, RHS)) 10087 return false; 10088 } 10089 } 10090 return true; 10091 } 10092 10093 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10094 const SCEV *LHS, const SCEV *RHS, 10095 const SCEV *FoundLHS, 10096 const SCEV *FoundRHS) { 10097 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10098 return true; 10099 10100 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10101 return true; 10102 10103 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10104 FoundLHS, FoundRHS) || 10105 // ~x < ~y --> x > y 10106 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10107 getNotSCEV(FoundRHS), 10108 getNotSCEV(FoundLHS)); 10109 } 10110 10111 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10112 template <typename MinMaxExprType> 10113 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10114 const SCEV *Candidate) { 10115 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10116 if (!MinMaxExpr) 10117 return false; 10118 10119 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10120 } 10121 10122 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10123 ICmpInst::Predicate Pred, 10124 const SCEV *LHS, const SCEV *RHS) { 10125 // If both sides are affine addrecs for the same loop, with equal 10126 // steps, and we know the recurrences don't wrap, then we only 10127 // need to check the predicate on the starting values. 10128 10129 if (!ICmpInst::isRelational(Pred)) 10130 return false; 10131 10132 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10133 if (!LAR) 10134 return false; 10135 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10136 if (!RAR) 10137 return false; 10138 if (LAR->getLoop() != RAR->getLoop()) 10139 return false; 10140 if (!LAR->isAffine() || !RAR->isAffine()) 10141 return false; 10142 10143 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10144 return false; 10145 10146 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10147 SCEV::FlagNSW : SCEV::FlagNUW; 10148 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10149 return false; 10150 10151 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10152 } 10153 10154 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10155 /// expression? 10156 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10157 ICmpInst::Predicate Pred, 10158 const SCEV *LHS, const SCEV *RHS) { 10159 switch (Pred) { 10160 default: 10161 return false; 10162 10163 case ICmpInst::ICMP_SGE: 10164 std::swap(LHS, RHS); 10165 LLVM_FALLTHROUGH; 10166 case ICmpInst::ICMP_SLE: 10167 return 10168 // min(A, ...) <= A 10169 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10170 // A <= max(A, ...) 10171 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10172 10173 case ICmpInst::ICMP_UGE: 10174 std::swap(LHS, RHS); 10175 LLVM_FALLTHROUGH; 10176 case ICmpInst::ICMP_ULE: 10177 return 10178 // min(A, ...) <= A 10179 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10180 // A <= max(A, ...) 10181 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10182 } 10183 10184 llvm_unreachable("covered switch fell through?!"); 10185 } 10186 10187 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10188 const SCEV *LHS, const SCEV *RHS, 10189 const SCEV *FoundLHS, 10190 const SCEV *FoundRHS, 10191 unsigned Depth) { 10192 assert(getTypeSizeInBits(LHS->getType()) == 10193 getTypeSizeInBits(RHS->getType()) && 10194 "LHS and RHS have different sizes?"); 10195 assert(getTypeSizeInBits(FoundLHS->getType()) == 10196 getTypeSizeInBits(FoundRHS->getType()) && 10197 "FoundLHS and FoundRHS have different sizes?"); 10198 // We want to avoid hurting the compile time with analysis of too big trees. 10199 if (Depth > MaxSCEVOperationsImplicationDepth) 10200 return false; 10201 // We only want to work with ICMP_SGT comparison so far. 10202 // TODO: Extend to ICMP_UGT? 10203 if (Pred == ICmpInst::ICMP_SLT) { 10204 Pred = ICmpInst::ICMP_SGT; 10205 std::swap(LHS, RHS); 10206 std::swap(FoundLHS, FoundRHS); 10207 } 10208 if (Pred != ICmpInst::ICMP_SGT) 10209 return false; 10210 10211 auto GetOpFromSExt = [&](const SCEV *S) { 10212 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10213 return Ext->getOperand(); 10214 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10215 // the constant in some cases. 10216 return S; 10217 }; 10218 10219 // Acquire values from extensions. 10220 auto *OrigLHS = LHS; 10221 auto *OrigFoundLHS = FoundLHS; 10222 LHS = GetOpFromSExt(LHS); 10223 FoundLHS = GetOpFromSExt(FoundLHS); 10224 10225 // Is the SGT predicate can be proved trivially or using the found context. 10226 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10227 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10228 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10229 FoundRHS, Depth + 1); 10230 }; 10231 10232 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10233 // We want to avoid creation of any new non-constant SCEV. Since we are 10234 // going to compare the operands to RHS, we should be certain that we don't 10235 // need any size extensions for this. So let's decline all cases when the 10236 // sizes of types of LHS and RHS do not match. 10237 // TODO: Maybe try to get RHS from sext to catch more cases? 10238 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10239 return false; 10240 10241 // Should not overflow. 10242 if (!LHSAddExpr->hasNoSignedWrap()) 10243 return false; 10244 10245 auto *LL = LHSAddExpr->getOperand(0); 10246 auto *LR = LHSAddExpr->getOperand(1); 10247 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10248 10249 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10250 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10251 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10252 }; 10253 // Try to prove the following rule: 10254 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10255 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10256 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10257 return true; 10258 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10259 Value *LL, *LR; 10260 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10261 10262 using namespace llvm::PatternMatch; 10263 10264 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10265 // Rules for division. 10266 // We are going to perform some comparisons with Denominator and its 10267 // derivative expressions. In general case, creating a SCEV for it may 10268 // lead to a complex analysis of the entire graph, and in particular it 10269 // can request trip count recalculation for the same loop. This would 10270 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10271 // this, we only want to create SCEVs that are constants in this section. 10272 // So we bail if Denominator is not a constant. 10273 if (!isa<ConstantInt>(LR)) 10274 return false; 10275 10276 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10277 10278 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10279 // then a SCEV for the numerator already exists and matches with FoundLHS. 10280 auto *Numerator = getExistingSCEV(LL); 10281 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10282 return false; 10283 10284 // Make sure that the numerator matches with FoundLHS and the denominator 10285 // is positive. 10286 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10287 return false; 10288 10289 auto *DTy = Denominator->getType(); 10290 auto *FRHSTy = FoundRHS->getType(); 10291 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10292 // One of types is a pointer and another one is not. We cannot extend 10293 // them properly to a wider type, so let us just reject this case. 10294 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10295 // to avoid this check. 10296 return false; 10297 10298 // Given that: 10299 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10300 auto *WTy = getWiderType(DTy, FRHSTy); 10301 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10302 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10303 10304 // Try to prove the following rule: 10305 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10306 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10307 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10308 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10309 if (isKnownNonPositive(RHS) && 10310 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10311 return true; 10312 10313 // Try to prove the following rule: 10314 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10315 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10316 // If we divide it by Denominator > 2, then: 10317 // 1. If FoundLHS is negative, then the result is 0. 10318 // 2. If FoundLHS is non-negative, then the result is non-negative. 10319 // Anyways, the result is non-negative. 10320 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10321 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10322 if (isKnownNegative(RHS) && 10323 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10324 return true; 10325 } 10326 } 10327 10328 // If our expression contained SCEVUnknown Phis, and we split it down and now 10329 // need to prove something for them, try to prove the predicate for every 10330 // possible incoming values of those Phis. 10331 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10332 return true; 10333 10334 return false; 10335 } 10336 10337 bool 10338 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10339 const SCEV *LHS, const SCEV *RHS) { 10340 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10341 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10342 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10343 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10344 } 10345 10346 bool 10347 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10348 const SCEV *LHS, const SCEV *RHS, 10349 const SCEV *FoundLHS, 10350 const SCEV *FoundRHS) { 10351 switch (Pred) { 10352 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10353 case ICmpInst::ICMP_EQ: 10354 case ICmpInst::ICMP_NE: 10355 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10356 return true; 10357 break; 10358 case ICmpInst::ICMP_SLT: 10359 case ICmpInst::ICMP_SLE: 10360 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10361 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10362 return true; 10363 break; 10364 case ICmpInst::ICMP_SGT: 10365 case ICmpInst::ICMP_SGE: 10366 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10367 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10368 return true; 10369 break; 10370 case ICmpInst::ICMP_ULT: 10371 case ICmpInst::ICMP_ULE: 10372 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10373 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10374 return true; 10375 break; 10376 case ICmpInst::ICMP_UGT: 10377 case ICmpInst::ICMP_UGE: 10378 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10379 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10380 return true; 10381 break; 10382 } 10383 10384 // Maybe it can be proved via operations? 10385 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10386 return true; 10387 10388 return false; 10389 } 10390 10391 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10392 const SCEV *LHS, 10393 const SCEV *RHS, 10394 const SCEV *FoundLHS, 10395 const SCEV *FoundRHS) { 10396 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10397 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10398 // reduce the compile time impact of this optimization. 10399 return false; 10400 10401 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10402 if (!Addend) 10403 return false; 10404 10405 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10406 10407 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10408 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10409 ConstantRange FoundLHSRange = 10410 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10411 10412 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10413 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10414 10415 // We can also compute the range of values for `LHS` that satisfy the 10416 // consequent, "`LHS` `Pred` `RHS`": 10417 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10418 ConstantRange SatisfyingLHSRange = 10419 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10420 10421 // The antecedent implies the consequent if every value of `LHS` that 10422 // satisfies the antecedent also satisfies the consequent. 10423 return SatisfyingLHSRange.contains(LHSRange); 10424 } 10425 10426 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10427 bool IsSigned, bool NoWrap) { 10428 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10429 10430 if (NoWrap) return false; 10431 10432 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10433 const SCEV *One = getOne(Stride->getType()); 10434 10435 if (IsSigned) { 10436 APInt MaxRHS = getSignedRangeMax(RHS); 10437 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10438 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10439 10440 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10441 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10442 } 10443 10444 APInt MaxRHS = getUnsignedRangeMax(RHS); 10445 APInt MaxValue = APInt::getMaxValue(BitWidth); 10446 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10447 10448 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10449 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10450 } 10451 10452 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10453 bool IsSigned, bool NoWrap) { 10454 if (NoWrap) return false; 10455 10456 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10457 const SCEV *One = getOne(Stride->getType()); 10458 10459 if (IsSigned) { 10460 APInt MinRHS = getSignedRangeMin(RHS); 10461 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10462 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10463 10464 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10465 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10466 } 10467 10468 APInt MinRHS = getUnsignedRangeMin(RHS); 10469 APInt MinValue = APInt::getMinValue(BitWidth); 10470 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10471 10472 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10473 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10474 } 10475 10476 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10477 bool Equality) { 10478 const SCEV *One = getOne(Step->getType()); 10479 Delta = Equality ? getAddExpr(Delta, Step) 10480 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10481 return getUDivExpr(Delta, Step); 10482 } 10483 10484 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10485 const SCEV *Stride, 10486 const SCEV *End, 10487 unsigned BitWidth, 10488 bool IsSigned) { 10489 10490 assert(!isKnownNonPositive(Stride) && 10491 "Stride is expected strictly positive!"); 10492 // Calculate the maximum backedge count based on the range of values 10493 // permitted by Start, End, and Stride. 10494 const SCEV *MaxBECount; 10495 APInt MinStart = 10496 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10497 10498 APInt StrideForMaxBECount = 10499 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10500 10501 // We already know that the stride is positive, so we paper over conservatism 10502 // in our range computation by forcing StrideForMaxBECount to be at least one. 10503 // In theory this is unnecessary, but we expect MaxBECount to be a 10504 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10505 // is nothing to constant fold it to). 10506 APInt One(BitWidth, 1, IsSigned); 10507 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10508 10509 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10510 : APInt::getMaxValue(BitWidth); 10511 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10512 10513 // Although End can be a MAX expression we estimate MaxEnd considering only 10514 // the case End = RHS of the loop termination condition. This is safe because 10515 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10516 // taken count. 10517 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10518 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10519 10520 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10521 getConstant(StrideForMaxBECount) /* Step */, 10522 false /* Equality */); 10523 10524 return MaxBECount; 10525 } 10526 10527 ScalarEvolution::ExitLimit 10528 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10529 const Loop *L, bool IsSigned, 10530 bool ControlsExit, bool AllowPredicates) { 10531 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10532 10533 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10534 bool PredicatedIV = false; 10535 10536 if (!IV && AllowPredicates) { 10537 // Try to make this an AddRec using runtime tests, in the first X 10538 // iterations of this loop, where X is the SCEV expression found by the 10539 // algorithm below. 10540 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10541 PredicatedIV = true; 10542 } 10543 10544 // Avoid weird loops 10545 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10546 return getCouldNotCompute(); 10547 10548 bool NoWrap = ControlsExit && 10549 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10550 10551 const SCEV *Stride = IV->getStepRecurrence(*this); 10552 10553 bool PositiveStride = isKnownPositive(Stride); 10554 10555 // Avoid negative or zero stride values. 10556 if (!PositiveStride) { 10557 // We can compute the correct backedge taken count for loops with unknown 10558 // strides if we can prove that the loop is not an infinite loop with side 10559 // effects. Here's the loop structure we are trying to handle - 10560 // 10561 // i = start 10562 // do { 10563 // A[i] = i; 10564 // i += s; 10565 // } while (i < end); 10566 // 10567 // The backedge taken count for such loops is evaluated as - 10568 // (max(end, start + stride) - start - 1) /u stride 10569 // 10570 // The additional preconditions that we need to check to prove correctness 10571 // of the above formula is as follows - 10572 // 10573 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10574 // NoWrap flag). 10575 // b) loop is single exit with no side effects. 10576 // 10577 // 10578 // Precondition a) implies that if the stride is negative, this is a single 10579 // trip loop. The backedge taken count formula reduces to zero in this case. 10580 // 10581 // Precondition b) implies that the unknown stride cannot be zero otherwise 10582 // we have UB. 10583 // 10584 // The positive stride case is the same as isKnownPositive(Stride) returning 10585 // true (original behavior of the function). 10586 // 10587 // We want to make sure that the stride is truly unknown as there are edge 10588 // cases where ScalarEvolution propagates no wrap flags to the 10589 // post-increment/decrement IV even though the increment/decrement operation 10590 // itself is wrapping. The computed backedge taken count may be wrong in 10591 // such cases. This is prevented by checking that the stride is not known to 10592 // be either positive or non-positive. For example, no wrap flags are 10593 // propagated to the post-increment IV of this loop with a trip count of 2 - 10594 // 10595 // unsigned char i; 10596 // for(i=127; i<128; i+=129) 10597 // A[i] = i; 10598 // 10599 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10600 !loopHasNoSideEffects(L)) 10601 return getCouldNotCompute(); 10602 } else if (!Stride->isOne() && 10603 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10604 // Avoid proven overflow cases: this will ensure that the backedge taken 10605 // count will not generate any unsigned overflow. Relaxed no-overflow 10606 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10607 // undefined behaviors like the case of C language. 10608 return getCouldNotCompute(); 10609 10610 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10611 : ICmpInst::ICMP_ULT; 10612 const SCEV *Start = IV->getStart(); 10613 const SCEV *End = RHS; 10614 // When the RHS is not invariant, we do not know the end bound of the loop and 10615 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10616 // calculate the MaxBECount, given the start, stride and max value for the end 10617 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10618 // checked above). 10619 if (!isLoopInvariant(RHS, L)) { 10620 const SCEV *MaxBECount = computeMaxBECountForLT( 10621 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10622 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10623 false /*MaxOrZero*/, Predicates); 10624 } 10625 // If the backedge is taken at least once, then it will be taken 10626 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10627 // is the LHS value of the less-than comparison the first time it is evaluated 10628 // and End is the RHS. 10629 const SCEV *BECountIfBackedgeTaken = 10630 computeBECount(getMinusSCEV(End, Start), Stride, false); 10631 // If the loop entry is guarded by the result of the backedge test of the 10632 // first loop iteration, then we know the backedge will be taken at least 10633 // once and so the backedge taken count is as above. If not then we use the 10634 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10635 // as if the backedge is taken at least once max(End,Start) is End and so the 10636 // result is as above, and if not max(End,Start) is Start so we get a backedge 10637 // count of zero. 10638 const SCEV *BECount; 10639 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10640 BECount = BECountIfBackedgeTaken; 10641 else { 10642 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10643 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10644 } 10645 10646 const SCEV *MaxBECount; 10647 bool MaxOrZero = false; 10648 if (isa<SCEVConstant>(BECount)) 10649 MaxBECount = BECount; 10650 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10651 // If we know exactly how many times the backedge will be taken if it's 10652 // taken at least once, then the backedge count will either be that or 10653 // zero. 10654 MaxBECount = BECountIfBackedgeTaken; 10655 MaxOrZero = true; 10656 } else { 10657 MaxBECount = computeMaxBECountForLT( 10658 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10659 } 10660 10661 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10662 !isa<SCEVCouldNotCompute>(BECount)) 10663 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10664 10665 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10666 } 10667 10668 ScalarEvolution::ExitLimit 10669 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10670 const Loop *L, bool IsSigned, 10671 bool ControlsExit, bool AllowPredicates) { 10672 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10673 // We handle only IV > Invariant 10674 if (!isLoopInvariant(RHS, L)) 10675 return getCouldNotCompute(); 10676 10677 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10678 if (!IV && AllowPredicates) 10679 // Try to make this an AddRec using runtime tests, in the first X 10680 // iterations of this loop, where X is the SCEV expression found by the 10681 // algorithm below. 10682 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10683 10684 // Avoid weird loops 10685 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10686 return getCouldNotCompute(); 10687 10688 bool NoWrap = ControlsExit && 10689 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10690 10691 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10692 10693 // Avoid negative or zero stride values 10694 if (!isKnownPositive(Stride)) 10695 return getCouldNotCompute(); 10696 10697 // Avoid proven overflow cases: this will ensure that the backedge taken count 10698 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10699 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10700 // behaviors like the case of C language. 10701 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10702 return getCouldNotCompute(); 10703 10704 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10705 : ICmpInst::ICMP_UGT; 10706 10707 const SCEV *Start = IV->getStart(); 10708 const SCEV *End = RHS; 10709 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10710 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10711 10712 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10713 10714 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10715 : getUnsignedRangeMax(Start); 10716 10717 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10718 : getUnsignedRangeMin(Stride); 10719 10720 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10721 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10722 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10723 10724 // Although End can be a MIN expression we estimate MinEnd considering only 10725 // the case End = RHS. This is safe because in the other case (Start - End) 10726 // is zero, leading to a zero maximum backedge taken count. 10727 APInt MinEnd = 10728 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10729 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10730 10731 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10732 ? BECount 10733 : computeBECount(getConstant(MaxStart - MinEnd), 10734 getConstant(MinStride), false); 10735 10736 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10737 MaxBECount = BECount; 10738 10739 return ExitLimit(BECount, MaxBECount, false, Predicates); 10740 } 10741 10742 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10743 ScalarEvolution &SE) const { 10744 if (Range.isFullSet()) // Infinite loop. 10745 return SE.getCouldNotCompute(); 10746 10747 // If the start is a non-zero constant, shift the range to simplify things. 10748 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10749 if (!SC->getValue()->isZero()) { 10750 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10751 Operands[0] = SE.getZero(SC->getType()); 10752 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10753 getNoWrapFlags(FlagNW)); 10754 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10755 return ShiftedAddRec->getNumIterationsInRange( 10756 Range.subtract(SC->getAPInt()), SE); 10757 // This is strange and shouldn't happen. 10758 return SE.getCouldNotCompute(); 10759 } 10760 10761 // The only time we can solve this is when we have all constant indices. 10762 // Otherwise, we cannot determine the overflow conditions. 10763 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10764 return SE.getCouldNotCompute(); 10765 10766 // Okay at this point we know that all elements of the chrec are constants and 10767 // that the start element is zero. 10768 10769 // First check to see if the range contains zero. If not, the first 10770 // iteration exits. 10771 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10772 if (!Range.contains(APInt(BitWidth, 0))) 10773 return SE.getZero(getType()); 10774 10775 if (isAffine()) { 10776 // If this is an affine expression then we have this situation: 10777 // Solve {0,+,A} in Range === Ax in Range 10778 10779 // We know that zero is in the range. If A is positive then we know that 10780 // the upper value of the range must be the first possible exit value. 10781 // If A is negative then the lower of the range is the last possible loop 10782 // value. Also note that we already checked for a full range. 10783 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10784 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10785 10786 // The exit value should be (End+A)/A. 10787 APInt ExitVal = (End + A).udiv(A); 10788 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10789 10790 // Evaluate at the exit value. If we really did fall out of the valid 10791 // range, then we computed our trip count, otherwise wrap around or other 10792 // things must have happened. 10793 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10794 if (Range.contains(Val->getValue())) 10795 return SE.getCouldNotCompute(); // Something strange happened 10796 10797 // Ensure that the previous value is in the range. This is a sanity check. 10798 assert(Range.contains( 10799 EvaluateConstantChrecAtConstant(this, 10800 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10801 "Linear scev computation is off in a bad way!"); 10802 return SE.getConstant(ExitValue); 10803 } 10804 10805 if (isQuadratic()) { 10806 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10807 return SE.getConstant(S.getValue()); 10808 } 10809 10810 return SE.getCouldNotCompute(); 10811 } 10812 10813 const SCEVAddRecExpr * 10814 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10815 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10816 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10817 // but in this case we cannot guarantee that the value returned will be an 10818 // AddRec because SCEV does not have a fixed point where it stops 10819 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10820 // may happen if we reach arithmetic depth limit while simplifying. So we 10821 // construct the returned value explicitly. 10822 SmallVector<const SCEV *, 3> Ops; 10823 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10824 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10825 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10826 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10827 // We know that the last operand is not a constant zero (otherwise it would 10828 // have been popped out earlier). This guarantees us that if the result has 10829 // the same last operand, then it will also not be popped out, meaning that 10830 // the returned value will be an AddRec. 10831 const SCEV *Last = getOperand(getNumOperands() - 1); 10832 assert(!Last->isZero() && "Recurrency with zero step?"); 10833 Ops.push_back(Last); 10834 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10835 SCEV::FlagAnyWrap)); 10836 } 10837 10838 // Return true when S contains at least an undef value. 10839 static inline bool containsUndefs(const SCEV *S) { 10840 return SCEVExprContains(S, [](const SCEV *S) { 10841 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10842 return isa<UndefValue>(SU->getValue()); 10843 return false; 10844 }); 10845 } 10846 10847 namespace { 10848 10849 // Collect all steps of SCEV expressions. 10850 struct SCEVCollectStrides { 10851 ScalarEvolution &SE; 10852 SmallVectorImpl<const SCEV *> &Strides; 10853 10854 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10855 : SE(SE), Strides(S) {} 10856 10857 bool follow(const SCEV *S) { 10858 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10859 Strides.push_back(AR->getStepRecurrence(SE)); 10860 return true; 10861 } 10862 10863 bool isDone() const { return false; } 10864 }; 10865 10866 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10867 struct SCEVCollectTerms { 10868 SmallVectorImpl<const SCEV *> &Terms; 10869 10870 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10871 10872 bool follow(const SCEV *S) { 10873 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10874 isa<SCEVSignExtendExpr>(S)) { 10875 if (!containsUndefs(S)) 10876 Terms.push_back(S); 10877 10878 // Stop recursion: once we collected a term, do not walk its operands. 10879 return false; 10880 } 10881 10882 // Keep looking. 10883 return true; 10884 } 10885 10886 bool isDone() const { return false; } 10887 }; 10888 10889 // Check if a SCEV contains an AddRecExpr. 10890 struct SCEVHasAddRec { 10891 bool &ContainsAddRec; 10892 10893 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10894 ContainsAddRec = false; 10895 } 10896 10897 bool follow(const SCEV *S) { 10898 if (isa<SCEVAddRecExpr>(S)) { 10899 ContainsAddRec = true; 10900 10901 // Stop recursion: once we collected a term, do not walk its operands. 10902 return false; 10903 } 10904 10905 // Keep looking. 10906 return true; 10907 } 10908 10909 bool isDone() const { return false; } 10910 }; 10911 10912 // Find factors that are multiplied with an expression that (possibly as a 10913 // subexpression) contains an AddRecExpr. In the expression: 10914 // 10915 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10916 // 10917 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10918 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10919 // parameters as they form a product with an induction variable. 10920 // 10921 // This collector expects all array size parameters to be in the same MulExpr. 10922 // It might be necessary to later add support for collecting parameters that are 10923 // spread over different nested MulExpr. 10924 struct SCEVCollectAddRecMultiplies { 10925 SmallVectorImpl<const SCEV *> &Terms; 10926 ScalarEvolution &SE; 10927 10928 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10929 : Terms(T), SE(SE) {} 10930 10931 bool follow(const SCEV *S) { 10932 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10933 bool HasAddRec = false; 10934 SmallVector<const SCEV *, 0> Operands; 10935 for (auto Op : Mul->operands()) { 10936 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10937 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10938 Operands.push_back(Op); 10939 } else if (Unknown) { 10940 HasAddRec = true; 10941 } else { 10942 bool ContainsAddRec; 10943 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10944 visitAll(Op, ContiansAddRec); 10945 HasAddRec |= ContainsAddRec; 10946 } 10947 } 10948 if (Operands.size() == 0) 10949 return true; 10950 10951 if (!HasAddRec) 10952 return false; 10953 10954 Terms.push_back(SE.getMulExpr(Operands)); 10955 // Stop recursion: once we collected a term, do not walk its operands. 10956 return false; 10957 } 10958 10959 // Keep looking. 10960 return true; 10961 } 10962 10963 bool isDone() const { return false; } 10964 }; 10965 10966 } // end anonymous namespace 10967 10968 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10969 /// two places: 10970 /// 1) The strides of AddRec expressions. 10971 /// 2) Unknowns that are multiplied with AddRec expressions. 10972 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10973 SmallVectorImpl<const SCEV *> &Terms) { 10974 SmallVector<const SCEV *, 4> Strides; 10975 SCEVCollectStrides StrideCollector(*this, Strides); 10976 visitAll(Expr, StrideCollector); 10977 10978 LLVM_DEBUG({ 10979 dbgs() << "Strides:\n"; 10980 for (const SCEV *S : Strides) 10981 dbgs() << *S << "\n"; 10982 }); 10983 10984 for (const SCEV *S : Strides) { 10985 SCEVCollectTerms TermCollector(Terms); 10986 visitAll(S, TermCollector); 10987 } 10988 10989 LLVM_DEBUG({ 10990 dbgs() << "Terms:\n"; 10991 for (const SCEV *T : Terms) 10992 dbgs() << *T << "\n"; 10993 }); 10994 10995 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10996 visitAll(Expr, MulCollector); 10997 } 10998 10999 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11000 SmallVectorImpl<const SCEV *> &Terms, 11001 SmallVectorImpl<const SCEV *> &Sizes) { 11002 int Last = Terms.size() - 1; 11003 const SCEV *Step = Terms[Last]; 11004 11005 // End of recursion. 11006 if (Last == 0) { 11007 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11008 SmallVector<const SCEV *, 2> Qs; 11009 for (const SCEV *Op : M->operands()) 11010 if (!isa<SCEVConstant>(Op)) 11011 Qs.push_back(Op); 11012 11013 Step = SE.getMulExpr(Qs); 11014 } 11015 11016 Sizes.push_back(Step); 11017 return true; 11018 } 11019 11020 for (const SCEV *&Term : Terms) { 11021 // Normalize the terms before the next call to findArrayDimensionsRec. 11022 const SCEV *Q, *R; 11023 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11024 11025 // Bail out when GCD does not evenly divide one of the terms. 11026 if (!R->isZero()) 11027 return false; 11028 11029 Term = Q; 11030 } 11031 11032 // Remove all SCEVConstants. 11033 Terms.erase( 11034 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11035 Terms.end()); 11036 11037 if (Terms.size() > 0) 11038 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11039 return false; 11040 11041 Sizes.push_back(Step); 11042 return true; 11043 } 11044 11045 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11046 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11047 for (const SCEV *T : Terms) 11048 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11049 return true; 11050 return false; 11051 } 11052 11053 // Return the number of product terms in S. 11054 static inline int numberOfTerms(const SCEV *S) { 11055 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11056 return Expr->getNumOperands(); 11057 return 1; 11058 } 11059 11060 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11061 if (isa<SCEVConstant>(T)) 11062 return nullptr; 11063 11064 if (isa<SCEVUnknown>(T)) 11065 return T; 11066 11067 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11068 SmallVector<const SCEV *, 2> Factors; 11069 for (const SCEV *Op : M->operands()) 11070 if (!isa<SCEVConstant>(Op)) 11071 Factors.push_back(Op); 11072 11073 return SE.getMulExpr(Factors); 11074 } 11075 11076 return T; 11077 } 11078 11079 /// Return the size of an element read or written by Inst. 11080 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11081 Type *Ty; 11082 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11083 Ty = Store->getValueOperand()->getType(); 11084 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11085 Ty = Load->getType(); 11086 else 11087 return nullptr; 11088 11089 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11090 return getSizeOfExpr(ETy, Ty); 11091 } 11092 11093 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11094 SmallVectorImpl<const SCEV *> &Sizes, 11095 const SCEV *ElementSize) { 11096 if (Terms.size() < 1 || !ElementSize) 11097 return; 11098 11099 // Early return when Terms do not contain parameters: we do not delinearize 11100 // non parametric SCEVs. 11101 if (!containsParameters(Terms)) 11102 return; 11103 11104 LLVM_DEBUG({ 11105 dbgs() << "Terms:\n"; 11106 for (const SCEV *T : Terms) 11107 dbgs() << *T << "\n"; 11108 }); 11109 11110 // Remove duplicates. 11111 array_pod_sort(Terms.begin(), Terms.end()); 11112 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11113 11114 // Put larger terms first. 11115 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11116 return numberOfTerms(LHS) > numberOfTerms(RHS); 11117 }); 11118 11119 // Try to divide all terms by the element size. If term is not divisible by 11120 // element size, proceed with the original term. 11121 for (const SCEV *&Term : Terms) { 11122 const SCEV *Q, *R; 11123 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11124 if (!Q->isZero()) 11125 Term = Q; 11126 } 11127 11128 SmallVector<const SCEV *, 4> NewTerms; 11129 11130 // Remove constant factors. 11131 for (const SCEV *T : Terms) 11132 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11133 NewTerms.push_back(NewT); 11134 11135 LLVM_DEBUG({ 11136 dbgs() << "Terms after sorting:\n"; 11137 for (const SCEV *T : NewTerms) 11138 dbgs() << *T << "\n"; 11139 }); 11140 11141 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11142 Sizes.clear(); 11143 return; 11144 } 11145 11146 // The last element to be pushed into Sizes is the size of an element. 11147 Sizes.push_back(ElementSize); 11148 11149 LLVM_DEBUG({ 11150 dbgs() << "Sizes:\n"; 11151 for (const SCEV *S : Sizes) 11152 dbgs() << *S << "\n"; 11153 }); 11154 } 11155 11156 void ScalarEvolution::computeAccessFunctions( 11157 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11158 SmallVectorImpl<const SCEV *> &Sizes) { 11159 // Early exit in case this SCEV is not an affine multivariate function. 11160 if (Sizes.empty()) 11161 return; 11162 11163 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11164 if (!AR->isAffine()) 11165 return; 11166 11167 const SCEV *Res = Expr; 11168 int Last = Sizes.size() - 1; 11169 for (int i = Last; i >= 0; i--) { 11170 const SCEV *Q, *R; 11171 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11172 11173 LLVM_DEBUG({ 11174 dbgs() << "Res: " << *Res << "\n"; 11175 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11176 dbgs() << "Res divided by Sizes[i]:\n"; 11177 dbgs() << "Quotient: " << *Q << "\n"; 11178 dbgs() << "Remainder: " << *R << "\n"; 11179 }); 11180 11181 Res = Q; 11182 11183 // Do not record the last subscript corresponding to the size of elements in 11184 // the array. 11185 if (i == Last) { 11186 11187 // Bail out if the remainder is too complex. 11188 if (isa<SCEVAddRecExpr>(R)) { 11189 Subscripts.clear(); 11190 Sizes.clear(); 11191 return; 11192 } 11193 11194 continue; 11195 } 11196 11197 // Record the access function for the current subscript. 11198 Subscripts.push_back(R); 11199 } 11200 11201 // Also push in last position the remainder of the last division: it will be 11202 // the access function of the innermost dimension. 11203 Subscripts.push_back(Res); 11204 11205 std::reverse(Subscripts.begin(), Subscripts.end()); 11206 11207 LLVM_DEBUG({ 11208 dbgs() << "Subscripts:\n"; 11209 for (const SCEV *S : Subscripts) 11210 dbgs() << *S << "\n"; 11211 }); 11212 } 11213 11214 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11215 /// sizes of an array access. Returns the remainder of the delinearization that 11216 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11217 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11218 /// expressions in the stride and base of a SCEV corresponding to the 11219 /// computation of a GCD (greatest common divisor) of base and stride. When 11220 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11221 /// 11222 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11223 /// 11224 /// void foo(long n, long m, long o, double A[n][m][o]) { 11225 /// 11226 /// for (long i = 0; i < n; i++) 11227 /// for (long j = 0; j < m; j++) 11228 /// for (long k = 0; k < o; k++) 11229 /// A[i][j][k] = 1.0; 11230 /// } 11231 /// 11232 /// the delinearization input is the following AddRec SCEV: 11233 /// 11234 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11235 /// 11236 /// From this SCEV, we are able to say that the base offset of the access is %A 11237 /// because it appears as an offset that does not divide any of the strides in 11238 /// the loops: 11239 /// 11240 /// CHECK: Base offset: %A 11241 /// 11242 /// and then SCEV->delinearize determines the size of some of the dimensions of 11243 /// the array as these are the multiples by which the strides are happening: 11244 /// 11245 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11246 /// 11247 /// Note that the outermost dimension remains of UnknownSize because there are 11248 /// no strides that would help identifying the size of the last dimension: when 11249 /// the array has been statically allocated, one could compute the size of that 11250 /// dimension by dividing the overall size of the array by the size of the known 11251 /// dimensions: %m * %o * 8. 11252 /// 11253 /// Finally delinearize provides the access functions for the array reference 11254 /// that does correspond to A[i][j][k] of the above C testcase: 11255 /// 11256 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11257 /// 11258 /// The testcases are checking the output of a function pass: 11259 /// DelinearizationPass that walks through all loads and stores of a function 11260 /// asking for the SCEV of the memory access with respect to all enclosing 11261 /// loops, calling SCEV->delinearize on that and printing the results. 11262 void ScalarEvolution::delinearize(const SCEV *Expr, 11263 SmallVectorImpl<const SCEV *> &Subscripts, 11264 SmallVectorImpl<const SCEV *> &Sizes, 11265 const SCEV *ElementSize) { 11266 // First step: collect parametric terms. 11267 SmallVector<const SCEV *, 4> Terms; 11268 collectParametricTerms(Expr, Terms); 11269 11270 if (Terms.empty()) 11271 return; 11272 11273 // Second step: find subscript sizes. 11274 findArrayDimensions(Terms, Sizes, ElementSize); 11275 11276 if (Sizes.empty()) 11277 return; 11278 11279 // Third step: compute the access functions for each subscript. 11280 computeAccessFunctions(Expr, Subscripts, Sizes); 11281 11282 if (Subscripts.empty()) 11283 return; 11284 11285 LLVM_DEBUG({ 11286 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11287 dbgs() << "ArrayDecl[UnknownSize]"; 11288 for (const SCEV *S : Sizes) 11289 dbgs() << "[" << *S << "]"; 11290 11291 dbgs() << "\nArrayRef"; 11292 for (const SCEV *S : Subscripts) 11293 dbgs() << "[" << *S << "]"; 11294 dbgs() << "\n"; 11295 }); 11296 } 11297 11298 //===----------------------------------------------------------------------===// 11299 // SCEVCallbackVH Class Implementation 11300 //===----------------------------------------------------------------------===// 11301 11302 void ScalarEvolution::SCEVCallbackVH::deleted() { 11303 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11304 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11305 SE->ConstantEvolutionLoopExitValue.erase(PN); 11306 SE->eraseValueFromMap(getValPtr()); 11307 // this now dangles! 11308 } 11309 11310 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11311 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11312 11313 // Forget all the expressions associated with users of the old value, 11314 // so that future queries will recompute the expressions using the new 11315 // value. 11316 Value *Old = getValPtr(); 11317 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11318 SmallPtrSet<User *, 8> Visited; 11319 while (!Worklist.empty()) { 11320 User *U = Worklist.pop_back_val(); 11321 // Deleting the Old value will cause this to dangle. Postpone 11322 // that until everything else is done. 11323 if (U == Old) 11324 continue; 11325 if (!Visited.insert(U).second) 11326 continue; 11327 if (PHINode *PN = dyn_cast<PHINode>(U)) 11328 SE->ConstantEvolutionLoopExitValue.erase(PN); 11329 SE->eraseValueFromMap(U); 11330 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11331 } 11332 // Delete the Old value. 11333 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11334 SE->ConstantEvolutionLoopExitValue.erase(PN); 11335 SE->eraseValueFromMap(Old); 11336 // this now dangles! 11337 } 11338 11339 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11340 : CallbackVH(V), SE(se) {} 11341 11342 //===----------------------------------------------------------------------===// 11343 // ScalarEvolution Class Implementation 11344 //===----------------------------------------------------------------------===// 11345 11346 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11347 AssumptionCache &AC, DominatorTree &DT, 11348 LoopInfo &LI) 11349 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11350 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11351 LoopDispositions(64), BlockDispositions(64) { 11352 // To use guards for proving predicates, we need to scan every instruction in 11353 // relevant basic blocks, and not just terminators. Doing this is a waste of 11354 // time if the IR does not actually contain any calls to 11355 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11356 // 11357 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11358 // to _add_ guards to the module when there weren't any before, and wants 11359 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11360 // efficient in lieu of being smart in that rather obscure case. 11361 11362 auto *GuardDecl = F.getParent()->getFunction( 11363 Intrinsic::getName(Intrinsic::experimental_guard)); 11364 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11365 } 11366 11367 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11368 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11369 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11370 ValueExprMap(std::move(Arg.ValueExprMap)), 11371 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11372 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11373 PendingMerges(std::move(Arg.PendingMerges)), 11374 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11375 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11376 PredicatedBackedgeTakenCounts( 11377 std::move(Arg.PredicatedBackedgeTakenCounts)), 11378 ConstantEvolutionLoopExitValue( 11379 std::move(Arg.ConstantEvolutionLoopExitValue)), 11380 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11381 LoopDispositions(std::move(Arg.LoopDispositions)), 11382 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11383 BlockDispositions(std::move(Arg.BlockDispositions)), 11384 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11385 SignedRanges(std::move(Arg.SignedRanges)), 11386 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11387 UniquePreds(std::move(Arg.UniquePreds)), 11388 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11389 LoopUsers(std::move(Arg.LoopUsers)), 11390 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11391 FirstUnknown(Arg.FirstUnknown) { 11392 Arg.FirstUnknown = nullptr; 11393 } 11394 11395 ScalarEvolution::~ScalarEvolution() { 11396 // Iterate through all the SCEVUnknown instances and call their 11397 // destructors, so that they release their references to their values. 11398 for (SCEVUnknown *U = FirstUnknown; U;) { 11399 SCEVUnknown *Tmp = U; 11400 U = U->Next; 11401 Tmp->~SCEVUnknown(); 11402 } 11403 FirstUnknown = nullptr; 11404 11405 ExprValueMap.clear(); 11406 ValueExprMap.clear(); 11407 HasRecMap.clear(); 11408 11409 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11410 // that a loop had multiple computable exits. 11411 for (auto &BTCI : BackedgeTakenCounts) 11412 BTCI.second.clear(); 11413 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11414 BTCI.second.clear(); 11415 11416 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11417 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11418 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11419 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11420 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11421 } 11422 11423 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11424 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11425 } 11426 11427 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11428 const Loop *L) { 11429 // Print all inner loops first 11430 for (Loop *I : *L) 11431 PrintLoopInfo(OS, SE, I); 11432 11433 OS << "Loop "; 11434 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11435 OS << ": "; 11436 11437 SmallVector<BasicBlock *, 8> ExitingBlocks; 11438 L->getExitingBlocks(ExitingBlocks); 11439 if (ExitingBlocks.size() != 1) 11440 OS << "<multiple exits> "; 11441 11442 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11443 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11444 else 11445 OS << "Unpredictable backedge-taken count.\n"; 11446 11447 if (ExitingBlocks.size() > 1) 11448 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11449 OS << " exit count for " << ExitingBlock->getName() << ": " 11450 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11451 } 11452 11453 OS << "Loop "; 11454 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11455 OS << ": "; 11456 11457 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11458 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11459 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11460 OS << ", actual taken count either this or zero."; 11461 } else { 11462 OS << "Unpredictable max backedge-taken count. "; 11463 } 11464 11465 OS << "\n" 11466 "Loop "; 11467 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11468 OS << ": "; 11469 11470 SCEVUnionPredicate Pred; 11471 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11472 if (!isa<SCEVCouldNotCompute>(PBT)) { 11473 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11474 OS << " Predicates:\n"; 11475 Pred.print(OS, 4); 11476 } else { 11477 OS << "Unpredictable predicated backedge-taken count. "; 11478 } 11479 OS << "\n"; 11480 11481 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11482 OS << "Loop "; 11483 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11484 OS << ": "; 11485 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11486 } 11487 } 11488 11489 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11490 switch (LD) { 11491 case ScalarEvolution::LoopVariant: 11492 return "Variant"; 11493 case ScalarEvolution::LoopInvariant: 11494 return "Invariant"; 11495 case ScalarEvolution::LoopComputable: 11496 return "Computable"; 11497 } 11498 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11499 } 11500 11501 void ScalarEvolution::print(raw_ostream &OS) const { 11502 // ScalarEvolution's implementation of the print method is to print 11503 // out SCEV values of all instructions that are interesting. Doing 11504 // this potentially causes it to create new SCEV objects though, 11505 // which technically conflicts with the const qualifier. This isn't 11506 // observable from outside the class though, so casting away the 11507 // const isn't dangerous. 11508 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11509 11510 OS << "Classifying expressions for: "; 11511 F.printAsOperand(OS, /*PrintType=*/false); 11512 OS << "\n"; 11513 for (Instruction &I : instructions(F)) 11514 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11515 OS << I << '\n'; 11516 OS << " --> "; 11517 const SCEV *SV = SE.getSCEV(&I); 11518 SV->print(OS); 11519 if (!isa<SCEVCouldNotCompute>(SV)) { 11520 OS << " U: "; 11521 SE.getUnsignedRange(SV).print(OS); 11522 OS << " S: "; 11523 SE.getSignedRange(SV).print(OS); 11524 } 11525 11526 const Loop *L = LI.getLoopFor(I.getParent()); 11527 11528 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11529 if (AtUse != SV) { 11530 OS << " --> "; 11531 AtUse->print(OS); 11532 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11533 OS << " U: "; 11534 SE.getUnsignedRange(AtUse).print(OS); 11535 OS << " S: "; 11536 SE.getSignedRange(AtUse).print(OS); 11537 } 11538 } 11539 11540 if (L) { 11541 OS << "\t\t" "Exits: "; 11542 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11543 if (!SE.isLoopInvariant(ExitValue, L)) { 11544 OS << "<<Unknown>>"; 11545 } else { 11546 OS << *ExitValue; 11547 } 11548 11549 bool First = true; 11550 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11551 if (First) { 11552 OS << "\t\t" "LoopDispositions: { "; 11553 First = false; 11554 } else { 11555 OS << ", "; 11556 } 11557 11558 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11559 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11560 } 11561 11562 for (auto *InnerL : depth_first(L)) { 11563 if (InnerL == L) 11564 continue; 11565 if (First) { 11566 OS << "\t\t" "LoopDispositions: { "; 11567 First = false; 11568 } else { 11569 OS << ", "; 11570 } 11571 11572 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11573 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11574 } 11575 11576 OS << " }"; 11577 } 11578 11579 OS << "\n"; 11580 } 11581 11582 OS << "Determining loop execution counts for: "; 11583 F.printAsOperand(OS, /*PrintType=*/false); 11584 OS << "\n"; 11585 for (Loop *I : LI) 11586 PrintLoopInfo(OS, &SE, I); 11587 } 11588 11589 ScalarEvolution::LoopDisposition 11590 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11591 auto &Values = LoopDispositions[S]; 11592 for (auto &V : Values) { 11593 if (V.getPointer() == L) 11594 return V.getInt(); 11595 } 11596 Values.emplace_back(L, LoopVariant); 11597 LoopDisposition D = computeLoopDisposition(S, L); 11598 auto &Values2 = LoopDispositions[S]; 11599 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11600 if (V.getPointer() == L) { 11601 V.setInt(D); 11602 break; 11603 } 11604 } 11605 return D; 11606 } 11607 11608 ScalarEvolution::LoopDisposition 11609 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11610 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11611 case scConstant: 11612 return LoopInvariant; 11613 case scTruncate: 11614 case scZeroExtend: 11615 case scSignExtend: 11616 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11617 case scAddRecExpr: { 11618 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11619 11620 // If L is the addrec's loop, it's computable. 11621 if (AR->getLoop() == L) 11622 return LoopComputable; 11623 11624 // Add recurrences are never invariant in the function-body (null loop). 11625 if (!L) 11626 return LoopVariant; 11627 11628 // Everything that is not defined at loop entry is variant. 11629 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11630 return LoopVariant; 11631 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11632 " dominate the contained loop's header?"); 11633 11634 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11635 if (AR->getLoop()->contains(L)) 11636 return LoopInvariant; 11637 11638 // This recurrence is variant w.r.t. L if any of its operands 11639 // are variant. 11640 for (auto *Op : AR->operands()) 11641 if (!isLoopInvariant(Op, L)) 11642 return LoopVariant; 11643 11644 // Otherwise it's loop-invariant. 11645 return LoopInvariant; 11646 } 11647 case scAddExpr: 11648 case scMulExpr: 11649 case scUMaxExpr: 11650 case scSMaxExpr: 11651 case scUMinExpr: 11652 case scSMinExpr: { 11653 bool HasVarying = false; 11654 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11655 LoopDisposition D = getLoopDisposition(Op, L); 11656 if (D == LoopVariant) 11657 return LoopVariant; 11658 if (D == LoopComputable) 11659 HasVarying = true; 11660 } 11661 return HasVarying ? LoopComputable : LoopInvariant; 11662 } 11663 case scUDivExpr: { 11664 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11665 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11666 if (LD == LoopVariant) 11667 return LoopVariant; 11668 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11669 if (RD == LoopVariant) 11670 return LoopVariant; 11671 return (LD == LoopInvariant && RD == LoopInvariant) ? 11672 LoopInvariant : LoopComputable; 11673 } 11674 case scUnknown: 11675 // All non-instruction values are loop invariant. All instructions are loop 11676 // invariant if they are not contained in the specified loop. 11677 // Instructions are never considered invariant in the function body 11678 // (null loop) because they are defined within the "loop". 11679 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11680 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11681 return LoopInvariant; 11682 case scCouldNotCompute: 11683 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11684 } 11685 llvm_unreachable("Unknown SCEV kind!"); 11686 } 11687 11688 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11689 return getLoopDisposition(S, L) == LoopInvariant; 11690 } 11691 11692 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11693 return getLoopDisposition(S, L) == LoopComputable; 11694 } 11695 11696 ScalarEvolution::BlockDisposition 11697 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11698 auto &Values = BlockDispositions[S]; 11699 for (auto &V : Values) { 11700 if (V.getPointer() == BB) 11701 return V.getInt(); 11702 } 11703 Values.emplace_back(BB, DoesNotDominateBlock); 11704 BlockDisposition D = computeBlockDisposition(S, BB); 11705 auto &Values2 = BlockDispositions[S]; 11706 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11707 if (V.getPointer() == BB) { 11708 V.setInt(D); 11709 break; 11710 } 11711 } 11712 return D; 11713 } 11714 11715 ScalarEvolution::BlockDisposition 11716 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11717 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11718 case scConstant: 11719 return ProperlyDominatesBlock; 11720 case scTruncate: 11721 case scZeroExtend: 11722 case scSignExtend: 11723 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11724 case scAddRecExpr: { 11725 // This uses a "dominates" query instead of "properly dominates" query 11726 // to test for proper dominance too, because the instruction which 11727 // produces the addrec's value is a PHI, and a PHI effectively properly 11728 // dominates its entire containing block. 11729 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11730 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11731 return DoesNotDominateBlock; 11732 11733 // Fall through into SCEVNAryExpr handling. 11734 LLVM_FALLTHROUGH; 11735 } 11736 case scAddExpr: 11737 case scMulExpr: 11738 case scUMaxExpr: 11739 case scSMaxExpr: 11740 case scUMinExpr: 11741 case scSMinExpr: { 11742 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11743 bool Proper = true; 11744 for (const SCEV *NAryOp : NAry->operands()) { 11745 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11746 if (D == DoesNotDominateBlock) 11747 return DoesNotDominateBlock; 11748 if (D == DominatesBlock) 11749 Proper = false; 11750 } 11751 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11752 } 11753 case scUDivExpr: { 11754 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11755 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11756 BlockDisposition LD = getBlockDisposition(LHS, BB); 11757 if (LD == DoesNotDominateBlock) 11758 return DoesNotDominateBlock; 11759 BlockDisposition RD = getBlockDisposition(RHS, BB); 11760 if (RD == DoesNotDominateBlock) 11761 return DoesNotDominateBlock; 11762 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11763 ProperlyDominatesBlock : DominatesBlock; 11764 } 11765 case scUnknown: 11766 if (Instruction *I = 11767 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11768 if (I->getParent() == BB) 11769 return DominatesBlock; 11770 if (DT.properlyDominates(I->getParent(), BB)) 11771 return ProperlyDominatesBlock; 11772 return DoesNotDominateBlock; 11773 } 11774 return ProperlyDominatesBlock; 11775 case scCouldNotCompute: 11776 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11777 } 11778 llvm_unreachable("Unknown SCEV kind!"); 11779 } 11780 11781 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11782 return getBlockDisposition(S, BB) >= DominatesBlock; 11783 } 11784 11785 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11786 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11787 } 11788 11789 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11790 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11791 } 11792 11793 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11794 auto IsS = [&](const SCEV *X) { return S == X; }; 11795 auto ContainsS = [&](const SCEV *X) { 11796 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11797 }; 11798 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11799 } 11800 11801 void 11802 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11803 ValuesAtScopes.erase(S); 11804 LoopDispositions.erase(S); 11805 BlockDispositions.erase(S); 11806 UnsignedRanges.erase(S); 11807 SignedRanges.erase(S); 11808 ExprValueMap.erase(S); 11809 HasRecMap.erase(S); 11810 MinTrailingZerosCache.erase(S); 11811 11812 for (auto I = PredicatedSCEVRewrites.begin(); 11813 I != PredicatedSCEVRewrites.end();) { 11814 std::pair<const SCEV *, const Loop *> Entry = I->first; 11815 if (Entry.first == S) 11816 PredicatedSCEVRewrites.erase(I++); 11817 else 11818 ++I; 11819 } 11820 11821 auto RemoveSCEVFromBackedgeMap = 11822 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11823 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11824 BackedgeTakenInfo &BEInfo = I->second; 11825 if (BEInfo.hasOperand(S, this)) { 11826 BEInfo.clear(); 11827 Map.erase(I++); 11828 } else 11829 ++I; 11830 } 11831 }; 11832 11833 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11834 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11835 } 11836 11837 void 11838 ScalarEvolution::getUsedLoops(const SCEV *S, 11839 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11840 struct FindUsedLoops { 11841 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11842 : LoopsUsed(LoopsUsed) {} 11843 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11844 bool follow(const SCEV *S) { 11845 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11846 LoopsUsed.insert(AR->getLoop()); 11847 return true; 11848 } 11849 11850 bool isDone() const { return false; } 11851 }; 11852 11853 FindUsedLoops F(LoopsUsed); 11854 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11855 } 11856 11857 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11858 SmallPtrSet<const Loop *, 8> LoopsUsed; 11859 getUsedLoops(S, LoopsUsed); 11860 for (auto *L : LoopsUsed) 11861 LoopUsers[L].push_back(S); 11862 } 11863 11864 void ScalarEvolution::verify() const { 11865 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11866 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11867 11868 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11869 11870 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11871 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11872 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11873 11874 const SCEV *visitConstant(const SCEVConstant *Constant) { 11875 return SE.getConstant(Constant->getAPInt()); 11876 } 11877 11878 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11879 return SE.getUnknown(Expr->getValue()); 11880 } 11881 11882 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11883 return SE.getCouldNotCompute(); 11884 } 11885 }; 11886 11887 SCEVMapper SCM(SE2); 11888 11889 while (!LoopStack.empty()) { 11890 auto *L = LoopStack.pop_back_val(); 11891 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11892 11893 auto *CurBECount = SCM.visit( 11894 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11895 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11896 11897 if (CurBECount == SE2.getCouldNotCompute() || 11898 NewBECount == SE2.getCouldNotCompute()) { 11899 // NB! This situation is legal, but is very suspicious -- whatever pass 11900 // change the loop to make a trip count go from could not compute to 11901 // computable or vice-versa *should have* invalidated SCEV. However, we 11902 // choose not to assert here (for now) since we don't want false 11903 // positives. 11904 continue; 11905 } 11906 11907 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11908 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11909 // not propagate undef aggressively). This means we can (and do) fail 11910 // verification in cases where a transform makes the trip count of a loop 11911 // go from "undef" to "undef+1" (say). The transform is fine, since in 11912 // both cases the loop iterates "undef" times, but SCEV thinks we 11913 // increased the trip count of the loop by 1 incorrectly. 11914 continue; 11915 } 11916 11917 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11918 SE.getTypeSizeInBits(NewBECount->getType())) 11919 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11920 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11921 SE.getTypeSizeInBits(NewBECount->getType())) 11922 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11923 11924 auto *ConstantDelta = 11925 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11926 11927 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11928 dbgs() << "Trip Count Changed!\n"; 11929 dbgs() << "Old: " << *CurBECount << "\n"; 11930 dbgs() << "New: " << *NewBECount << "\n"; 11931 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11932 std::abort(); 11933 } 11934 } 11935 } 11936 11937 bool ScalarEvolution::invalidate( 11938 Function &F, const PreservedAnalyses &PA, 11939 FunctionAnalysisManager::Invalidator &Inv) { 11940 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11941 // of its dependencies is invalidated. 11942 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11943 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11944 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11945 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11946 Inv.invalidate<LoopAnalysis>(F, PA); 11947 } 11948 11949 AnalysisKey ScalarEvolutionAnalysis::Key; 11950 11951 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11952 FunctionAnalysisManager &AM) { 11953 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11954 AM.getResult<AssumptionAnalysis>(F), 11955 AM.getResult<DominatorTreeAnalysis>(F), 11956 AM.getResult<LoopAnalysis>(F)); 11957 } 11958 11959 PreservedAnalyses 11960 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11961 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11962 return PreservedAnalyses::all(); 11963 } 11964 11965 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11966 "Scalar Evolution Analysis", false, true) 11967 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11968 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11969 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11970 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11971 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11972 "Scalar Evolution Analysis", false, true) 11973 11974 char ScalarEvolutionWrapperPass::ID = 0; 11975 11976 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11977 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11978 } 11979 11980 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11981 SE.reset(new ScalarEvolution( 11982 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 11983 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11984 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11985 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11986 return false; 11987 } 11988 11989 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11990 11991 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11992 SE->print(OS); 11993 } 11994 11995 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11996 if (!VerifySCEV) 11997 return; 11998 11999 SE->verify(); 12000 } 12001 12002 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12003 AU.setPreservesAll(); 12004 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12005 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12006 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12007 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12008 } 12009 12010 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12011 const SCEV *RHS) { 12012 FoldingSetNodeID ID; 12013 assert(LHS->getType() == RHS->getType() && 12014 "Type mismatch between LHS and RHS"); 12015 // Unique this node based on the arguments 12016 ID.AddInteger(SCEVPredicate::P_Equal); 12017 ID.AddPointer(LHS); 12018 ID.AddPointer(RHS); 12019 void *IP = nullptr; 12020 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12021 return S; 12022 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12023 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12024 UniquePreds.InsertNode(Eq, IP); 12025 return Eq; 12026 } 12027 12028 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12029 const SCEVAddRecExpr *AR, 12030 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12031 FoldingSetNodeID ID; 12032 // Unique this node based on the arguments 12033 ID.AddInteger(SCEVPredicate::P_Wrap); 12034 ID.AddPointer(AR); 12035 ID.AddInteger(AddedFlags); 12036 void *IP = nullptr; 12037 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12038 return S; 12039 auto *OF = new (SCEVAllocator) 12040 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12041 UniquePreds.InsertNode(OF, IP); 12042 return OF; 12043 } 12044 12045 namespace { 12046 12047 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12048 public: 12049 12050 /// Rewrites \p S in the context of a loop L and the SCEV predication 12051 /// infrastructure. 12052 /// 12053 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12054 /// equivalences present in \p Pred. 12055 /// 12056 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12057 /// \p NewPreds such that the result will be an AddRecExpr. 12058 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12059 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12060 SCEVUnionPredicate *Pred) { 12061 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12062 return Rewriter.visit(S); 12063 } 12064 12065 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12066 if (Pred) { 12067 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12068 for (auto *Pred : ExprPreds) 12069 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12070 if (IPred->getLHS() == Expr) 12071 return IPred->getRHS(); 12072 } 12073 return convertToAddRecWithPreds(Expr); 12074 } 12075 12076 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12077 const SCEV *Operand = visit(Expr->getOperand()); 12078 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12079 if (AR && AR->getLoop() == L && AR->isAffine()) { 12080 // This couldn't be folded because the operand didn't have the nuw 12081 // flag. Add the nusw flag as an assumption that we could make. 12082 const SCEV *Step = AR->getStepRecurrence(SE); 12083 Type *Ty = Expr->getType(); 12084 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12085 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12086 SE.getSignExtendExpr(Step, Ty), L, 12087 AR->getNoWrapFlags()); 12088 } 12089 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12090 } 12091 12092 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12093 const SCEV *Operand = visit(Expr->getOperand()); 12094 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12095 if (AR && AR->getLoop() == L && AR->isAffine()) { 12096 // This couldn't be folded because the operand didn't have the nsw 12097 // flag. Add the nssw flag as an assumption that we could make. 12098 const SCEV *Step = AR->getStepRecurrence(SE); 12099 Type *Ty = Expr->getType(); 12100 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12101 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12102 SE.getSignExtendExpr(Step, Ty), L, 12103 AR->getNoWrapFlags()); 12104 } 12105 return SE.getSignExtendExpr(Operand, Expr->getType()); 12106 } 12107 12108 private: 12109 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12110 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12111 SCEVUnionPredicate *Pred) 12112 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12113 12114 bool addOverflowAssumption(const SCEVPredicate *P) { 12115 if (!NewPreds) { 12116 // Check if we've already made this assumption. 12117 return Pred && Pred->implies(P); 12118 } 12119 NewPreds->insert(P); 12120 return true; 12121 } 12122 12123 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12124 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12125 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12126 return addOverflowAssumption(A); 12127 } 12128 12129 // If \p Expr represents a PHINode, we try to see if it can be represented 12130 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12131 // to add this predicate as a runtime overflow check, we return the AddRec. 12132 // If \p Expr does not meet these conditions (is not a PHI node, or we 12133 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12134 // return \p Expr. 12135 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12136 if (!isa<PHINode>(Expr->getValue())) 12137 return Expr; 12138 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12139 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12140 if (!PredicatedRewrite) 12141 return Expr; 12142 for (auto *P : PredicatedRewrite->second){ 12143 // Wrap predicates from outer loops are not supported. 12144 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12145 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12146 if (L != AR->getLoop()) 12147 return Expr; 12148 } 12149 if (!addOverflowAssumption(P)) 12150 return Expr; 12151 } 12152 return PredicatedRewrite->first; 12153 } 12154 12155 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12156 SCEVUnionPredicate *Pred; 12157 const Loop *L; 12158 }; 12159 12160 } // end anonymous namespace 12161 12162 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12163 SCEVUnionPredicate &Preds) { 12164 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12165 } 12166 12167 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12168 const SCEV *S, const Loop *L, 12169 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12170 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12171 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12172 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12173 12174 if (!AddRec) 12175 return nullptr; 12176 12177 // Since the transformation was successful, we can now transfer the SCEV 12178 // predicates. 12179 for (auto *P : TransformPreds) 12180 Preds.insert(P); 12181 12182 return AddRec; 12183 } 12184 12185 /// SCEV predicates 12186 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12187 SCEVPredicateKind Kind) 12188 : FastID(ID), Kind(Kind) {} 12189 12190 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12191 const SCEV *LHS, const SCEV *RHS) 12192 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12193 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12194 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12195 } 12196 12197 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12198 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12199 12200 if (!Op) 12201 return false; 12202 12203 return Op->LHS == LHS && Op->RHS == RHS; 12204 } 12205 12206 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12207 12208 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12209 12210 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12211 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12212 } 12213 12214 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12215 const SCEVAddRecExpr *AR, 12216 IncrementWrapFlags Flags) 12217 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12218 12219 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12220 12221 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12222 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12223 12224 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12225 } 12226 12227 bool SCEVWrapPredicate::isAlwaysTrue() const { 12228 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12229 IncrementWrapFlags IFlags = Flags; 12230 12231 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12232 IFlags = clearFlags(IFlags, IncrementNSSW); 12233 12234 return IFlags == IncrementAnyWrap; 12235 } 12236 12237 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12238 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12239 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12240 OS << "<nusw>"; 12241 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12242 OS << "<nssw>"; 12243 OS << "\n"; 12244 } 12245 12246 SCEVWrapPredicate::IncrementWrapFlags 12247 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12248 ScalarEvolution &SE) { 12249 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12250 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12251 12252 // We can safely transfer the NSW flag as NSSW. 12253 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12254 ImpliedFlags = IncrementNSSW; 12255 12256 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12257 // If the increment is positive, the SCEV NUW flag will also imply the 12258 // WrapPredicate NUSW flag. 12259 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12260 if (Step->getValue()->getValue().isNonNegative()) 12261 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12262 } 12263 12264 return ImpliedFlags; 12265 } 12266 12267 /// Union predicates don't get cached so create a dummy set ID for it. 12268 SCEVUnionPredicate::SCEVUnionPredicate() 12269 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12270 12271 bool SCEVUnionPredicate::isAlwaysTrue() const { 12272 return all_of(Preds, 12273 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12274 } 12275 12276 ArrayRef<const SCEVPredicate *> 12277 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12278 auto I = SCEVToPreds.find(Expr); 12279 if (I == SCEVToPreds.end()) 12280 return ArrayRef<const SCEVPredicate *>(); 12281 return I->second; 12282 } 12283 12284 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12285 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12286 return all_of(Set->Preds, 12287 [this](const SCEVPredicate *I) { return this->implies(I); }); 12288 12289 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12290 if (ScevPredsIt == SCEVToPreds.end()) 12291 return false; 12292 auto &SCEVPreds = ScevPredsIt->second; 12293 12294 return any_of(SCEVPreds, 12295 [N](const SCEVPredicate *I) { return I->implies(N); }); 12296 } 12297 12298 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12299 12300 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12301 for (auto Pred : Preds) 12302 Pred->print(OS, Depth); 12303 } 12304 12305 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12306 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12307 for (auto Pred : Set->Preds) 12308 add(Pred); 12309 return; 12310 } 12311 12312 if (implies(N)) 12313 return; 12314 12315 const SCEV *Key = N->getExpr(); 12316 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12317 " associated expression!"); 12318 12319 SCEVToPreds[Key].push_back(N); 12320 Preds.push_back(N); 12321 } 12322 12323 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12324 Loop &L) 12325 : SE(SE), L(L) {} 12326 12327 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12328 const SCEV *Expr = SE.getSCEV(V); 12329 RewriteEntry &Entry = RewriteMap[Expr]; 12330 12331 // If we already have an entry and the version matches, return it. 12332 if (Entry.second && Generation == Entry.first) 12333 return Entry.second; 12334 12335 // We found an entry but it's stale. Rewrite the stale entry 12336 // according to the current predicate. 12337 if (Entry.second) 12338 Expr = Entry.second; 12339 12340 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12341 Entry = {Generation, NewSCEV}; 12342 12343 return NewSCEV; 12344 } 12345 12346 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12347 if (!BackedgeCount) { 12348 SCEVUnionPredicate BackedgePred; 12349 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12350 addPredicate(BackedgePred); 12351 } 12352 return BackedgeCount; 12353 } 12354 12355 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12356 if (Preds.implies(&Pred)) 12357 return; 12358 Preds.add(&Pred); 12359 updateGeneration(); 12360 } 12361 12362 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12363 return Preds; 12364 } 12365 12366 void PredicatedScalarEvolution::updateGeneration() { 12367 // If the generation number wrapped recompute everything. 12368 if (++Generation == 0) { 12369 for (auto &II : RewriteMap) { 12370 const SCEV *Rewritten = II.second.second; 12371 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12372 } 12373 } 12374 } 12375 12376 void PredicatedScalarEvolution::setNoOverflow( 12377 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12378 const SCEV *Expr = getSCEV(V); 12379 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12380 12381 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12382 12383 // Clear the statically implied flags. 12384 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12385 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12386 12387 auto II = FlagsMap.insert({V, Flags}); 12388 if (!II.second) 12389 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12390 } 12391 12392 bool PredicatedScalarEvolution::hasNoOverflow( 12393 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12394 const SCEV *Expr = getSCEV(V); 12395 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12396 12397 Flags = SCEVWrapPredicate::clearFlags( 12398 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12399 12400 auto II = FlagsMap.find(V); 12401 12402 if (II != FlagsMap.end()) 12403 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12404 12405 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12406 } 12407 12408 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12409 const SCEV *Expr = this->getSCEV(V); 12410 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12411 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12412 12413 if (!New) 12414 return nullptr; 12415 12416 for (auto *P : NewPreds) 12417 Preds.add(P); 12418 12419 updateGeneration(); 12420 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12421 return New; 12422 } 12423 12424 PredicatedScalarEvolution::PredicatedScalarEvolution( 12425 const PredicatedScalarEvolution &Init) 12426 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12427 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12428 for (const auto &I : Init.FlagsMap) 12429 FlagsMap.insert(I); 12430 } 12431 12432 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12433 // For each block. 12434 for (auto *BB : L.getBlocks()) 12435 for (auto &I : *BB) { 12436 if (!SE.isSCEVable(I.getType())) 12437 continue; 12438 12439 auto *Expr = SE.getSCEV(&I); 12440 auto II = RewriteMap.find(Expr); 12441 12442 if (II == RewriteMap.end()) 12443 continue; 12444 12445 // Don't print things that are not interesting. 12446 if (II->second.second == Expr) 12447 continue; 12448 12449 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12450 OS.indent(Depth + 2) << *Expr << "\n"; 12451 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12452 } 12453 } 12454 12455 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12456 // arbitrary expressions. 12457 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12458 // 4, A / B becomes X / 8). 12459 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12460 const SCEV *&RHS) { 12461 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12462 if (Add == nullptr || Add->getNumOperands() != 2) 12463 return false; 12464 12465 const SCEV *A = Add->getOperand(1); 12466 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12467 12468 if (Mul == nullptr) 12469 return false; 12470 12471 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12472 // (SomeExpr + (-(SomeExpr / B) * B)). 12473 if (Expr == getURemExpr(A, B)) { 12474 LHS = A; 12475 RHS = B; 12476 return true; 12477 } 12478 return false; 12479 }; 12480 12481 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12482 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12483 return MatchURemWithDivisor(Mul->getOperand(1)) || 12484 MatchURemWithDivisor(Mul->getOperand(2)); 12485 12486 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12487 if (Mul->getNumOperands() == 2) 12488 return MatchURemWithDivisor(Mul->getOperand(1)) || 12489 MatchURemWithDivisor(Mul->getOperand(0)) || 12490 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12491 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12492 return false; 12493 } 12494