1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumArrayLenItCounts, 143 "Number of trip counts computed with array length"); 144 STATISTIC(NumTripCountsComputed, 145 "Number of loops with predictable loop counts"); 146 STATISTIC(NumTripCountsNotComputed, 147 "Number of loops without predictable loop counts"); 148 STATISTIC(NumBruteForceTripCountsComputed, 149 "Number of loops with trip counts computed by force"); 150 151 static cl::opt<unsigned> 152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 153 cl::ZeroOrMore, 154 cl::desc("Maximum number of iterations SCEV will " 155 "symbolically execute a constant " 156 "derived loop"), 157 cl::init(100)); 158 159 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 160 static cl::opt<bool> VerifySCEV( 161 "verify-scev", cl::Hidden, 162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 163 static cl::opt<bool> VerifySCEVStrict( 164 "verify-scev-strict", cl::Hidden, 165 cl::desc("Enable stricter verification with -verify-scev is passed")); 166 static cl::opt<bool> 167 VerifySCEVMap("verify-scev-maps", cl::Hidden, 168 cl::desc("Verify no dangling value in ScalarEvolution's " 169 "ExprValueMap (slow)")); 170 171 static cl::opt<bool> VerifyIR( 172 "scev-verify-ir", cl::Hidden, 173 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 174 cl::init(false)); 175 176 static cl::opt<unsigned> MulOpsInlineThreshold( 177 "scev-mulops-inline-threshold", cl::Hidden, 178 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 179 cl::init(32)); 180 181 static cl::opt<unsigned> AddOpsInlineThreshold( 182 "scev-addops-inline-threshold", cl::Hidden, 183 cl::desc("Threshold for inlining addition operands into a SCEV"), 184 cl::init(500)); 185 186 static cl::opt<unsigned> MaxSCEVCompareDepth( 187 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 188 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 189 cl::init(32)); 190 191 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 192 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 193 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 194 cl::init(2)); 195 196 static cl::opt<unsigned> MaxValueCompareDepth( 197 "scalar-evolution-max-value-compare-depth", cl::Hidden, 198 cl::desc("Maximum depth of recursive value complexity comparisons"), 199 cl::init(2)); 200 201 static cl::opt<unsigned> 202 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 203 cl::desc("Maximum depth of recursive arithmetics"), 204 cl::init(32)); 205 206 static cl::opt<unsigned> MaxConstantEvolvingDepth( 207 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 208 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 209 210 static cl::opt<unsigned> 211 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 212 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 213 cl::init(8)); 214 215 static cl::opt<unsigned> 216 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 217 cl::desc("Max coefficients in AddRec during evolving"), 218 cl::init(8)); 219 220 static cl::opt<unsigned> 221 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 222 cl::desc("Size of the expression which is considered huge"), 223 cl::init(4096)); 224 225 static cl::opt<bool> 226 ClassifyExpressions("scalar-evolution-classify-expressions", 227 cl::Hidden, cl::init(true), 228 cl::desc("When printing analysis, include information on every instruction")); 229 230 static cl::opt<bool> UseExpensiveRangeSharpening( 231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 232 cl::init(false), 233 cl::desc("Use more powerful methods of sharpening expression ranges. May " 234 "be costly in terms of compile time")); 235 236 //===----------------------------------------------------------------------===// 237 // SCEV class definitions 238 //===----------------------------------------------------------------------===// 239 240 //===----------------------------------------------------------------------===// 241 // Implementation of the SCEV class. 242 // 243 244 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 245 LLVM_DUMP_METHOD void SCEV::dump() const { 246 print(dbgs()); 247 dbgs() << '\n'; 248 } 249 #endif 250 251 void SCEV::print(raw_ostream &OS) const { 252 switch (getSCEVType()) { 253 case scConstant: 254 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 255 return; 256 case scPtrToInt: { 257 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 258 const SCEV *Op = PtrToInt->getOperand(); 259 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 260 << *PtrToInt->getType() << ")"; 261 return; 262 } 263 case scTruncate: { 264 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 265 const SCEV *Op = Trunc->getOperand(); 266 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 267 << *Trunc->getType() << ")"; 268 return; 269 } 270 case scZeroExtend: { 271 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 272 const SCEV *Op = ZExt->getOperand(); 273 OS << "(zext " << *Op->getType() << " " << *Op << " to " 274 << *ZExt->getType() << ")"; 275 return; 276 } 277 case scSignExtend: { 278 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 279 const SCEV *Op = SExt->getOperand(); 280 OS << "(sext " << *Op->getType() << " " << *Op << " to " 281 << *SExt->getType() << ")"; 282 return; 283 } 284 case scAddRecExpr: { 285 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 286 OS << "{" << *AR->getOperand(0); 287 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 288 OS << ",+," << *AR->getOperand(i); 289 OS << "}<"; 290 if (AR->hasNoUnsignedWrap()) 291 OS << "nuw><"; 292 if (AR->hasNoSignedWrap()) 293 OS << "nsw><"; 294 if (AR->hasNoSelfWrap() && 295 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 296 OS << "nw><"; 297 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 298 OS << ">"; 299 return; 300 } 301 case scAddExpr: 302 case scMulExpr: 303 case scUMaxExpr: 304 case scSMaxExpr: 305 case scUMinExpr: 306 case scSMinExpr: { 307 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 308 const char *OpStr = nullptr; 309 switch (NAry->getSCEVType()) { 310 case scAddExpr: OpStr = " + "; break; 311 case scMulExpr: OpStr = " * "; break; 312 case scUMaxExpr: OpStr = " umax "; break; 313 case scSMaxExpr: OpStr = " smax "; break; 314 case scUMinExpr: 315 OpStr = " umin "; 316 break; 317 case scSMinExpr: 318 OpStr = " smin "; 319 break; 320 default: 321 llvm_unreachable("There are no other nary expression types."); 322 } 323 OS << "("; 324 ListSeparator LS(OpStr); 325 for (const SCEV *Op : NAry->operands()) 326 OS << LS << *Op; 327 OS << ")"; 328 switch (NAry->getSCEVType()) { 329 case scAddExpr: 330 case scMulExpr: 331 if (NAry->hasNoUnsignedWrap()) 332 OS << "<nuw>"; 333 if (NAry->hasNoSignedWrap()) 334 OS << "<nsw>"; 335 break; 336 default: 337 // Nothing to print for other nary expressions. 338 break; 339 } 340 return; 341 } 342 case scUDivExpr: { 343 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 344 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 345 return; 346 } 347 case scUnknown: { 348 const SCEVUnknown *U = cast<SCEVUnknown>(this); 349 Type *AllocTy; 350 if (U->isSizeOf(AllocTy)) { 351 OS << "sizeof(" << *AllocTy << ")"; 352 return; 353 } 354 if (U->isAlignOf(AllocTy)) { 355 OS << "alignof(" << *AllocTy << ")"; 356 return; 357 } 358 359 Type *CTy; 360 Constant *FieldNo; 361 if (U->isOffsetOf(CTy, FieldNo)) { 362 OS << "offsetof(" << *CTy << ", "; 363 FieldNo->printAsOperand(OS, false); 364 OS << ")"; 365 return; 366 } 367 368 // Otherwise just print it normally. 369 U->getValue()->printAsOperand(OS, false); 370 return; 371 } 372 case scCouldNotCompute: 373 OS << "***COULDNOTCOMPUTE***"; 374 return; 375 } 376 llvm_unreachable("Unknown SCEV kind!"); 377 } 378 379 Type *SCEV::getType() const { 380 switch (getSCEVType()) { 381 case scConstant: 382 return cast<SCEVConstant>(this)->getType(); 383 case scPtrToInt: 384 case scTruncate: 385 case scZeroExtend: 386 case scSignExtend: 387 return cast<SCEVCastExpr>(this)->getType(); 388 case scAddRecExpr: 389 return cast<SCEVAddRecExpr>(this)->getType(); 390 case scMulExpr: 391 return cast<SCEVMulExpr>(this)->getType(); 392 case scUMaxExpr: 393 case scSMaxExpr: 394 case scUMinExpr: 395 case scSMinExpr: 396 return cast<SCEVMinMaxExpr>(this)->getType(); 397 case scAddExpr: 398 return cast<SCEVAddExpr>(this)->getType(); 399 case scUDivExpr: 400 return cast<SCEVUDivExpr>(this)->getType(); 401 case scUnknown: 402 return cast<SCEVUnknown>(this)->getType(); 403 case scCouldNotCompute: 404 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 405 } 406 llvm_unreachable("Unknown SCEV kind!"); 407 } 408 409 bool SCEV::isZero() const { 410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 411 return SC->getValue()->isZero(); 412 return false; 413 } 414 415 bool SCEV::isOne() const { 416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 417 return SC->getValue()->isOne(); 418 return false; 419 } 420 421 bool SCEV::isAllOnesValue() const { 422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 423 return SC->getValue()->isMinusOne(); 424 return false; 425 } 426 427 bool SCEV::isNonConstantNegative() const { 428 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 429 if (!Mul) return false; 430 431 // If there is a constant factor, it will be first. 432 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 433 if (!SC) return false; 434 435 // Return true if the value is negative, this matches things like (-42 * V). 436 return SC->getAPInt().isNegative(); 437 } 438 439 SCEVCouldNotCompute::SCEVCouldNotCompute() : 440 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 441 442 bool SCEVCouldNotCompute::classof(const SCEV *S) { 443 return S->getSCEVType() == scCouldNotCompute; 444 } 445 446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 447 FoldingSetNodeID ID; 448 ID.AddInteger(scConstant); 449 ID.AddPointer(V); 450 void *IP = nullptr; 451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 452 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 453 UniqueSCEVs.InsertNode(S, IP); 454 return S; 455 } 456 457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 458 return getConstant(ConstantInt::get(getContext(), Val)); 459 } 460 461 const SCEV * 462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 463 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 464 return getConstant(ConstantInt::get(ITy, V, isSigned)); 465 } 466 467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 468 const SCEV *op, Type *ty) 469 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 470 Operands[0] = op; 471 } 472 473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 474 Type *ITy) 475 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 476 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 477 "Must be a non-bit-width-changing pointer-to-integer cast!"); 478 } 479 480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 481 SCEVTypes SCEVTy, const SCEV *op, 482 Type *ty) 483 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 484 485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 486 Type *ty) 487 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 488 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 489 "Cannot truncate non-integer value!"); 490 } 491 492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 493 const SCEV *op, Type *ty) 494 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 495 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 496 "Cannot zero extend non-integer value!"); 497 } 498 499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 500 const SCEV *op, Type *ty) 501 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 502 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 503 "Cannot sign extend non-integer value!"); 504 } 505 506 void SCEVUnknown::deleted() { 507 // Clear this SCEVUnknown from various maps. 508 SE->forgetMemoizedResults(this); 509 510 // Remove this SCEVUnknown from the uniquing map. 511 SE->UniqueSCEVs.RemoveNode(this); 512 513 // Release the value. 514 setValPtr(nullptr); 515 } 516 517 void SCEVUnknown::allUsesReplacedWith(Value *New) { 518 // Remove this SCEVUnknown from the uniquing map. 519 SE->UniqueSCEVs.RemoveNode(this); 520 521 // Update this SCEVUnknown to point to the new value. This is needed 522 // because there may still be outstanding SCEVs which still point to 523 // this SCEVUnknown. 524 setValPtr(New); 525 } 526 527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 528 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 529 if (VCE->getOpcode() == Instruction::PtrToInt) 530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 531 if (CE->getOpcode() == Instruction::GetElementPtr && 532 CE->getOperand(0)->isNullValue() && 533 CE->getNumOperands() == 2) 534 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 535 if (CI->isOne()) { 536 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 537 return true; 538 } 539 540 return false; 541 } 542 543 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 544 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 545 if (VCE->getOpcode() == Instruction::PtrToInt) 546 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 547 if (CE->getOpcode() == Instruction::GetElementPtr && 548 CE->getOperand(0)->isNullValue()) { 549 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 550 if (StructType *STy = dyn_cast<StructType>(Ty)) 551 if (!STy->isPacked() && 552 CE->getNumOperands() == 3 && 553 CE->getOperand(1)->isNullValue()) { 554 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 555 if (CI->isOne() && 556 STy->getNumElements() == 2 && 557 STy->getElementType(0)->isIntegerTy(1)) { 558 AllocTy = STy->getElementType(1); 559 return true; 560 } 561 } 562 } 563 564 return false; 565 } 566 567 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 568 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 569 if (VCE->getOpcode() == Instruction::PtrToInt) 570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 571 if (CE->getOpcode() == Instruction::GetElementPtr && 572 CE->getNumOperands() == 3 && 573 CE->getOperand(0)->isNullValue() && 574 CE->getOperand(1)->isNullValue()) { 575 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 576 // Ignore vector types here so that ScalarEvolutionExpander doesn't 577 // emit getelementptrs that index into vectors. 578 if (Ty->isStructTy() || Ty->isArrayTy()) { 579 CTy = Ty; 580 FieldNo = CE->getOperand(2); 581 return true; 582 } 583 } 584 585 return false; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SCEV Utilities 590 //===----------------------------------------------------------------------===// 591 592 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 593 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 594 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 595 /// have been previously deemed to be "equally complex" by this routine. It is 596 /// intended to avoid exponential time complexity in cases like: 597 /// 598 /// %a = f(%x, %y) 599 /// %b = f(%a, %a) 600 /// %c = f(%b, %b) 601 /// 602 /// %d = f(%x, %y) 603 /// %e = f(%d, %d) 604 /// %f = f(%e, %e) 605 /// 606 /// CompareValueComplexity(%f, %c) 607 /// 608 /// Since we do not continue running this routine on expression trees once we 609 /// have seen unequal values, there is no need to track them in the cache. 610 static int 611 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 612 const LoopInfo *const LI, Value *LV, Value *RV, 613 unsigned Depth) { 614 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 615 return 0; 616 617 // Order pointer values after integer values. This helps SCEVExpander form 618 // GEPs. 619 bool LIsPointer = LV->getType()->isPointerTy(), 620 RIsPointer = RV->getType()->isPointerTy(); 621 if (LIsPointer != RIsPointer) 622 return (int)LIsPointer - (int)RIsPointer; 623 624 // Compare getValueID values. 625 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 626 if (LID != RID) 627 return (int)LID - (int)RID; 628 629 // Sort arguments by their position. 630 if (const auto *LA = dyn_cast<Argument>(LV)) { 631 const auto *RA = cast<Argument>(RV); 632 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 633 return (int)LArgNo - (int)RArgNo; 634 } 635 636 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 637 const auto *RGV = cast<GlobalValue>(RV); 638 639 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 640 auto LT = GV->getLinkage(); 641 return !(GlobalValue::isPrivateLinkage(LT) || 642 GlobalValue::isInternalLinkage(LT)); 643 }; 644 645 // Use the names to distinguish the two values, but only if the 646 // names are semantically important. 647 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 648 return LGV->getName().compare(RGV->getName()); 649 } 650 651 // For instructions, compare their loop depth, and their operand count. This 652 // is pretty loose. 653 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 654 const auto *RInst = cast<Instruction>(RV); 655 656 // Compare loop depths. 657 const BasicBlock *LParent = LInst->getParent(), 658 *RParent = RInst->getParent(); 659 if (LParent != RParent) { 660 unsigned LDepth = LI->getLoopDepth(LParent), 661 RDepth = LI->getLoopDepth(RParent); 662 if (LDepth != RDepth) 663 return (int)LDepth - (int)RDepth; 664 } 665 666 // Compare the number of operands. 667 unsigned LNumOps = LInst->getNumOperands(), 668 RNumOps = RInst->getNumOperands(); 669 if (LNumOps != RNumOps) 670 return (int)LNumOps - (int)RNumOps; 671 672 for (unsigned Idx : seq(0u, LNumOps)) { 673 int Result = 674 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 675 RInst->getOperand(Idx), Depth + 1); 676 if (Result != 0) 677 return Result; 678 } 679 } 680 681 EqCacheValue.unionSets(LV, RV); 682 return 0; 683 } 684 685 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 686 // than RHS, respectively. A three-way result allows recursive comparisons to be 687 // more efficient. 688 // If the max analysis depth was reached, return None, assuming we do not know 689 // if they are equivalent for sure. 690 static Optional<int> 691 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 692 EquivalenceClasses<const Value *> &EqCacheValue, 693 const LoopInfo *const LI, const SCEV *LHS, 694 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 695 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 696 if (LHS == RHS) 697 return 0; 698 699 // Primarily, sort the SCEVs by their getSCEVType(). 700 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 701 if (LType != RType) 702 return (int)LType - (int)RType; 703 704 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 705 return 0; 706 707 if (Depth > MaxSCEVCompareDepth) 708 return None; 709 710 // Aside from the getSCEVType() ordering, the particular ordering 711 // isn't very important except that it's beneficial to be consistent, 712 // so that (a + b) and (b + a) don't end up as different expressions. 713 switch (LType) { 714 case scUnknown: { 715 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 716 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 717 718 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 719 RU->getValue(), Depth + 1); 720 if (X == 0) 721 EqCacheSCEV.unionSets(LHS, RHS); 722 return X; 723 } 724 725 case scConstant: { 726 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 727 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 728 729 // Compare constant values. 730 const APInt &LA = LC->getAPInt(); 731 const APInt &RA = RC->getAPInt(); 732 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 733 if (LBitWidth != RBitWidth) 734 return (int)LBitWidth - (int)RBitWidth; 735 return LA.ult(RA) ? -1 : 1; 736 } 737 738 case scAddRecExpr: { 739 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 740 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 741 742 // There is always a dominance between two recs that are used by one SCEV, 743 // so we can safely sort recs by loop header dominance. We require such 744 // order in getAddExpr. 745 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 746 if (LLoop != RLoop) { 747 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 748 assert(LHead != RHead && "Two loops share the same header?"); 749 if (DT.dominates(LHead, RHead)) 750 return 1; 751 else 752 assert(DT.dominates(RHead, LHead) && 753 "No dominance between recurrences used by one SCEV?"); 754 return -1; 755 } 756 757 // Addrec complexity grows with operand count. 758 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 759 if (LNumOps != RNumOps) 760 return (int)LNumOps - (int)RNumOps; 761 762 // Lexicographically compare. 763 for (unsigned i = 0; i != LNumOps; ++i) { 764 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 765 LA->getOperand(i), RA->getOperand(i), DT, 766 Depth + 1); 767 if (X != 0) 768 return X; 769 } 770 EqCacheSCEV.unionSets(LHS, RHS); 771 return 0; 772 } 773 774 case scAddExpr: 775 case scMulExpr: 776 case scSMaxExpr: 777 case scUMaxExpr: 778 case scSMinExpr: 779 case scUMinExpr: { 780 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 781 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 782 783 // Lexicographically compare n-ary expressions. 784 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 785 if (LNumOps != RNumOps) 786 return (int)LNumOps - (int)RNumOps; 787 788 for (unsigned i = 0; i != LNumOps; ++i) { 789 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 790 LC->getOperand(i), RC->getOperand(i), DT, 791 Depth + 1); 792 if (X != 0) 793 return X; 794 } 795 EqCacheSCEV.unionSets(LHS, RHS); 796 return 0; 797 } 798 799 case scUDivExpr: { 800 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 801 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 802 803 // Lexicographically compare udiv expressions. 804 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 805 RC->getLHS(), DT, Depth + 1); 806 if (X != 0) 807 return X; 808 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 809 RC->getRHS(), DT, Depth + 1); 810 if (X == 0) 811 EqCacheSCEV.unionSets(LHS, RHS); 812 return X; 813 } 814 815 case scPtrToInt: 816 case scTruncate: 817 case scZeroExtend: 818 case scSignExtend: { 819 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 820 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 821 822 // Compare cast expressions by operand. 823 auto X = 824 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 825 RC->getOperand(), DT, Depth + 1); 826 if (X == 0) 827 EqCacheSCEV.unionSets(LHS, RHS); 828 return X; 829 } 830 831 case scCouldNotCompute: 832 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 833 } 834 llvm_unreachable("Unknown SCEV kind!"); 835 } 836 837 /// Given a list of SCEV objects, order them by their complexity, and group 838 /// objects of the same complexity together by value. When this routine is 839 /// finished, we know that any duplicates in the vector are consecutive and that 840 /// complexity is monotonically increasing. 841 /// 842 /// Note that we go take special precautions to ensure that we get deterministic 843 /// results from this routine. In other words, we don't want the results of 844 /// this to depend on where the addresses of various SCEV objects happened to 845 /// land in memory. 846 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 847 LoopInfo *LI, DominatorTree &DT) { 848 if (Ops.size() < 2) return; // Noop 849 850 EquivalenceClasses<const SCEV *> EqCacheSCEV; 851 EquivalenceClasses<const Value *> EqCacheValue; 852 853 // Whether LHS has provably less complexity than RHS. 854 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 855 auto Complexity = 856 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 857 return Complexity && *Complexity < 0; 858 }; 859 if (Ops.size() == 2) { 860 // This is the common case, which also happens to be trivially simple. 861 // Special case it. 862 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 863 if (IsLessComplex(RHS, LHS)) 864 std::swap(LHS, RHS); 865 return; 866 } 867 868 // Do the rough sort by complexity. 869 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 870 return IsLessComplex(LHS, RHS); 871 }); 872 873 // Now that we are sorted by complexity, group elements of the same 874 // complexity. Note that this is, at worst, N^2, but the vector is likely to 875 // be extremely short in practice. Note that we take this approach because we 876 // do not want to depend on the addresses of the objects we are grouping. 877 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 878 const SCEV *S = Ops[i]; 879 unsigned Complexity = S->getSCEVType(); 880 881 // If there are any objects of the same complexity and same value as this 882 // one, group them. 883 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 884 if (Ops[j] == S) { // Found a duplicate. 885 // Move it to immediately after i'th element. 886 std::swap(Ops[i+1], Ops[j]); 887 ++i; // no need to rescan it. 888 if (i == e-2) return; // Done! 889 } 890 } 891 } 892 } 893 894 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 895 /// least HugeExprThreshold nodes). 896 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 897 return any_of(Ops, [](const SCEV *S) { 898 return S->getExpressionSize() >= HugeExprThreshold; 899 }); 900 } 901 902 //===----------------------------------------------------------------------===// 903 // Simple SCEV method implementations 904 //===----------------------------------------------------------------------===// 905 906 /// Compute BC(It, K). The result has width W. Assume, K > 0. 907 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 908 ScalarEvolution &SE, 909 Type *ResultTy) { 910 // Handle the simplest case efficiently. 911 if (K == 1) 912 return SE.getTruncateOrZeroExtend(It, ResultTy); 913 914 // We are using the following formula for BC(It, K): 915 // 916 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 917 // 918 // Suppose, W is the bitwidth of the return value. We must be prepared for 919 // overflow. Hence, we must assure that the result of our computation is 920 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 921 // safe in modular arithmetic. 922 // 923 // However, this code doesn't use exactly that formula; the formula it uses 924 // is something like the following, where T is the number of factors of 2 in 925 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 926 // exponentiation: 927 // 928 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 929 // 930 // This formula is trivially equivalent to the previous formula. However, 931 // this formula can be implemented much more efficiently. The trick is that 932 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 933 // arithmetic. To do exact division in modular arithmetic, all we have 934 // to do is multiply by the inverse. Therefore, this step can be done at 935 // width W. 936 // 937 // The next issue is how to safely do the division by 2^T. The way this 938 // is done is by doing the multiplication step at a width of at least W + T 939 // bits. This way, the bottom W+T bits of the product are accurate. Then, 940 // when we perform the division by 2^T (which is equivalent to a right shift 941 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 942 // truncated out after the division by 2^T. 943 // 944 // In comparison to just directly using the first formula, this technique 945 // is much more efficient; using the first formula requires W * K bits, 946 // but this formula less than W + K bits. Also, the first formula requires 947 // a division step, whereas this formula only requires multiplies and shifts. 948 // 949 // It doesn't matter whether the subtraction step is done in the calculation 950 // width or the input iteration count's width; if the subtraction overflows, 951 // the result must be zero anyway. We prefer here to do it in the width of 952 // the induction variable because it helps a lot for certain cases; CodeGen 953 // isn't smart enough to ignore the overflow, which leads to much less 954 // efficient code if the width of the subtraction is wider than the native 955 // register width. 956 // 957 // (It's possible to not widen at all by pulling out factors of 2 before 958 // the multiplication; for example, K=2 can be calculated as 959 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 960 // extra arithmetic, so it's not an obvious win, and it gets 961 // much more complicated for K > 3.) 962 963 // Protection from insane SCEVs; this bound is conservative, 964 // but it probably doesn't matter. 965 if (K > 1000) 966 return SE.getCouldNotCompute(); 967 968 unsigned W = SE.getTypeSizeInBits(ResultTy); 969 970 // Calculate K! / 2^T and T; we divide out the factors of two before 971 // multiplying for calculating K! / 2^T to avoid overflow. 972 // Other overflow doesn't matter because we only care about the bottom 973 // W bits of the result. 974 APInt OddFactorial(W, 1); 975 unsigned T = 1; 976 for (unsigned i = 3; i <= K; ++i) { 977 APInt Mult(W, i); 978 unsigned TwoFactors = Mult.countTrailingZeros(); 979 T += TwoFactors; 980 Mult.lshrInPlace(TwoFactors); 981 OddFactorial *= Mult; 982 } 983 984 // We need at least W + T bits for the multiplication step 985 unsigned CalculationBits = W + T; 986 987 // Calculate 2^T, at width T+W. 988 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 989 990 // Calculate the multiplicative inverse of K! / 2^T; 991 // this multiplication factor will perform the exact division by 992 // K! / 2^T. 993 APInt Mod = APInt::getSignedMinValue(W+1); 994 APInt MultiplyFactor = OddFactorial.zext(W+1); 995 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 996 MultiplyFactor = MultiplyFactor.trunc(W); 997 998 // Calculate the product, at width T+W 999 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1000 CalculationBits); 1001 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1002 for (unsigned i = 1; i != K; ++i) { 1003 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1004 Dividend = SE.getMulExpr(Dividend, 1005 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1006 } 1007 1008 // Divide by 2^T 1009 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1010 1011 // Truncate the result, and divide by K! / 2^T. 1012 1013 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1014 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1015 } 1016 1017 /// Return the value of this chain of recurrences at the specified iteration 1018 /// number. We can evaluate this recurrence by multiplying each element in the 1019 /// chain by the binomial coefficient corresponding to it. In other words, we 1020 /// can evaluate {A,+,B,+,C,+,D} as: 1021 /// 1022 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1023 /// 1024 /// where BC(It, k) stands for binomial coefficient. 1025 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1026 ScalarEvolution &SE) const { 1027 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1028 } 1029 1030 const SCEV * 1031 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1032 const SCEV *It, ScalarEvolution &SE) { 1033 assert(Operands.size() > 0); 1034 const SCEV *Result = Operands[0]; 1035 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1036 // The computation is correct in the face of overflow provided that the 1037 // multiplication is performed _after_ the evaluation of the binomial 1038 // coefficient. 1039 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1040 if (isa<SCEVCouldNotCompute>(Coeff)) 1041 return Coeff; 1042 1043 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1044 } 1045 return Result; 1046 } 1047 1048 //===----------------------------------------------------------------------===// 1049 // SCEV Expression folder implementations 1050 //===----------------------------------------------------------------------===// 1051 1052 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1053 unsigned Depth) { 1054 assert(Depth <= 1 && 1055 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1056 1057 // We could be called with an integer-typed operands during SCEV rewrites. 1058 // Since the operand is an integer already, just perform zext/trunc/self cast. 1059 if (!Op->getType()->isPointerTy()) 1060 return Op; 1061 1062 // What would be an ID for such a SCEV cast expression? 1063 FoldingSetNodeID ID; 1064 ID.AddInteger(scPtrToInt); 1065 ID.AddPointer(Op); 1066 1067 void *IP = nullptr; 1068 1069 // Is there already an expression for such a cast? 1070 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1071 return S; 1072 1073 // It isn't legal for optimizations to construct new ptrtoint expressions 1074 // for non-integral pointers. 1075 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1076 return getCouldNotCompute(); 1077 1078 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1079 1080 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1081 // is sufficiently wide to represent all possible pointer values. 1082 // We could theoretically teach SCEV to truncate wider pointers, but 1083 // that isn't implemented for now. 1084 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1085 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1086 return getCouldNotCompute(); 1087 1088 // If not, is this expression something we can't reduce any further? 1089 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1090 // Perform some basic constant folding. If the operand of the ptr2int cast 1091 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1092 // left as-is), but produce a zero constant. 1093 // NOTE: We could handle a more general case, but lack motivational cases. 1094 if (isa<ConstantPointerNull>(U->getValue())) 1095 return getZero(IntPtrTy); 1096 1097 // Create an explicit cast node. 1098 // We can reuse the existing insert position since if we get here, 1099 // we won't have made any changes which would invalidate it. 1100 SCEV *S = new (SCEVAllocator) 1101 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1102 UniqueSCEVs.InsertNode(S, IP); 1103 addToLoopUseLists(S); 1104 return S; 1105 } 1106 1107 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1108 "non-SCEVUnknown's."); 1109 1110 // Otherwise, we've got some expression that is more complex than just a 1111 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1112 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1113 // only, and the expressions must otherwise be integer-typed. 1114 // So sink the cast down to the SCEVUnknown's. 1115 1116 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1117 /// which computes a pointer-typed value, and rewrites the whole expression 1118 /// tree so that *all* the computations are done on integers, and the only 1119 /// pointer-typed operands in the expression are SCEVUnknown. 1120 class SCEVPtrToIntSinkingRewriter 1121 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1122 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1123 1124 public: 1125 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1126 1127 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1128 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1129 return Rewriter.visit(Scev); 1130 } 1131 1132 const SCEV *visit(const SCEV *S) { 1133 Type *STy = S->getType(); 1134 // If the expression is not pointer-typed, just keep it as-is. 1135 if (!STy->isPointerTy()) 1136 return S; 1137 // Else, recursively sink the cast down into it. 1138 return Base::visit(S); 1139 } 1140 1141 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1142 SmallVector<const SCEV *, 2> Operands; 1143 bool Changed = false; 1144 for (auto *Op : Expr->operands()) { 1145 Operands.push_back(visit(Op)); 1146 Changed |= Op != Operands.back(); 1147 } 1148 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1149 } 1150 1151 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1152 SmallVector<const SCEV *, 2> Operands; 1153 bool Changed = false; 1154 for (auto *Op : Expr->operands()) { 1155 Operands.push_back(visit(Op)); 1156 Changed |= Op != Operands.back(); 1157 } 1158 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1159 } 1160 1161 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1162 assert(Expr->getType()->isPointerTy() && 1163 "Should only reach pointer-typed SCEVUnknown's."); 1164 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1165 } 1166 }; 1167 1168 // And actually perform the cast sinking. 1169 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1170 assert(IntOp->getType()->isIntegerTy() && 1171 "We must have succeeded in sinking the cast, " 1172 "and ending up with an integer-typed expression!"); 1173 return IntOp; 1174 } 1175 1176 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1177 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1178 1179 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1180 if (isa<SCEVCouldNotCompute>(IntOp)) 1181 return IntOp; 1182 1183 return getTruncateOrZeroExtend(IntOp, Ty); 1184 } 1185 1186 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1187 unsigned Depth) { 1188 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1189 "This is not a truncating conversion!"); 1190 assert(isSCEVable(Ty) && 1191 "This is not a conversion to a SCEVable type!"); 1192 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1193 Ty = getEffectiveSCEVType(Ty); 1194 1195 FoldingSetNodeID ID; 1196 ID.AddInteger(scTruncate); 1197 ID.AddPointer(Op); 1198 ID.AddPointer(Ty); 1199 void *IP = nullptr; 1200 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1201 1202 // Fold if the operand is constant. 1203 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1204 return getConstant( 1205 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1206 1207 // trunc(trunc(x)) --> trunc(x) 1208 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1209 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1210 1211 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1212 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1213 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1214 1215 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1216 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1217 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1218 1219 if (Depth > MaxCastDepth) { 1220 SCEV *S = 1221 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1222 UniqueSCEVs.InsertNode(S, IP); 1223 addToLoopUseLists(S); 1224 return S; 1225 } 1226 1227 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1228 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1229 // if after transforming we have at most one truncate, not counting truncates 1230 // that replace other casts. 1231 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1232 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1233 SmallVector<const SCEV *, 4> Operands; 1234 unsigned numTruncs = 0; 1235 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1236 ++i) { 1237 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1238 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1239 isa<SCEVTruncateExpr>(S)) 1240 numTruncs++; 1241 Operands.push_back(S); 1242 } 1243 if (numTruncs < 2) { 1244 if (isa<SCEVAddExpr>(Op)) 1245 return getAddExpr(Operands); 1246 else if (isa<SCEVMulExpr>(Op)) 1247 return getMulExpr(Operands); 1248 else 1249 llvm_unreachable("Unexpected SCEV type for Op."); 1250 } 1251 // Although we checked in the beginning that ID is not in the cache, it is 1252 // possible that during recursion and different modification ID was inserted 1253 // into the cache. So if we find it, just return it. 1254 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1255 return S; 1256 } 1257 1258 // If the input value is a chrec scev, truncate the chrec's operands. 1259 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1260 SmallVector<const SCEV *, 4> Operands; 1261 for (const SCEV *Op : AddRec->operands()) 1262 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1263 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1264 } 1265 1266 // Return zero if truncating to known zeros. 1267 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1268 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1269 return getZero(Ty); 1270 1271 // The cast wasn't folded; create an explicit cast node. We can reuse 1272 // the existing insert position since if we get here, we won't have 1273 // made any changes which would invalidate it. 1274 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1275 Op, Ty); 1276 UniqueSCEVs.InsertNode(S, IP); 1277 addToLoopUseLists(S); 1278 return S; 1279 } 1280 1281 // Get the limit of a recurrence such that incrementing by Step cannot cause 1282 // signed overflow as long as the value of the recurrence within the 1283 // loop does not exceed this limit before incrementing. 1284 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1285 ICmpInst::Predicate *Pred, 1286 ScalarEvolution *SE) { 1287 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1288 if (SE->isKnownPositive(Step)) { 1289 *Pred = ICmpInst::ICMP_SLT; 1290 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1291 SE->getSignedRangeMax(Step)); 1292 } 1293 if (SE->isKnownNegative(Step)) { 1294 *Pred = ICmpInst::ICMP_SGT; 1295 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1296 SE->getSignedRangeMin(Step)); 1297 } 1298 return nullptr; 1299 } 1300 1301 // Get the limit of a recurrence such that incrementing by Step cannot cause 1302 // unsigned overflow as long as the value of the recurrence within the loop does 1303 // not exceed this limit before incrementing. 1304 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1305 ICmpInst::Predicate *Pred, 1306 ScalarEvolution *SE) { 1307 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1308 *Pred = ICmpInst::ICMP_ULT; 1309 1310 return SE->getConstant(APInt::getMinValue(BitWidth) - 1311 SE->getUnsignedRangeMax(Step)); 1312 } 1313 1314 namespace { 1315 1316 struct ExtendOpTraitsBase { 1317 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1318 unsigned); 1319 }; 1320 1321 // Used to make code generic over signed and unsigned overflow. 1322 template <typename ExtendOp> struct ExtendOpTraits { 1323 // Members present: 1324 // 1325 // static const SCEV::NoWrapFlags WrapType; 1326 // 1327 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1328 // 1329 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1330 // ICmpInst::Predicate *Pred, 1331 // ScalarEvolution *SE); 1332 }; 1333 1334 template <> 1335 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1336 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1337 1338 static const GetExtendExprTy GetExtendExpr; 1339 1340 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1341 ICmpInst::Predicate *Pred, 1342 ScalarEvolution *SE) { 1343 return getSignedOverflowLimitForStep(Step, Pred, SE); 1344 } 1345 }; 1346 1347 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1348 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1349 1350 template <> 1351 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1352 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1353 1354 static const GetExtendExprTy GetExtendExpr; 1355 1356 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1357 ICmpInst::Predicate *Pred, 1358 ScalarEvolution *SE) { 1359 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1360 } 1361 }; 1362 1363 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1364 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1365 1366 } // end anonymous namespace 1367 1368 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1369 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1370 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1371 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1372 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1373 // expression "Step + sext/zext(PreIncAR)" is congruent with 1374 // "sext/zext(PostIncAR)" 1375 template <typename ExtendOpTy> 1376 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1377 ScalarEvolution *SE, unsigned Depth) { 1378 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1379 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1380 1381 const Loop *L = AR->getLoop(); 1382 const SCEV *Start = AR->getStart(); 1383 const SCEV *Step = AR->getStepRecurrence(*SE); 1384 1385 // Check for a simple looking step prior to loop entry. 1386 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1387 if (!SA) 1388 return nullptr; 1389 1390 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1391 // subtraction is expensive. For this purpose, perform a quick and dirty 1392 // difference, by checking for Step in the operand list. 1393 SmallVector<const SCEV *, 4> DiffOps; 1394 for (const SCEV *Op : SA->operands()) 1395 if (Op != Step) 1396 DiffOps.push_back(Op); 1397 1398 if (DiffOps.size() == SA->getNumOperands()) 1399 return nullptr; 1400 1401 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1402 // `Step`: 1403 1404 // 1. NSW/NUW flags on the step increment. 1405 auto PreStartFlags = 1406 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1407 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1408 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1409 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1410 1411 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1412 // "S+X does not sign/unsign-overflow". 1413 // 1414 1415 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1416 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1417 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1418 return PreStart; 1419 1420 // 2. Direct overflow check on the step operation's expression. 1421 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1422 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1423 const SCEV *OperandExtendedStart = 1424 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1425 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1426 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1427 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1428 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1429 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1430 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1431 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1432 } 1433 return PreStart; 1434 } 1435 1436 // 3. Loop precondition. 1437 ICmpInst::Predicate Pred; 1438 const SCEV *OverflowLimit = 1439 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1440 1441 if (OverflowLimit && 1442 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1443 return PreStart; 1444 1445 return nullptr; 1446 } 1447 1448 // Get the normalized zero or sign extended expression for this AddRec's Start. 1449 template <typename ExtendOpTy> 1450 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1451 ScalarEvolution *SE, 1452 unsigned Depth) { 1453 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1454 1455 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1456 if (!PreStart) 1457 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1458 1459 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1460 Depth), 1461 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1462 } 1463 1464 // Try to prove away overflow by looking at "nearby" add recurrences. A 1465 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1466 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1467 // 1468 // Formally: 1469 // 1470 // {S,+,X} == {S-T,+,X} + T 1471 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1472 // 1473 // If ({S-T,+,X} + T) does not overflow ... (1) 1474 // 1475 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1476 // 1477 // If {S-T,+,X} does not overflow ... (2) 1478 // 1479 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1480 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1481 // 1482 // If (S-T)+T does not overflow ... (3) 1483 // 1484 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1485 // == {Ext(S),+,Ext(X)} == LHS 1486 // 1487 // Thus, if (1), (2) and (3) are true for some T, then 1488 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1489 // 1490 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1491 // does not overflow" restricted to the 0th iteration. Therefore we only need 1492 // to check for (1) and (2). 1493 // 1494 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1495 // is `Delta` (defined below). 1496 template <typename ExtendOpTy> 1497 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1498 const SCEV *Step, 1499 const Loop *L) { 1500 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1501 1502 // We restrict `Start` to a constant to prevent SCEV from spending too much 1503 // time here. It is correct (but more expensive) to continue with a 1504 // non-constant `Start` and do a general SCEV subtraction to compute 1505 // `PreStart` below. 1506 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1507 if (!StartC) 1508 return false; 1509 1510 APInt StartAI = StartC->getAPInt(); 1511 1512 for (unsigned Delta : {-2, -1, 1, 2}) { 1513 const SCEV *PreStart = getConstant(StartAI - Delta); 1514 1515 FoldingSetNodeID ID; 1516 ID.AddInteger(scAddRecExpr); 1517 ID.AddPointer(PreStart); 1518 ID.AddPointer(Step); 1519 ID.AddPointer(L); 1520 void *IP = nullptr; 1521 const auto *PreAR = 1522 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1523 1524 // Give up if we don't already have the add recurrence we need because 1525 // actually constructing an add recurrence is relatively expensive. 1526 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1527 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1528 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1529 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1530 DeltaS, &Pred, this); 1531 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1532 return true; 1533 } 1534 } 1535 1536 return false; 1537 } 1538 1539 // Finds an integer D for an expression (C + x + y + ...) such that the top 1540 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1541 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1542 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1543 // the (C + x + y + ...) expression is \p WholeAddExpr. 1544 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1545 const SCEVConstant *ConstantTerm, 1546 const SCEVAddExpr *WholeAddExpr) { 1547 const APInt &C = ConstantTerm->getAPInt(); 1548 const unsigned BitWidth = C.getBitWidth(); 1549 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1550 uint32_t TZ = BitWidth; 1551 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1552 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1553 if (TZ) { 1554 // Set D to be as many least significant bits of C as possible while still 1555 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1556 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1557 } 1558 return APInt(BitWidth, 0); 1559 } 1560 1561 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1562 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1563 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1564 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1565 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1566 const APInt &ConstantStart, 1567 const SCEV *Step) { 1568 const unsigned BitWidth = ConstantStart.getBitWidth(); 1569 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1570 if (TZ) 1571 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1572 : ConstantStart; 1573 return APInt(BitWidth, 0); 1574 } 1575 1576 const SCEV * 1577 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1578 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1579 "This is not an extending conversion!"); 1580 assert(isSCEVable(Ty) && 1581 "This is not a conversion to a SCEVable type!"); 1582 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1583 Ty = getEffectiveSCEVType(Ty); 1584 1585 // Fold if the operand is constant. 1586 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1587 return getConstant( 1588 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1589 1590 // zext(zext(x)) --> zext(x) 1591 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1592 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1593 1594 // Before doing any expensive analysis, check to see if we've already 1595 // computed a SCEV for this Op and Ty. 1596 FoldingSetNodeID ID; 1597 ID.AddInteger(scZeroExtend); 1598 ID.AddPointer(Op); 1599 ID.AddPointer(Ty); 1600 void *IP = nullptr; 1601 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1602 if (Depth > MaxCastDepth) { 1603 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1604 Op, Ty); 1605 UniqueSCEVs.InsertNode(S, IP); 1606 addToLoopUseLists(S); 1607 return S; 1608 } 1609 1610 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1611 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1612 // It's possible the bits taken off by the truncate were all zero bits. If 1613 // so, we should be able to simplify this further. 1614 const SCEV *X = ST->getOperand(); 1615 ConstantRange CR = getUnsignedRange(X); 1616 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1617 unsigned NewBits = getTypeSizeInBits(Ty); 1618 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1619 CR.zextOrTrunc(NewBits))) 1620 return getTruncateOrZeroExtend(X, Ty, Depth); 1621 } 1622 1623 // If the input value is a chrec scev, and we can prove that the value 1624 // did not overflow the old, smaller, value, we can zero extend all of the 1625 // operands (often constants). This allows analysis of something like 1626 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1627 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1628 if (AR->isAffine()) { 1629 const SCEV *Start = AR->getStart(); 1630 const SCEV *Step = AR->getStepRecurrence(*this); 1631 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1632 const Loop *L = AR->getLoop(); 1633 1634 if (!AR->hasNoUnsignedWrap()) { 1635 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1636 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1637 } 1638 1639 // If we have special knowledge that this addrec won't overflow, 1640 // we don't need to do any further analysis. 1641 if (AR->hasNoUnsignedWrap()) 1642 return getAddRecExpr( 1643 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1644 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1645 1646 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1647 // Note that this serves two purposes: It filters out loops that are 1648 // simply not analyzable, and it covers the case where this code is 1649 // being called from within backedge-taken count analysis, such that 1650 // attempting to ask for the backedge-taken count would likely result 1651 // in infinite recursion. In the later case, the analysis code will 1652 // cope with a conservative value, and it will take care to purge 1653 // that value once it has finished. 1654 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1655 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1656 // Manually compute the final value for AR, checking for overflow. 1657 1658 // Check whether the backedge-taken count can be losslessly casted to 1659 // the addrec's type. The count is always unsigned. 1660 const SCEV *CastedMaxBECount = 1661 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1662 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1663 CastedMaxBECount, MaxBECount->getType(), Depth); 1664 if (MaxBECount == RecastedMaxBECount) { 1665 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1666 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1667 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1668 SCEV::FlagAnyWrap, Depth + 1); 1669 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1670 SCEV::FlagAnyWrap, 1671 Depth + 1), 1672 WideTy, Depth + 1); 1673 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1674 const SCEV *WideMaxBECount = 1675 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1676 const SCEV *OperandExtendedAdd = 1677 getAddExpr(WideStart, 1678 getMulExpr(WideMaxBECount, 1679 getZeroExtendExpr(Step, WideTy, Depth + 1), 1680 SCEV::FlagAnyWrap, Depth + 1), 1681 SCEV::FlagAnyWrap, Depth + 1); 1682 if (ZAdd == OperandExtendedAdd) { 1683 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1684 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1685 // Return the expression with the addrec on the outside. 1686 return getAddRecExpr( 1687 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1688 Depth + 1), 1689 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1690 AR->getNoWrapFlags()); 1691 } 1692 // Similar to above, only this time treat the step value as signed. 1693 // This covers loops that count down. 1694 OperandExtendedAdd = 1695 getAddExpr(WideStart, 1696 getMulExpr(WideMaxBECount, 1697 getSignExtendExpr(Step, WideTy, Depth + 1), 1698 SCEV::FlagAnyWrap, Depth + 1), 1699 SCEV::FlagAnyWrap, Depth + 1); 1700 if (ZAdd == OperandExtendedAdd) { 1701 // Cache knowledge of AR NW, which is propagated to this AddRec. 1702 // Negative step causes unsigned wrap, but it still can't self-wrap. 1703 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1704 // Return the expression with the addrec on the outside. 1705 return getAddRecExpr( 1706 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1707 Depth + 1), 1708 getSignExtendExpr(Step, Ty, Depth + 1), L, 1709 AR->getNoWrapFlags()); 1710 } 1711 } 1712 } 1713 1714 // Normally, in the cases we can prove no-overflow via a 1715 // backedge guarding condition, we can also compute a backedge 1716 // taken count for the loop. The exceptions are assumptions and 1717 // guards present in the loop -- SCEV is not great at exploiting 1718 // these to compute max backedge taken counts, but can still use 1719 // these to prove lack of overflow. Use this fact to avoid 1720 // doing extra work that may not pay off. 1721 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1722 !AC.assumptions().empty()) { 1723 1724 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1725 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1726 if (AR->hasNoUnsignedWrap()) { 1727 // Same as nuw case above - duplicated here to avoid a compile time 1728 // issue. It's not clear that the order of checks does matter, but 1729 // it's one of two issue possible causes for a change which was 1730 // reverted. Be conservative for the moment. 1731 return getAddRecExpr( 1732 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1733 Depth + 1), 1734 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1735 AR->getNoWrapFlags()); 1736 } 1737 1738 // For a negative step, we can extend the operands iff doing so only 1739 // traverses values in the range zext([0,UINT_MAX]). 1740 if (isKnownNegative(Step)) { 1741 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1742 getSignedRangeMin(Step)); 1743 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1744 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1745 // Cache knowledge of AR NW, which is propagated to this 1746 // AddRec. Negative step causes unsigned wrap, but it 1747 // still can't self-wrap. 1748 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1749 // Return the expression with the addrec on the outside. 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1752 Depth + 1), 1753 getSignExtendExpr(Step, Ty, Depth + 1), L, 1754 AR->getNoWrapFlags()); 1755 } 1756 } 1757 } 1758 1759 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1760 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1761 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1762 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1763 const APInt &C = SC->getAPInt(); 1764 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1765 if (D != 0) { 1766 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1767 const SCEV *SResidual = 1768 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1769 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1770 return getAddExpr(SZExtD, SZExtR, 1771 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1772 Depth + 1); 1773 } 1774 } 1775 1776 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1777 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1778 return getAddRecExpr( 1779 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1780 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1781 } 1782 } 1783 1784 // zext(A % B) --> zext(A) % zext(B) 1785 { 1786 const SCEV *LHS; 1787 const SCEV *RHS; 1788 if (matchURem(Op, LHS, RHS)) 1789 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1790 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1791 } 1792 1793 // zext(A / B) --> zext(A) / zext(B). 1794 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1795 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1796 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1797 1798 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1799 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1800 if (SA->hasNoUnsignedWrap()) { 1801 // If the addition does not unsign overflow then we can, by definition, 1802 // commute the zero extension with the addition operation. 1803 SmallVector<const SCEV *, 4> Ops; 1804 for (const auto *Op : SA->operands()) 1805 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1806 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1807 } 1808 1809 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1810 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1811 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1812 // 1813 // Often address arithmetics contain expressions like 1814 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1815 // This transformation is useful while proving that such expressions are 1816 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1817 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1818 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1819 if (D != 0) { 1820 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1821 const SCEV *SResidual = 1822 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1823 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1824 return getAddExpr(SZExtD, SZExtR, 1825 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1826 Depth + 1); 1827 } 1828 } 1829 } 1830 1831 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1832 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1833 if (SM->hasNoUnsignedWrap()) { 1834 // If the multiply does not unsign overflow then we can, by definition, 1835 // commute the zero extension with the multiply operation. 1836 SmallVector<const SCEV *, 4> Ops; 1837 for (const auto *Op : SM->operands()) 1838 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1839 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1840 } 1841 1842 // zext(2^K * (trunc X to iN)) to iM -> 1843 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1844 // 1845 // Proof: 1846 // 1847 // zext(2^K * (trunc X to iN)) to iM 1848 // = zext((trunc X to iN) << K) to iM 1849 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1850 // (because shl removes the top K bits) 1851 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1852 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1853 // 1854 if (SM->getNumOperands() == 2) 1855 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1856 if (MulLHS->getAPInt().isPowerOf2()) 1857 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1858 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1859 MulLHS->getAPInt().logBase2(); 1860 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1861 return getMulExpr( 1862 getZeroExtendExpr(MulLHS, Ty), 1863 getZeroExtendExpr( 1864 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1865 SCEV::FlagNUW, Depth + 1); 1866 } 1867 } 1868 1869 // The cast wasn't folded; create an explicit cast node. 1870 // Recompute the insert position, as it may have been invalidated. 1871 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1872 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1873 Op, Ty); 1874 UniqueSCEVs.InsertNode(S, IP); 1875 addToLoopUseLists(S); 1876 return S; 1877 } 1878 1879 const SCEV * 1880 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1881 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1882 "This is not an extending conversion!"); 1883 assert(isSCEVable(Ty) && 1884 "This is not a conversion to a SCEVable type!"); 1885 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1886 Ty = getEffectiveSCEVType(Ty); 1887 1888 // Fold if the operand is constant. 1889 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1890 return getConstant( 1891 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1892 1893 // sext(sext(x)) --> sext(x) 1894 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1895 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1896 1897 // sext(zext(x)) --> zext(x) 1898 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1899 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1900 1901 // Before doing any expensive analysis, check to see if we've already 1902 // computed a SCEV for this Op and Ty. 1903 FoldingSetNodeID ID; 1904 ID.AddInteger(scSignExtend); 1905 ID.AddPointer(Op); 1906 ID.AddPointer(Ty); 1907 void *IP = nullptr; 1908 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1909 // Limit recursion depth. 1910 if (Depth > MaxCastDepth) { 1911 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1912 Op, Ty); 1913 UniqueSCEVs.InsertNode(S, IP); 1914 addToLoopUseLists(S); 1915 return S; 1916 } 1917 1918 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1919 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1920 // It's possible the bits taken off by the truncate were all sign bits. If 1921 // so, we should be able to simplify this further. 1922 const SCEV *X = ST->getOperand(); 1923 ConstantRange CR = getSignedRange(X); 1924 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1925 unsigned NewBits = getTypeSizeInBits(Ty); 1926 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1927 CR.sextOrTrunc(NewBits))) 1928 return getTruncateOrSignExtend(X, Ty, Depth); 1929 } 1930 1931 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1932 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1933 if (SA->hasNoSignedWrap()) { 1934 // If the addition does not sign overflow then we can, by definition, 1935 // commute the sign extension with the addition operation. 1936 SmallVector<const SCEV *, 4> Ops; 1937 for (const auto *Op : SA->operands()) 1938 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1939 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1940 } 1941 1942 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1943 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1944 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1945 // 1946 // For instance, this will bring two seemingly different expressions: 1947 // 1 + sext(5 + 20 * %x + 24 * %y) and 1948 // sext(6 + 20 * %x + 24 * %y) 1949 // to the same form: 1950 // 2 + sext(4 + 20 * %x + 24 * %y) 1951 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1952 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1953 if (D != 0) { 1954 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1955 const SCEV *SResidual = 1956 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1957 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1958 return getAddExpr(SSExtD, SSExtR, 1959 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1960 Depth + 1); 1961 } 1962 } 1963 } 1964 // If the input value is a chrec scev, and we can prove that the value 1965 // did not overflow the old, smaller, value, we can sign extend all of the 1966 // operands (often constants). This allows analysis of something like 1967 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1968 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1969 if (AR->isAffine()) { 1970 const SCEV *Start = AR->getStart(); 1971 const SCEV *Step = AR->getStepRecurrence(*this); 1972 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1973 const Loop *L = AR->getLoop(); 1974 1975 if (!AR->hasNoSignedWrap()) { 1976 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1977 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1978 } 1979 1980 // If we have special knowledge that this addrec won't overflow, 1981 // we don't need to do any further analysis. 1982 if (AR->hasNoSignedWrap()) 1983 return getAddRecExpr( 1984 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1985 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1986 1987 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1988 // Note that this serves two purposes: It filters out loops that are 1989 // simply not analyzable, and it covers the case where this code is 1990 // being called from within backedge-taken count analysis, such that 1991 // attempting to ask for the backedge-taken count would likely result 1992 // in infinite recursion. In the later case, the analysis code will 1993 // cope with a conservative value, and it will take care to purge 1994 // that value once it has finished. 1995 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1996 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1997 // Manually compute the final value for AR, checking for 1998 // overflow. 1999 2000 // Check whether the backedge-taken count can be losslessly casted to 2001 // the addrec's type. The count is always unsigned. 2002 const SCEV *CastedMaxBECount = 2003 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2004 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2005 CastedMaxBECount, MaxBECount->getType(), Depth); 2006 if (MaxBECount == RecastedMaxBECount) { 2007 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2008 // Check whether Start+Step*MaxBECount has no signed overflow. 2009 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2010 SCEV::FlagAnyWrap, Depth + 1); 2011 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2012 SCEV::FlagAnyWrap, 2013 Depth + 1), 2014 WideTy, Depth + 1); 2015 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2016 const SCEV *WideMaxBECount = 2017 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2018 const SCEV *OperandExtendedAdd = 2019 getAddExpr(WideStart, 2020 getMulExpr(WideMaxBECount, 2021 getSignExtendExpr(Step, WideTy, Depth + 1), 2022 SCEV::FlagAnyWrap, Depth + 1), 2023 SCEV::FlagAnyWrap, Depth + 1); 2024 if (SAdd == OperandExtendedAdd) { 2025 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2026 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2027 // Return the expression with the addrec on the outside. 2028 return getAddRecExpr( 2029 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2030 Depth + 1), 2031 getSignExtendExpr(Step, Ty, Depth + 1), L, 2032 AR->getNoWrapFlags()); 2033 } 2034 // Similar to above, only this time treat the step value as unsigned. 2035 // This covers loops that count up with an unsigned step. 2036 OperandExtendedAdd = 2037 getAddExpr(WideStart, 2038 getMulExpr(WideMaxBECount, 2039 getZeroExtendExpr(Step, WideTy, Depth + 1), 2040 SCEV::FlagAnyWrap, Depth + 1), 2041 SCEV::FlagAnyWrap, Depth + 1); 2042 if (SAdd == OperandExtendedAdd) { 2043 // If AR wraps around then 2044 // 2045 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2046 // => SAdd != OperandExtendedAdd 2047 // 2048 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2049 // (SAdd == OperandExtendedAdd => AR is NW) 2050 2051 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2052 2053 // Return the expression with the addrec on the outside. 2054 return getAddRecExpr( 2055 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2056 Depth + 1), 2057 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2058 AR->getNoWrapFlags()); 2059 } 2060 } 2061 } 2062 2063 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2064 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2065 if (AR->hasNoSignedWrap()) { 2066 // Same as nsw case above - duplicated here to avoid a compile time 2067 // issue. It's not clear that the order of checks does matter, but 2068 // it's one of two issue possible causes for a change which was 2069 // reverted. Be conservative for the moment. 2070 return getAddRecExpr( 2071 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2072 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2073 } 2074 2075 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2076 // if D + (C - D + Step * n) could be proven to not signed wrap 2077 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2078 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2079 const APInt &C = SC->getAPInt(); 2080 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2081 if (D != 0) { 2082 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2083 const SCEV *SResidual = 2084 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2085 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2086 return getAddExpr(SSExtD, SSExtR, 2087 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2088 Depth + 1); 2089 } 2090 } 2091 2092 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2093 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2094 return getAddRecExpr( 2095 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2096 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2097 } 2098 } 2099 2100 // If the input value is provably positive and we could not simplify 2101 // away the sext build a zext instead. 2102 if (isKnownNonNegative(Op)) 2103 return getZeroExtendExpr(Op, Ty, Depth + 1); 2104 2105 // The cast wasn't folded; create an explicit cast node. 2106 // Recompute the insert position, as it may have been invalidated. 2107 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2108 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2109 Op, Ty); 2110 UniqueSCEVs.InsertNode(S, IP); 2111 addToLoopUseLists(S); 2112 return S; 2113 } 2114 2115 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2116 /// unspecified bits out to the given type. 2117 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2118 Type *Ty) { 2119 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2120 "This is not an extending conversion!"); 2121 assert(isSCEVable(Ty) && 2122 "This is not a conversion to a SCEVable type!"); 2123 Ty = getEffectiveSCEVType(Ty); 2124 2125 // Sign-extend negative constants. 2126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2127 if (SC->getAPInt().isNegative()) 2128 return getSignExtendExpr(Op, Ty); 2129 2130 // Peel off a truncate cast. 2131 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2132 const SCEV *NewOp = T->getOperand(); 2133 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2134 return getAnyExtendExpr(NewOp, Ty); 2135 return getTruncateOrNoop(NewOp, Ty); 2136 } 2137 2138 // Next try a zext cast. If the cast is folded, use it. 2139 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2140 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2141 return ZExt; 2142 2143 // Next try a sext cast. If the cast is folded, use it. 2144 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2145 if (!isa<SCEVSignExtendExpr>(SExt)) 2146 return SExt; 2147 2148 // Force the cast to be folded into the operands of an addrec. 2149 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2150 SmallVector<const SCEV *, 4> Ops; 2151 for (const SCEV *Op : AR->operands()) 2152 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2153 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2154 } 2155 2156 // If the expression is obviously signed, use the sext cast value. 2157 if (isa<SCEVSMaxExpr>(Op)) 2158 return SExt; 2159 2160 // Absent any other information, use the zext cast value. 2161 return ZExt; 2162 } 2163 2164 /// Process the given Ops list, which is a list of operands to be added under 2165 /// the given scale, update the given map. This is a helper function for 2166 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2167 /// that would form an add expression like this: 2168 /// 2169 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2170 /// 2171 /// where A and B are constants, update the map with these values: 2172 /// 2173 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2174 /// 2175 /// and add 13 + A*B*29 to AccumulatedConstant. 2176 /// This will allow getAddRecExpr to produce this: 2177 /// 2178 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2179 /// 2180 /// This form often exposes folding opportunities that are hidden in 2181 /// the original operand list. 2182 /// 2183 /// Return true iff it appears that any interesting folding opportunities 2184 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2185 /// the common case where no interesting opportunities are present, and 2186 /// is also used as a check to avoid infinite recursion. 2187 static bool 2188 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2189 SmallVectorImpl<const SCEV *> &NewOps, 2190 APInt &AccumulatedConstant, 2191 const SCEV *const *Ops, size_t NumOperands, 2192 const APInt &Scale, 2193 ScalarEvolution &SE) { 2194 bool Interesting = false; 2195 2196 // Iterate over the add operands. They are sorted, with constants first. 2197 unsigned i = 0; 2198 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2199 ++i; 2200 // Pull a buried constant out to the outside. 2201 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2202 Interesting = true; 2203 AccumulatedConstant += Scale * C->getAPInt(); 2204 } 2205 2206 // Next comes everything else. We're especially interested in multiplies 2207 // here, but they're in the middle, so just visit the rest with one loop. 2208 for (; i != NumOperands; ++i) { 2209 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2210 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2211 APInt NewScale = 2212 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2213 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2214 // A multiplication of a constant with another add; recurse. 2215 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2216 Interesting |= 2217 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2218 Add->op_begin(), Add->getNumOperands(), 2219 NewScale, SE); 2220 } else { 2221 // A multiplication of a constant with some other value. Update 2222 // the map. 2223 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2224 const SCEV *Key = SE.getMulExpr(MulOps); 2225 auto Pair = M.insert({Key, NewScale}); 2226 if (Pair.second) { 2227 NewOps.push_back(Pair.first->first); 2228 } else { 2229 Pair.first->second += NewScale; 2230 // The map already had an entry for this value, which may indicate 2231 // a folding opportunity. 2232 Interesting = true; 2233 } 2234 } 2235 } else { 2236 // An ordinary operand. Update the map. 2237 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2238 M.insert({Ops[i], Scale}); 2239 if (Pair.second) { 2240 NewOps.push_back(Pair.first->first); 2241 } else { 2242 Pair.first->second += Scale; 2243 // The map already had an entry for this value, which may indicate 2244 // a folding opportunity. 2245 Interesting = true; 2246 } 2247 } 2248 } 2249 2250 return Interesting; 2251 } 2252 2253 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2254 const SCEV *LHS, const SCEV *RHS) { 2255 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2256 SCEV::NoWrapFlags, unsigned); 2257 switch (BinOp) { 2258 default: 2259 llvm_unreachable("Unsupported binary op"); 2260 case Instruction::Add: 2261 Operation = &ScalarEvolution::getAddExpr; 2262 break; 2263 case Instruction::Sub: 2264 Operation = &ScalarEvolution::getMinusSCEV; 2265 break; 2266 case Instruction::Mul: 2267 Operation = &ScalarEvolution::getMulExpr; 2268 break; 2269 } 2270 2271 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2272 Signed ? &ScalarEvolution::getSignExtendExpr 2273 : &ScalarEvolution::getZeroExtendExpr; 2274 2275 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2276 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2277 auto *WideTy = 2278 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2279 2280 const SCEV *A = (this->*Extension)( 2281 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2282 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2283 (this->*Extension)(RHS, WideTy, 0), 2284 SCEV::FlagAnyWrap, 0); 2285 return A == B; 2286 } 2287 2288 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2289 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2290 const OverflowingBinaryOperator *OBO) { 2291 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2292 2293 if (OBO->hasNoUnsignedWrap()) 2294 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2295 if (OBO->hasNoSignedWrap()) 2296 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2297 2298 bool Deduced = false; 2299 2300 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2301 return {Flags, Deduced}; 2302 2303 if (OBO->getOpcode() != Instruction::Add && 2304 OBO->getOpcode() != Instruction::Sub && 2305 OBO->getOpcode() != Instruction::Mul) 2306 return {Flags, Deduced}; 2307 2308 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2309 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2310 2311 if (!OBO->hasNoUnsignedWrap() && 2312 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2313 /* Signed */ false, LHS, RHS)) { 2314 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2315 Deduced = true; 2316 } 2317 2318 if (!OBO->hasNoSignedWrap() && 2319 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2320 /* Signed */ true, LHS, RHS)) { 2321 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2322 Deduced = true; 2323 } 2324 2325 return {Flags, Deduced}; 2326 } 2327 2328 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2329 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2330 // can't-overflow flags for the operation if possible. 2331 static SCEV::NoWrapFlags 2332 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2333 const ArrayRef<const SCEV *> Ops, 2334 SCEV::NoWrapFlags Flags) { 2335 using namespace std::placeholders; 2336 2337 using OBO = OverflowingBinaryOperator; 2338 2339 bool CanAnalyze = 2340 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2341 (void)CanAnalyze; 2342 assert(CanAnalyze && "don't call from other places!"); 2343 2344 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2345 SCEV::NoWrapFlags SignOrUnsignWrap = 2346 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2347 2348 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2349 auto IsKnownNonNegative = [&](const SCEV *S) { 2350 return SE->isKnownNonNegative(S); 2351 }; 2352 2353 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2354 Flags = 2355 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2356 2357 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2358 2359 if (SignOrUnsignWrap != SignOrUnsignMask && 2360 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2361 isa<SCEVConstant>(Ops[0])) { 2362 2363 auto Opcode = [&] { 2364 switch (Type) { 2365 case scAddExpr: 2366 return Instruction::Add; 2367 case scMulExpr: 2368 return Instruction::Mul; 2369 default: 2370 llvm_unreachable("Unexpected SCEV op."); 2371 } 2372 }(); 2373 2374 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2375 2376 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2377 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2378 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2379 Opcode, C, OBO::NoSignedWrap); 2380 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2381 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2382 } 2383 2384 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2385 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2386 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2387 Opcode, C, OBO::NoUnsignedWrap); 2388 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2389 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2390 } 2391 } 2392 2393 // <0,+,nonnegative><nw> is also nuw 2394 // TODO: Add corresponding nsw case 2395 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2396 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2397 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2398 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2399 2400 return Flags; 2401 } 2402 2403 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2404 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2405 } 2406 2407 /// Get a canonical add expression, or something simpler if possible. 2408 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2409 SCEV::NoWrapFlags OrigFlags, 2410 unsigned Depth) { 2411 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2412 "only nuw or nsw allowed"); 2413 assert(!Ops.empty() && "Cannot get empty add!"); 2414 if (Ops.size() == 1) return Ops[0]; 2415 #ifndef NDEBUG 2416 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2417 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2418 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2419 "SCEVAddExpr operand types don't match!"); 2420 unsigned NumPtrs = count_if( 2421 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2422 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2423 #endif 2424 2425 // Sort by complexity, this groups all similar expression types together. 2426 GroupByComplexity(Ops, &LI, DT); 2427 2428 // If there are any constants, fold them together. 2429 unsigned Idx = 0; 2430 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2431 ++Idx; 2432 assert(Idx < Ops.size()); 2433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2434 // We found two constants, fold them together! 2435 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2436 if (Ops.size() == 2) return Ops[0]; 2437 Ops.erase(Ops.begin()+1); // Erase the folded element 2438 LHSC = cast<SCEVConstant>(Ops[0]); 2439 } 2440 2441 // If we are left with a constant zero being added, strip it off. 2442 if (LHSC->getValue()->isZero()) { 2443 Ops.erase(Ops.begin()); 2444 --Idx; 2445 } 2446 2447 if (Ops.size() == 1) return Ops[0]; 2448 } 2449 2450 // Delay expensive flag strengthening until necessary. 2451 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2452 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2453 }; 2454 2455 // Limit recursion calls depth. 2456 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2457 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2458 2459 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2460 // Don't strengthen flags if we have no new information. 2461 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2462 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2463 Add->setNoWrapFlags(ComputeFlags(Ops)); 2464 return S; 2465 } 2466 2467 // Okay, check to see if the same value occurs in the operand list more than 2468 // once. If so, merge them together into an multiply expression. Since we 2469 // sorted the list, these values are required to be adjacent. 2470 Type *Ty = Ops[0]->getType(); 2471 bool FoundMatch = false; 2472 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2473 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2474 // Scan ahead to count how many equal operands there are. 2475 unsigned Count = 2; 2476 while (i+Count != e && Ops[i+Count] == Ops[i]) 2477 ++Count; 2478 // Merge the values into a multiply. 2479 const SCEV *Scale = getConstant(Ty, Count); 2480 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2481 if (Ops.size() == Count) 2482 return Mul; 2483 Ops[i] = Mul; 2484 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2485 --i; e -= Count - 1; 2486 FoundMatch = true; 2487 } 2488 if (FoundMatch) 2489 return getAddExpr(Ops, OrigFlags, Depth + 1); 2490 2491 // Check for truncates. If all the operands are truncated from the same 2492 // type, see if factoring out the truncate would permit the result to be 2493 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2494 // if the contents of the resulting outer trunc fold to something simple. 2495 auto FindTruncSrcType = [&]() -> Type * { 2496 // We're ultimately looking to fold an addrec of truncs and muls of only 2497 // constants and truncs, so if we find any other types of SCEV 2498 // as operands of the addrec then we bail and return nullptr here. 2499 // Otherwise, we return the type of the operand of a trunc that we find. 2500 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2501 return T->getOperand()->getType(); 2502 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2503 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2504 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2505 return T->getOperand()->getType(); 2506 } 2507 return nullptr; 2508 }; 2509 if (auto *SrcType = FindTruncSrcType()) { 2510 SmallVector<const SCEV *, 8> LargeOps; 2511 bool Ok = true; 2512 // Check all the operands to see if they can be represented in the 2513 // source type of the truncate. 2514 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2515 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2516 if (T->getOperand()->getType() != SrcType) { 2517 Ok = false; 2518 break; 2519 } 2520 LargeOps.push_back(T->getOperand()); 2521 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2522 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2523 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2524 SmallVector<const SCEV *, 8> LargeMulOps; 2525 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2526 if (const SCEVTruncateExpr *T = 2527 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2528 if (T->getOperand()->getType() != SrcType) { 2529 Ok = false; 2530 break; 2531 } 2532 LargeMulOps.push_back(T->getOperand()); 2533 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2534 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2535 } else { 2536 Ok = false; 2537 break; 2538 } 2539 } 2540 if (Ok) 2541 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2542 } else { 2543 Ok = false; 2544 break; 2545 } 2546 } 2547 if (Ok) { 2548 // Evaluate the expression in the larger type. 2549 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2550 // If it folds to something simple, use it. Otherwise, don't. 2551 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2552 return getTruncateExpr(Fold, Ty); 2553 } 2554 } 2555 2556 if (Ops.size() == 2) { 2557 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2558 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2559 // C1). 2560 const SCEV *A = Ops[0]; 2561 const SCEV *B = Ops[1]; 2562 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2563 auto *C = dyn_cast<SCEVConstant>(A); 2564 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2565 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2566 auto C2 = C->getAPInt(); 2567 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2568 2569 APInt ConstAdd = C1 + C2; 2570 auto AddFlags = AddExpr->getNoWrapFlags(); 2571 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2572 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2573 ConstAdd.ule(C1)) { 2574 PreservedFlags = 2575 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2576 } 2577 2578 // Adding a constant with the same sign and small magnitude is NSW, if the 2579 // original AddExpr was NSW. 2580 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2581 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2582 ConstAdd.abs().ule(C1.abs())) { 2583 PreservedFlags = 2584 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2585 } 2586 2587 if (PreservedFlags != SCEV::FlagAnyWrap) { 2588 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2589 NewOps[0] = getConstant(ConstAdd); 2590 return getAddExpr(NewOps, PreservedFlags); 2591 } 2592 } 2593 } 2594 2595 // Skip past any other cast SCEVs. 2596 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2597 ++Idx; 2598 2599 // If there are add operands they would be next. 2600 if (Idx < Ops.size()) { 2601 bool DeletedAdd = false; 2602 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2603 // common NUW flag for expression after inlining. Other flags cannot be 2604 // preserved, because they may depend on the original order of operations. 2605 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2606 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2607 if (Ops.size() > AddOpsInlineThreshold || 2608 Add->getNumOperands() > AddOpsInlineThreshold) 2609 break; 2610 // If we have an add, expand the add operands onto the end of the operands 2611 // list. 2612 Ops.erase(Ops.begin()+Idx); 2613 Ops.append(Add->op_begin(), Add->op_end()); 2614 DeletedAdd = true; 2615 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2616 } 2617 2618 // If we deleted at least one add, we added operands to the end of the list, 2619 // and they are not necessarily sorted. Recurse to resort and resimplify 2620 // any operands we just acquired. 2621 if (DeletedAdd) 2622 return getAddExpr(Ops, CommonFlags, Depth + 1); 2623 } 2624 2625 // Skip over the add expression until we get to a multiply. 2626 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2627 ++Idx; 2628 2629 // Check to see if there are any folding opportunities present with 2630 // operands multiplied by constant values. 2631 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2632 uint64_t BitWidth = getTypeSizeInBits(Ty); 2633 DenseMap<const SCEV *, APInt> M; 2634 SmallVector<const SCEV *, 8> NewOps; 2635 APInt AccumulatedConstant(BitWidth, 0); 2636 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2637 Ops.data(), Ops.size(), 2638 APInt(BitWidth, 1), *this)) { 2639 struct APIntCompare { 2640 bool operator()(const APInt &LHS, const APInt &RHS) const { 2641 return LHS.ult(RHS); 2642 } 2643 }; 2644 2645 // Some interesting folding opportunity is present, so its worthwhile to 2646 // re-generate the operands list. Group the operands by constant scale, 2647 // to avoid multiplying by the same constant scale multiple times. 2648 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2649 for (const SCEV *NewOp : NewOps) 2650 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2651 // Re-generate the operands list. 2652 Ops.clear(); 2653 if (AccumulatedConstant != 0) 2654 Ops.push_back(getConstant(AccumulatedConstant)); 2655 for (auto &MulOp : MulOpLists) { 2656 if (MulOp.first == 1) { 2657 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2658 } else if (MulOp.first != 0) { 2659 Ops.push_back(getMulExpr( 2660 getConstant(MulOp.first), 2661 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2662 SCEV::FlagAnyWrap, Depth + 1)); 2663 } 2664 } 2665 if (Ops.empty()) 2666 return getZero(Ty); 2667 if (Ops.size() == 1) 2668 return Ops[0]; 2669 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 } 2672 2673 // If we are adding something to a multiply expression, make sure the 2674 // something is not already an operand of the multiply. If so, merge it into 2675 // the multiply. 2676 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2677 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2678 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2679 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2680 if (isa<SCEVConstant>(MulOpSCEV)) 2681 continue; 2682 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2683 if (MulOpSCEV == Ops[AddOp]) { 2684 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2685 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2686 if (Mul->getNumOperands() != 2) { 2687 // If the multiply has more than two operands, we must get the 2688 // Y*Z term. 2689 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2690 Mul->op_begin()+MulOp); 2691 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2692 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2693 } 2694 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2695 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2696 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2697 SCEV::FlagAnyWrap, Depth + 1); 2698 if (Ops.size() == 2) return OuterMul; 2699 if (AddOp < Idx) { 2700 Ops.erase(Ops.begin()+AddOp); 2701 Ops.erase(Ops.begin()+Idx-1); 2702 } else { 2703 Ops.erase(Ops.begin()+Idx); 2704 Ops.erase(Ops.begin()+AddOp-1); 2705 } 2706 Ops.push_back(OuterMul); 2707 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2708 } 2709 2710 // Check this multiply against other multiplies being added together. 2711 for (unsigned OtherMulIdx = Idx+1; 2712 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2713 ++OtherMulIdx) { 2714 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2715 // If MulOp occurs in OtherMul, we can fold the two multiplies 2716 // together. 2717 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2718 OMulOp != e; ++OMulOp) 2719 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2720 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2721 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2722 if (Mul->getNumOperands() != 2) { 2723 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2724 Mul->op_begin()+MulOp); 2725 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2726 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2727 } 2728 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2729 if (OtherMul->getNumOperands() != 2) { 2730 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2731 OtherMul->op_begin()+OMulOp); 2732 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2733 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2734 } 2735 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2736 const SCEV *InnerMulSum = 2737 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2738 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2739 SCEV::FlagAnyWrap, Depth + 1); 2740 if (Ops.size() == 2) return OuterMul; 2741 Ops.erase(Ops.begin()+Idx); 2742 Ops.erase(Ops.begin()+OtherMulIdx-1); 2743 Ops.push_back(OuterMul); 2744 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2745 } 2746 } 2747 } 2748 } 2749 2750 // If there are any add recurrences in the operands list, see if any other 2751 // added values are loop invariant. If so, we can fold them into the 2752 // recurrence. 2753 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2754 ++Idx; 2755 2756 // Scan over all recurrences, trying to fold loop invariants into them. 2757 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2758 // Scan all of the other operands to this add and add them to the vector if 2759 // they are loop invariant w.r.t. the recurrence. 2760 SmallVector<const SCEV *, 8> LIOps; 2761 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2762 const Loop *AddRecLoop = AddRec->getLoop(); 2763 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2764 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2765 LIOps.push_back(Ops[i]); 2766 Ops.erase(Ops.begin()+i); 2767 --i; --e; 2768 } 2769 2770 // If we found some loop invariants, fold them into the recurrence. 2771 if (!LIOps.empty()) { 2772 // Compute nowrap flags for the addition of the loop-invariant ops and 2773 // the addrec. Temporarily push it as an operand for that purpose. 2774 LIOps.push_back(AddRec); 2775 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2776 LIOps.pop_back(); 2777 2778 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2779 LIOps.push_back(AddRec->getStart()); 2780 2781 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2782 // This follows from the fact that the no-wrap flags on the outer add 2783 // expression are applicable on the 0th iteration, when the add recurrence 2784 // will be equal to its start value. 2785 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2786 2787 // Build the new addrec. Propagate the NUW and NSW flags if both the 2788 // outer add and the inner addrec are guaranteed to have no overflow. 2789 // Always propagate NW. 2790 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2791 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2792 2793 // If all of the other operands were loop invariant, we are done. 2794 if (Ops.size() == 1) return NewRec; 2795 2796 // Otherwise, add the folded AddRec by the non-invariant parts. 2797 for (unsigned i = 0;; ++i) 2798 if (Ops[i] == AddRec) { 2799 Ops[i] = NewRec; 2800 break; 2801 } 2802 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2803 } 2804 2805 // Okay, if there weren't any loop invariants to be folded, check to see if 2806 // there are multiple AddRec's with the same loop induction variable being 2807 // added together. If so, we can fold them. 2808 for (unsigned OtherIdx = Idx+1; 2809 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2810 ++OtherIdx) { 2811 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2812 // so that the 1st found AddRecExpr is dominated by all others. 2813 assert(DT.dominates( 2814 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2815 AddRec->getLoop()->getHeader()) && 2816 "AddRecExprs are not sorted in reverse dominance order?"); 2817 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2818 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2819 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2820 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2821 ++OtherIdx) { 2822 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2823 if (OtherAddRec->getLoop() == AddRecLoop) { 2824 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2825 i != e; ++i) { 2826 if (i >= AddRecOps.size()) { 2827 AddRecOps.append(OtherAddRec->op_begin()+i, 2828 OtherAddRec->op_end()); 2829 break; 2830 } 2831 SmallVector<const SCEV *, 2> TwoOps = { 2832 AddRecOps[i], OtherAddRec->getOperand(i)}; 2833 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2834 } 2835 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2836 } 2837 } 2838 // Step size has changed, so we cannot guarantee no self-wraparound. 2839 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2840 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2841 } 2842 } 2843 2844 // Otherwise couldn't fold anything into this recurrence. Move onto the 2845 // next one. 2846 } 2847 2848 // Okay, it looks like we really DO need an add expr. Check to see if we 2849 // already have one, otherwise create a new one. 2850 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2851 } 2852 2853 const SCEV * 2854 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2855 SCEV::NoWrapFlags Flags) { 2856 FoldingSetNodeID ID; 2857 ID.AddInteger(scAddExpr); 2858 for (const SCEV *Op : Ops) 2859 ID.AddPointer(Op); 2860 void *IP = nullptr; 2861 SCEVAddExpr *S = 2862 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2863 if (!S) { 2864 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2865 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2866 S = new (SCEVAllocator) 2867 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2868 UniqueSCEVs.InsertNode(S, IP); 2869 addToLoopUseLists(S); 2870 } 2871 S->setNoWrapFlags(Flags); 2872 return S; 2873 } 2874 2875 const SCEV * 2876 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2877 const Loop *L, SCEV::NoWrapFlags Flags) { 2878 FoldingSetNodeID ID; 2879 ID.AddInteger(scAddRecExpr); 2880 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2881 ID.AddPointer(Ops[i]); 2882 ID.AddPointer(L); 2883 void *IP = nullptr; 2884 SCEVAddRecExpr *S = 2885 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2886 if (!S) { 2887 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2888 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2889 S = new (SCEVAllocator) 2890 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2891 UniqueSCEVs.InsertNode(S, IP); 2892 addToLoopUseLists(S); 2893 } 2894 setNoWrapFlags(S, Flags); 2895 return S; 2896 } 2897 2898 const SCEV * 2899 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2900 SCEV::NoWrapFlags Flags) { 2901 FoldingSetNodeID ID; 2902 ID.AddInteger(scMulExpr); 2903 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2904 ID.AddPointer(Ops[i]); 2905 void *IP = nullptr; 2906 SCEVMulExpr *S = 2907 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2908 if (!S) { 2909 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2910 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2911 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2912 O, Ops.size()); 2913 UniqueSCEVs.InsertNode(S, IP); 2914 addToLoopUseLists(S); 2915 } 2916 S->setNoWrapFlags(Flags); 2917 return S; 2918 } 2919 2920 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2921 uint64_t k = i*j; 2922 if (j > 1 && k / j != i) Overflow = true; 2923 return k; 2924 } 2925 2926 /// Compute the result of "n choose k", the binomial coefficient. If an 2927 /// intermediate computation overflows, Overflow will be set and the return will 2928 /// be garbage. Overflow is not cleared on absence of overflow. 2929 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2930 // We use the multiplicative formula: 2931 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2932 // At each iteration, we take the n-th term of the numeral and divide by the 2933 // (k-n)th term of the denominator. This division will always produce an 2934 // integral result, and helps reduce the chance of overflow in the 2935 // intermediate computations. However, we can still overflow even when the 2936 // final result would fit. 2937 2938 if (n == 0 || n == k) return 1; 2939 if (k > n) return 0; 2940 2941 if (k > n/2) 2942 k = n-k; 2943 2944 uint64_t r = 1; 2945 for (uint64_t i = 1; i <= k; ++i) { 2946 r = umul_ov(r, n-(i-1), Overflow); 2947 r /= i; 2948 } 2949 return r; 2950 } 2951 2952 /// Determine if any of the operands in this SCEV are a constant or if 2953 /// any of the add or multiply expressions in this SCEV contain a constant. 2954 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2955 struct FindConstantInAddMulChain { 2956 bool FoundConstant = false; 2957 2958 bool follow(const SCEV *S) { 2959 FoundConstant |= isa<SCEVConstant>(S); 2960 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2961 } 2962 2963 bool isDone() const { 2964 return FoundConstant; 2965 } 2966 }; 2967 2968 FindConstantInAddMulChain F; 2969 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2970 ST.visitAll(StartExpr); 2971 return F.FoundConstant; 2972 } 2973 2974 /// Get a canonical multiply expression, or something simpler if possible. 2975 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2976 SCEV::NoWrapFlags OrigFlags, 2977 unsigned Depth) { 2978 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2979 "only nuw or nsw allowed"); 2980 assert(!Ops.empty() && "Cannot get empty mul!"); 2981 if (Ops.size() == 1) return Ops[0]; 2982 #ifndef NDEBUG 2983 Type *ETy = Ops[0]->getType(); 2984 assert(!ETy->isPointerTy()); 2985 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2986 assert(Ops[i]->getType() == ETy && 2987 "SCEVMulExpr operand types don't match!"); 2988 #endif 2989 2990 // Sort by complexity, this groups all similar expression types together. 2991 GroupByComplexity(Ops, &LI, DT); 2992 2993 // If there are any constants, fold them together. 2994 unsigned Idx = 0; 2995 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2996 ++Idx; 2997 assert(Idx < Ops.size()); 2998 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2999 // We found two constants, fold them together! 3000 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3001 if (Ops.size() == 2) return Ops[0]; 3002 Ops.erase(Ops.begin()+1); // Erase the folded element 3003 LHSC = cast<SCEVConstant>(Ops[0]); 3004 } 3005 3006 // If we have a multiply of zero, it will always be zero. 3007 if (LHSC->getValue()->isZero()) 3008 return LHSC; 3009 3010 // If we are left with a constant one being multiplied, strip it off. 3011 if (LHSC->getValue()->isOne()) { 3012 Ops.erase(Ops.begin()); 3013 --Idx; 3014 } 3015 3016 if (Ops.size() == 1) 3017 return Ops[0]; 3018 } 3019 3020 // Delay expensive flag strengthening until necessary. 3021 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3022 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3023 }; 3024 3025 // Limit recursion calls depth. 3026 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3027 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3028 3029 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3030 // Don't strengthen flags if we have no new information. 3031 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3032 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3033 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3034 return S; 3035 } 3036 3037 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3038 if (Ops.size() == 2) { 3039 // C1*(C2+V) -> C1*C2 + C1*V 3040 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3041 // If any of Add's ops are Adds or Muls with a constant, apply this 3042 // transformation as well. 3043 // 3044 // TODO: There are some cases where this transformation is not 3045 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3046 // this transformation should be narrowed down. 3047 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3048 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3049 SCEV::FlagAnyWrap, Depth + 1), 3050 getMulExpr(LHSC, Add->getOperand(1), 3051 SCEV::FlagAnyWrap, Depth + 1), 3052 SCEV::FlagAnyWrap, Depth + 1); 3053 3054 if (Ops[0]->isAllOnesValue()) { 3055 // If we have a mul by -1 of an add, try distributing the -1 among the 3056 // add operands. 3057 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3058 SmallVector<const SCEV *, 4> NewOps; 3059 bool AnyFolded = false; 3060 for (const SCEV *AddOp : Add->operands()) { 3061 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3062 Depth + 1); 3063 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3064 NewOps.push_back(Mul); 3065 } 3066 if (AnyFolded) 3067 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3068 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3069 // Negation preserves a recurrence's no self-wrap property. 3070 SmallVector<const SCEV *, 4> Operands; 3071 for (const SCEV *AddRecOp : AddRec->operands()) 3072 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3073 Depth + 1)); 3074 3075 return getAddRecExpr(Operands, AddRec->getLoop(), 3076 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3077 } 3078 } 3079 } 3080 } 3081 3082 // Skip over the add expression until we get to a multiply. 3083 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3084 ++Idx; 3085 3086 // If there are mul operands inline them all into this expression. 3087 if (Idx < Ops.size()) { 3088 bool DeletedMul = false; 3089 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3090 if (Ops.size() > MulOpsInlineThreshold) 3091 break; 3092 // If we have an mul, expand the mul operands onto the end of the 3093 // operands list. 3094 Ops.erase(Ops.begin()+Idx); 3095 Ops.append(Mul->op_begin(), Mul->op_end()); 3096 DeletedMul = true; 3097 } 3098 3099 // If we deleted at least one mul, we added operands to the end of the 3100 // list, and they are not necessarily sorted. Recurse to resort and 3101 // resimplify any operands we just acquired. 3102 if (DeletedMul) 3103 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3104 } 3105 3106 // If there are any add recurrences in the operands list, see if any other 3107 // added values are loop invariant. If so, we can fold them into the 3108 // recurrence. 3109 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3110 ++Idx; 3111 3112 // Scan over all recurrences, trying to fold loop invariants into them. 3113 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3114 // Scan all of the other operands to this mul and add them to the vector 3115 // if they are loop invariant w.r.t. the recurrence. 3116 SmallVector<const SCEV *, 8> LIOps; 3117 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3118 const Loop *AddRecLoop = AddRec->getLoop(); 3119 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3120 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3121 LIOps.push_back(Ops[i]); 3122 Ops.erase(Ops.begin()+i); 3123 --i; --e; 3124 } 3125 3126 // If we found some loop invariants, fold them into the recurrence. 3127 if (!LIOps.empty()) { 3128 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3129 SmallVector<const SCEV *, 4> NewOps; 3130 NewOps.reserve(AddRec->getNumOperands()); 3131 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3132 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3133 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3134 SCEV::FlagAnyWrap, Depth + 1)); 3135 3136 // Build the new addrec. Propagate the NUW and NSW flags if both the 3137 // outer mul and the inner addrec are guaranteed to have no overflow. 3138 // 3139 // No self-wrap cannot be guaranteed after changing the step size, but 3140 // will be inferred if either NUW or NSW is true. 3141 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3142 const SCEV *NewRec = getAddRecExpr( 3143 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3144 3145 // If all of the other operands were loop invariant, we are done. 3146 if (Ops.size() == 1) return NewRec; 3147 3148 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3149 for (unsigned i = 0;; ++i) 3150 if (Ops[i] == AddRec) { 3151 Ops[i] = NewRec; 3152 break; 3153 } 3154 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3155 } 3156 3157 // Okay, if there weren't any loop invariants to be folded, check to see 3158 // if there are multiple AddRec's with the same loop induction variable 3159 // being multiplied together. If so, we can fold them. 3160 3161 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3162 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3163 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3164 // ]]],+,...up to x=2n}. 3165 // Note that the arguments to choose() are always integers with values 3166 // known at compile time, never SCEV objects. 3167 // 3168 // The implementation avoids pointless extra computations when the two 3169 // addrec's are of different length (mathematically, it's equivalent to 3170 // an infinite stream of zeros on the right). 3171 bool OpsModified = false; 3172 for (unsigned OtherIdx = Idx+1; 3173 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3174 ++OtherIdx) { 3175 const SCEVAddRecExpr *OtherAddRec = 3176 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3177 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3178 continue; 3179 3180 // Limit max number of arguments to avoid creation of unreasonably big 3181 // SCEVAddRecs with very complex operands. 3182 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3183 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3184 continue; 3185 3186 bool Overflow = false; 3187 Type *Ty = AddRec->getType(); 3188 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3189 SmallVector<const SCEV*, 7> AddRecOps; 3190 for (int x = 0, xe = AddRec->getNumOperands() + 3191 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3192 SmallVector <const SCEV *, 7> SumOps; 3193 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3194 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3195 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3196 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3197 z < ze && !Overflow; ++z) { 3198 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3199 uint64_t Coeff; 3200 if (LargerThan64Bits) 3201 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3202 else 3203 Coeff = Coeff1*Coeff2; 3204 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3205 const SCEV *Term1 = AddRec->getOperand(y-z); 3206 const SCEV *Term2 = OtherAddRec->getOperand(z); 3207 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3208 SCEV::FlagAnyWrap, Depth + 1)); 3209 } 3210 } 3211 if (SumOps.empty()) 3212 SumOps.push_back(getZero(Ty)); 3213 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3214 } 3215 if (!Overflow) { 3216 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3217 SCEV::FlagAnyWrap); 3218 if (Ops.size() == 2) return NewAddRec; 3219 Ops[Idx] = NewAddRec; 3220 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3221 OpsModified = true; 3222 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3223 if (!AddRec) 3224 break; 3225 } 3226 } 3227 if (OpsModified) 3228 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3229 3230 // Otherwise couldn't fold anything into this recurrence. Move onto the 3231 // next one. 3232 } 3233 3234 // Okay, it looks like we really DO need an mul expr. Check to see if we 3235 // already have one, otherwise create a new one. 3236 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3237 } 3238 3239 /// Represents an unsigned remainder expression based on unsigned division. 3240 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3241 const SCEV *RHS) { 3242 assert(getEffectiveSCEVType(LHS->getType()) == 3243 getEffectiveSCEVType(RHS->getType()) && 3244 "SCEVURemExpr operand types don't match!"); 3245 3246 // Short-circuit easy cases 3247 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3248 // If constant is one, the result is trivial 3249 if (RHSC->getValue()->isOne()) 3250 return getZero(LHS->getType()); // X urem 1 --> 0 3251 3252 // If constant is a power of two, fold into a zext(trunc(LHS)). 3253 if (RHSC->getAPInt().isPowerOf2()) { 3254 Type *FullTy = LHS->getType(); 3255 Type *TruncTy = 3256 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3257 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3258 } 3259 } 3260 3261 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3262 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3263 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3264 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3265 } 3266 3267 /// Get a canonical unsigned division expression, or something simpler if 3268 /// possible. 3269 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3270 const SCEV *RHS) { 3271 assert(!LHS->getType()->isPointerTy() && 3272 "SCEVUDivExpr operand can't be pointer!"); 3273 assert(LHS->getType() == RHS->getType() && 3274 "SCEVUDivExpr operand types don't match!"); 3275 3276 FoldingSetNodeID ID; 3277 ID.AddInteger(scUDivExpr); 3278 ID.AddPointer(LHS); 3279 ID.AddPointer(RHS); 3280 void *IP = nullptr; 3281 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3282 return S; 3283 3284 // 0 udiv Y == 0 3285 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3286 if (LHSC->getValue()->isZero()) 3287 return LHS; 3288 3289 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3290 if (RHSC->getValue()->isOne()) 3291 return LHS; // X udiv 1 --> x 3292 // If the denominator is zero, the result of the udiv is undefined. Don't 3293 // try to analyze it, because the resolution chosen here may differ from 3294 // the resolution chosen in other parts of the compiler. 3295 if (!RHSC->getValue()->isZero()) { 3296 // Determine if the division can be folded into the operands of 3297 // its operands. 3298 // TODO: Generalize this to non-constants by using known-bits information. 3299 Type *Ty = LHS->getType(); 3300 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3301 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3302 // For non-power-of-two values, effectively round the value up to the 3303 // nearest power of two. 3304 if (!RHSC->getAPInt().isPowerOf2()) 3305 ++MaxShiftAmt; 3306 IntegerType *ExtTy = 3307 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3308 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3309 if (const SCEVConstant *Step = 3310 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3311 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3312 const APInt &StepInt = Step->getAPInt(); 3313 const APInt &DivInt = RHSC->getAPInt(); 3314 if (!StepInt.urem(DivInt) && 3315 getZeroExtendExpr(AR, ExtTy) == 3316 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3317 getZeroExtendExpr(Step, ExtTy), 3318 AR->getLoop(), SCEV::FlagAnyWrap)) { 3319 SmallVector<const SCEV *, 4> Operands; 3320 for (const SCEV *Op : AR->operands()) 3321 Operands.push_back(getUDivExpr(Op, RHS)); 3322 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3323 } 3324 /// Get a canonical UDivExpr for a recurrence. 3325 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3326 // We can currently only fold X%N if X is constant. 3327 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3328 if (StartC && !DivInt.urem(StepInt) && 3329 getZeroExtendExpr(AR, ExtTy) == 3330 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3331 getZeroExtendExpr(Step, ExtTy), 3332 AR->getLoop(), SCEV::FlagAnyWrap)) { 3333 const APInt &StartInt = StartC->getAPInt(); 3334 const APInt &StartRem = StartInt.urem(StepInt); 3335 if (StartRem != 0) { 3336 const SCEV *NewLHS = 3337 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3338 AR->getLoop(), SCEV::FlagNW); 3339 if (LHS != NewLHS) { 3340 LHS = NewLHS; 3341 3342 // Reset the ID to include the new LHS, and check if it is 3343 // already cached. 3344 ID.clear(); 3345 ID.AddInteger(scUDivExpr); 3346 ID.AddPointer(LHS); 3347 ID.AddPointer(RHS); 3348 IP = nullptr; 3349 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3350 return S; 3351 } 3352 } 3353 } 3354 } 3355 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3356 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3357 SmallVector<const SCEV *, 4> Operands; 3358 for (const SCEV *Op : M->operands()) 3359 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3360 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3361 // Find an operand that's safely divisible. 3362 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3363 const SCEV *Op = M->getOperand(i); 3364 const SCEV *Div = getUDivExpr(Op, RHSC); 3365 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3366 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3367 Operands[i] = Div; 3368 return getMulExpr(Operands); 3369 } 3370 } 3371 } 3372 3373 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3374 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3375 if (auto *DivisorConstant = 3376 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3377 bool Overflow = false; 3378 APInt NewRHS = 3379 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3380 if (Overflow) { 3381 return getConstant(RHSC->getType(), 0, false); 3382 } 3383 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3384 } 3385 } 3386 3387 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3388 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3389 SmallVector<const SCEV *, 4> Operands; 3390 for (const SCEV *Op : A->operands()) 3391 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3392 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3393 Operands.clear(); 3394 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3395 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3396 if (isa<SCEVUDivExpr>(Op) || 3397 getMulExpr(Op, RHS) != A->getOperand(i)) 3398 break; 3399 Operands.push_back(Op); 3400 } 3401 if (Operands.size() == A->getNumOperands()) 3402 return getAddExpr(Operands); 3403 } 3404 } 3405 3406 // Fold if both operands are constant. 3407 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3408 Constant *LHSCV = LHSC->getValue(); 3409 Constant *RHSCV = RHSC->getValue(); 3410 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3411 RHSCV))); 3412 } 3413 } 3414 } 3415 3416 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3417 // changes). Make sure we get a new one. 3418 IP = nullptr; 3419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3420 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3421 LHS, RHS); 3422 UniqueSCEVs.InsertNode(S, IP); 3423 addToLoopUseLists(S); 3424 return S; 3425 } 3426 3427 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3428 APInt A = C1->getAPInt().abs(); 3429 APInt B = C2->getAPInt().abs(); 3430 uint32_t ABW = A.getBitWidth(); 3431 uint32_t BBW = B.getBitWidth(); 3432 3433 if (ABW > BBW) 3434 B = B.zext(ABW); 3435 else if (ABW < BBW) 3436 A = A.zext(BBW); 3437 3438 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3439 } 3440 3441 /// Get a canonical unsigned division expression, or something simpler if 3442 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3443 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3444 /// it's not exact because the udiv may be clearing bits. 3445 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3446 const SCEV *RHS) { 3447 // TODO: we could try to find factors in all sorts of things, but for now we 3448 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3449 // end of this file for inspiration. 3450 3451 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3452 if (!Mul || !Mul->hasNoUnsignedWrap()) 3453 return getUDivExpr(LHS, RHS); 3454 3455 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3456 // If the mulexpr multiplies by a constant, then that constant must be the 3457 // first element of the mulexpr. 3458 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3459 if (LHSCst == RHSCst) { 3460 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3461 return getMulExpr(Operands); 3462 } 3463 3464 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3465 // that there's a factor provided by one of the other terms. We need to 3466 // check. 3467 APInt Factor = gcd(LHSCst, RHSCst); 3468 if (!Factor.isIntN(1)) { 3469 LHSCst = 3470 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3471 RHSCst = 3472 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3473 SmallVector<const SCEV *, 2> Operands; 3474 Operands.push_back(LHSCst); 3475 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3476 LHS = getMulExpr(Operands); 3477 RHS = RHSCst; 3478 Mul = dyn_cast<SCEVMulExpr>(LHS); 3479 if (!Mul) 3480 return getUDivExactExpr(LHS, RHS); 3481 } 3482 } 3483 } 3484 3485 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3486 if (Mul->getOperand(i) == RHS) { 3487 SmallVector<const SCEV *, 2> Operands; 3488 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3489 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3490 return getMulExpr(Operands); 3491 } 3492 } 3493 3494 return getUDivExpr(LHS, RHS); 3495 } 3496 3497 /// Get an add recurrence expression for the specified loop. Simplify the 3498 /// expression as much as possible. 3499 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3500 const Loop *L, 3501 SCEV::NoWrapFlags Flags) { 3502 SmallVector<const SCEV *, 4> Operands; 3503 Operands.push_back(Start); 3504 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3505 if (StepChrec->getLoop() == L) { 3506 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3507 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3508 } 3509 3510 Operands.push_back(Step); 3511 return getAddRecExpr(Operands, L, Flags); 3512 } 3513 3514 /// Get an add recurrence expression for the specified loop. Simplify the 3515 /// expression as much as possible. 3516 const SCEV * 3517 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3518 const Loop *L, SCEV::NoWrapFlags Flags) { 3519 if (Operands.size() == 1) return Operands[0]; 3520 #ifndef NDEBUG 3521 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3522 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3523 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3524 "SCEVAddRecExpr operand types don't match!"); 3525 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3526 } 3527 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3528 assert(isLoopInvariant(Operands[i], L) && 3529 "SCEVAddRecExpr operand is not loop-invariant!"); 3530 #endif 3531 3532 if (Operands.back()->isZero()) { 3533 Operands.pop_back(); 3534 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3535 } 3536 3537 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3538 // use that information to infer NUW and NSW flags. However, computing a 3539 // BE count requires calling getAddRecExpr, so we may not yet have a 3540 // meaningful BE count at this point (and if we don't, we'd be stuck 3541 // with a SCEVCouldNotCompute as the cached BE count). 3542 3543 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3544 3545 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3546 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3547 const Loop *NestedLoop = NestedAR->getLoop(); 3548 if (L->contains(NestedLoop) 3549 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3550 : (!NestedLoop->contains(L) && 3551 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3552 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3553 Operands[0] = NestedAR->getStart(); 3554 // AddRecs require their operands be loop-invariant with respect to their 3555 // loops. Don't perform this transformation if it would break this 3556 // requirement. 3557 bool AllInvariant = all_of( 3558 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3559 3560 if (AllInvariant) { 3561 // Create a recurrence for the outer loop with the same step size. 3562 // 3563 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3564 // inner recurrence has the same property. 3565 SCEV::NoWrapFlags OuterFlags = 3566 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3567 3568 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3569 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3570 return isLoopInvariant(Op, NestedLoop); 3571 }); 3572 3573 if (AllInvariant) { 3574 // Ok, both add recurrences are valid after the transformation. 3575 // 3576 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3577 // the outer recurrence has the same property. 3578 SCEV::NoWrapFlags InnerFlags = 3579 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3580 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3581 } 3582 } 3583 // Reset Operands to its original state. 3584 Operands[0] = NestedAR; 3585 } 3586 } 3587 3588 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3589 // already have one, otherwise create a new one. 3590 return getOrCreateAddRecExpr(Operands, L, Flags); 3591 } 3592 3593 const SCEV * 3594 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3595 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3596 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3597 // getSCEV(Base)->getType() has the same address space as Base->getType() 3598 // because SCEV::getType() preserves the address space. 3599 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3600 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3601 // instruction to its SCEV, because the Instruction may be guarded by control 3602 // flow and the no-overflow bits may not be valid for the expression in any 3603 // context. This can be fixed similarly to how these flags are handled for 3604 // adds. 3605 SCEV::NoWrapFlags OffsetWrap = 3606 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3607 3608 Type *CurTy = GEP->getType(); 3609 bool FirstIter = true; 3610 SmallVector<const SCEV *, 4> Offsets; 3611 for (const SCEV *IndexExpr : IndexExprs) { 3612 // Compute the (potentially symbolic) offset in bytes for this index. 3613 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3614 // For a struct, add the member offset. 3615 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3616 unsigned FieldNo = Index->getZExtValue(); 3617 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3618 Offsets.push_back(FieldOffset); 3619 3620 // Update CurTy to the type of the field at Index. 3621 CurTy = STy->getTypeAtIndex(Index); 3622 } else { 3623 // Update CurTy to its element type. 3624 if (FirstIter) { 3625 assert(isa<PointerType>(CurTy) && 3626 "The first index of a GEP indexes a pointer"); 3627 CurTy = GEP->getSourceElementType(); 3628 FirstIter = false; 3629 } else { 3630 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3631 } 3632 // For an array, add the element offset, explicitly scaled. 3633 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3634 // Getelementptr indices are signed. 3635 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3636 3637 // Multiply the index by the element size to compute the element offset. 3638 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3639 Offsets.push_back(LocalOffset); 3640 } 3641 } 3642 3643 // Handle degenerate case of GEP without offsets. 3644 if (Offsets.empty()) 3645 return BaseExpr; 3646 3647 // Add the offsets together, assuming nsw if inbounds. 3648 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3649 // Add the base address and the offset. We cannot use the nsw flag, as the 3650 // base address is unsigned. However, if we know that the offset is 3651 // non-negative, we can use nuw. 3652 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3653 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3654 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3655 assert(BaseExpr->getType() == GEPExpr->getType() && 3656 "GEP should not change type mid-flight."); 3657 return GEPExpr; 3658 } 3659 3660 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3661 ArrayRef<const SCEV *> Ops) { 3662 FoldingSetNodeID ID; 3663 ID.AddInteger(SCEVType); 3664 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3665 ID.AddPointer(Ops[i]); 3666 void *IP = nullptr; 3667 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3668 } 3669 3670 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3671 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3672 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3673 } 3674 3675 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3676 SmallVectorImpl<const SCEV *> &Ops) { 3677 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3678 if (Ops.size() == 1) return Ops[0]; 3679 #ifndef NDEBUG 3680 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3681 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3682 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3683 "Operand types don't match!"); 3684 assert(Ops[0]->getType()->isPointerTy() == 3685 Ops[i]->getType()->isPointerTy() && 3686 "min/max should be consistently pointerish"); 3687 } 3688 #endif 3689 3690 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3691 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3692 3693 // Sort by complexity, this groups all similar expression types together. 3694 GroupByComplexity(Ops, &LI, DT); 3695 3696 // Check if we have created the same expression before. 3697 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3698 return S; 3699 } 3700 3701 // If there are any constants, fold them together. 3702 unsigned Idx = 0; 3703 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3704 ++Idx; 3705 assert(Idx < Ops.size()); 3706 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3707 if (Kind == scSMaxExpr) 3708 return APIntOps::smax(LHS, RHS); 3709 else if (Kind == scSMinExpr) 3710 return APIntOps::smin(LHS, RHS); 3711 else if (Kind == scUMaxExpr) 3712 return APIntOps::umax(LHS, RHS); 3713 else if (Kind == scUMinExpr) 3714 return APIntOps::umin(LHS, RHS); 3715 llvm_unreachable("Unknown SCEV min/max opcode"); 3716 }; 3717 3718 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3719 // We found two constants, fold them together! 3720 ConstantInt *Fold = ConstantInt::get( 3721 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3722 Ops[0] = getConstant(Fold); 3723 Ops.erase(Ops.begin()+1); // Erase the folded element 3724 if (Ops.size() == 1) return Ops[0]; 3725 LHSC = cast<SCEVConstant>(Ops[0]); 3726 } 3727 3728 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3729 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3730 3731 if (IsMax ? IsMinV : IsMaxV) { 3732 // If we are left with a constant minimum(/maximum)-int, strip it off. 3733 Ops.erase(Ops.begin()); 3734 --Idx; 3735 } else if (IsMax ? IsMaxV : IsMinV) { 3736 // If we have a max(/min) with a constant maximum(/minimum)-int, 3737 // it will always be the extremum. 3738 return LHSC; 3739 } 3740 3741 if (Ops.size() == 1) return Ops[0]; 3742 } 3743 3744 // Find the first operation of the same kind 3745 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3746 ++Idx; 3747 3748 // Check to see if one of the operands is of the same kind. If so, expand its 3749 // operands onto our operand list, and recurse to simplify. 3750 if (Idx < Ops.size()) { 3751 bool DeletedAny = false; 3752 while (Ops[Idx]->getSCEVType() == Kind) { 3753 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3754 Ops.erase(Ops.begin()+Idx); 3755 Ops.append(SMME->op_begin(), SMME->op_end()); 3756 DeletedAny = true; 3757 } 3758 3759 if (DeletedAny) 3760 return getMinMaxExpr(Kind, Ops); 3761 } 3762 3763 // Okay, check to see if the same value occurs in the operand list twice. If 3764 // so, delete one. Since we sorted the list, these values are required to 3765 // be adjacent. 3766 llvm::CmpInst::Predicate GEPred = 3767 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3768 llvm::CmpInst::Predicate LEPred = 3769 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3770 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3771 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3772 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3773 if (Ops[i] == Ops[i + 1] || 3774 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3775 // X op Y op Y --> X op Y 3776 // X op Y --> X, if we know X, Y are ordered appropriately 3777 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3778 --i; 3779 --e; 3780 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3781 Ops[i + 1])) { 3782 // X op Y --> Y, if we know X, Y are ordered appropriately 3783 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3784 --i; 3785 --e; 3786 } 3787 } 3788 3789 if (Ops.size() == 1) return Ops[0]; 3790 3791 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3792 3793 // Okay, it looks like we really DO need an expr. Check to see if we 3794 // already have one, otherwise create a new one. 3795 FoldingSetNodeID ID; 3796 ID.AddInteger(Kind); 3797 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3798 ID.AddPointer(Ops[i]); 3799 void *IP = nullptr; 3800 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3801 if (ExistingSCEV) 3802 return ExistingSCEV; 3803 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3804 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3805 SCEV *S = new (SCEVAllocator) 3806 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3807 3808 UniqueSCEVs.InsertNode(S, IP); 3809 addToLoopUseLists(S); 3810 return S; 3811 } 3812 3813 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3814 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3815 return getSMaxExpr(Ops); 3816 } 3817 3818 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3819 return getMinMaxExpr(scSMaxExpr, Ops); 3820 } 3821 3822 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3823 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3824 return getUMaxExpr(Ops); 3825 } 3826 3827 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3828 return getMinMaxExpr(scUMaxExpr, Ops); 3829 } 3830 3831 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3832 const SCEV *RHS) { 3833 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3834 return getSMinExpr(Ops); 3835 } 3836 3837 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3838 return getMinMaxExpr(scSMinExpr, Ops); 3839 } 3840 3841 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3842 const SCEV *RHS) { 3843 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3844 return getUMinExpr(Ops); 3845 } 3846 3847 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3848 return getMinMaxExpr(scUMinExpr, Ops); 3849 } 3850 3851 const SCEV * 3852 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3853 ScalableVectorType *ScalableTy) { 3854 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3855 Constant *One = ConstantInt::get(IntTy, 1); 3856 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3857 // Note that the expression we created is the final expression, we don't 3858 // want to simplify it any further Also, if we call a normal getSCEV(), 3859 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3860 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3861 } 3862 3863 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3864 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3865 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3866 // We can bypass creating a target-independent constant expression and then 3867 // folding it back into a ConstantInt. This is just a compile-time 3868 // optimization. 3869 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3870 } 3871 3872 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3873 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3874 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3875 // We can bypass creating a target-independent constant expression and then 3876 // folding it back into a ConstantInt. This is just a compile-time 3877 // optimization. 3878 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3879 } 3880 3881 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3882 StructType *STy, 3883 unsigned FieldNo) { 3884 // We can bypass creating a target-independent constant expression and then 3885 // folding it back into a ConstantInt. This is just a compile-time 3886 // optimization. 3887 return getConstant( 3888 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3889 } 3890 3891 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3892 // Don't attempt to do anything other than create a SCEVUnknown object 3893 // here. createSCEV only calls getUnknown after checking for all other 3894 // interesting possibilities, and any other code that calls getUnknown 3895 // is doing so in order to hide a value from SCEV canonicalization. 3896 3897 FoldingSetNodeID ID; 3898 ID.AddInteger(scUnknown); 3899 ID.AddPointer(V); 3900 void *IP = nullptr; 3901 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3902 assert(cast<SCEVUnknown>(S)->getValue() == V && 3903 "Stale SCEVUnknown in uniquing map!"); 3904 return S; 3905 } 3906 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3907 FirstUnknown); 3908 FirstUnknown = cast<SCEVUnknown>(S); 3909 UniqueSCEVs.InsertNode(S, IP); 3910 return S; 3911 } 3912 3913 //===----------------------------------------------------------------------===// 3914 // Basic SCEV Analysis and PHI Idiom Recognition Code 3915 // 3916 3917 /// Test if values of the given type are analyzable within the SCEV 3918 /// framework. This primarily includes integer types, and it can optionally 3919 /// include pointer types if the ScalarEvolution class has access to 3920 /// target-specific information. 3921 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3922 // Integers and pointers are always SCEVable. 3923 return Ty->isIntOrPtrTy(); 3924 } 3925 3926 /// Return the size in bits of the specified type, for which isSCEVable must 3927 /// return true. 3928 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3929 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3930 if (Ty->isPointerTy()) 3931 return getDataLayout().getIndexTypeSizeInBits(Ty); 3932 return getDataLayout().getTypeSizeInBits(Ty); 3933 } 3934 3935 /// Return a type with the same bitwidth as the given type and which represents 3936 /// how SCEV will treat the given type, for which isSCEVable must return 3937 /// true. For pointer types, this is the pointer index sized integer type. 3938 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3939 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3940 3941 if (Ty->isIntegerTy()) 3942 return Ty; 3943 3944 // The only other support type is pointer. 3945 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3946 return getDataLayout().getIndexType(Ty); 3947 } 3948 3949 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3950 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3951 } 3952 3953 const SCEV *ScalarEvolution::getCouldNotCompute() { 3954 return CouldNotCompute.get(); 3955 } 3956 3957 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3958 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3959 auto *SU = dyn_cast<SCEVUnknown>(S); 3960 return SU && SU->getValue() == nullptr; 3961 }); 3962 3963 return !ContainsNulls; 3964 } 3965 3966 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3967 HasRecMapType::iterator I = HasRecMap.find(S); 3968 if (I != HasRecMap.end()) 3969 return I->second; 3970 3971 bool FoundAddRec = 3972 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3973 HasRecMap.insert({S, FoundAddRec}); 3974 return FoundAddRec; 3975 } 3976 3977 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3978 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3979 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3980 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3981 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3982 if (!Add) 3983 return {S, nullptr}; 3984 3985 if (Add->getNumOperands() != 2) 3986 return {S, nullptr}; 3987 3988 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3989 if (!ConstOp) 3990 return {S, nullptr}; 3991 3992 return {Add->getOperand(1), ConstOp->getValue()}; 3993 } 3994 3995 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3996 /// by the value and offset from any ValueOffsetPair in the set. 3997 ScalarEvolution::ValueOffsetPairSetVector * 3998 ScalarEvolution::getSCEVValues(const SCEV *S) { 3999 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4000 if (SI == ExprValueMap.end()) 4001 return nullptr; 4002 #ifndef NDEBUG 4003 if (VerifySCEVMap) { 4004 // Check there is no dangling Value in the set returned. 4005 for (const auto &VE : SI->second) 4006 assert(ValueExprMap.count(VE.first)); 4007 } 4008 #endif 4009 return &SI->second; 4010 } 4011 4012 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4013 /// cannot be used separately. eraseValueFromMap should be used to remove 4014 /// V from ValueExprMap and ExprValueMap at the same time. 4015 void ScalarEvolution::eraseValueFromMap(Value *V) { 4016 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4017 if (I != ValueExprMap.end()) { 4018 const SCEV *S = I->second; 4019 // Remove {V, 0} from the set of ExprValueMap[S] 4020 if (auto *SV = getSCEVValues(S)) 4021 SV->remove({V, nullptr}); 4022 4023 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4024 const SCEV *Stripped; 4025 ConstantInt *Offset; 4026 std::tie(Stripped, Offset) = splitAddExpr(S); 4027 if (Offset != nullptr) { 4028 if (auto *SV = getSCEVValues(Stripped)) 4029 SV->remove({V, Offset}); 4030 } 4031 ValueExprMap.erase(V); 4032 } 4033 } 4034 4035 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4036 /// TODO: In reality it is better to check the poison recursively 4037 /// but this is better than nothing. 4038 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4039 if (auto *I = dyn_cast<Instruction>(V)) { 4040 if (isa<OverflowingBinaryOperator>(I)) { 4041 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4042 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4043 return true; 4044 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4045 return true; 4046 } 4047 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4048 return true; 4049 } 4050 return false; 4051 } 4052 4053 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4054 /// create a new one. 4055 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4056 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4057 4058 const SCEV *S = getExistingSCEV(V); 4059 if (S == nullptr) { 4060 S = createSCEV(V); 4061 // During PHI resolution, it is possible to create two SCEVs for the same 4062 // V, so it is needed to double check whether V->S is inserted into 4063 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4064 std::pair<ValueExprMapType::iterator, bool> Pair = 4065 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4066 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4067 ExprValueMap[S].insert({V, nullptr}); 4068 4069 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4070 // ExprValueMap. 4071 const SCEV *Stripped = S; 4072 ConstantInt *Offset = nullptr; 4073 std::tie(Stripped, Offset) = splitAddExpr(S); 4074 // If stripped is SCEVUnknown, don't bother to save 4075 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4076 // increase the complexity of the expansion code. 4077 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4078 // because it may generate add/sub instead of GEP in SCEV expansion. 4079 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4080 !isa<GetElementPtrInst>(V)) 4081 ExprValueMap[Stripped].insert({V, Offset}); 4082 } 4083 } 4084 return S; 4085 } 4086 4087 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4088 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4089 4090 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4091 if (I != ValueExprMap.end()) { 4092 const SCEV *S = I->second; 4093 if (checkValidity(S)) 4094 return S; 4095 eraseValueFromMap(V); 4096 forgetMemoizedResults(S); 4097 } 4098 return nullptr; 4099 } 4100 4101 /// Return a SCEV corresponding to -V = -1*V 4102 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4103 SCEV::NoWrapFlags Flags) { 4104 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4105 return getConstant( 4106 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4107 4108 Type *Ty = V->getType(); 4109 Ty = getEffectiveSCEVType(Ty); 4110 return getMulExpr(V, getMinusOne(Ty), Flags); 4111 } 4112 4113 /// If Expr computes ~A, return A else return nullptr 4114 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4115 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4116 if (!Add || Add->getNumOperands() != 2 || 4117 !Add->getOperand(0)->isAllOnesValue()) 4118 return nullptr; 4119 4120 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4121 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4122 !AddRHS->getOperand(0)->isAllOnesValue()) 4123 return nullptr; 4124 4125 return AddRHS->getOperand(1); 4126 } 4127 4128 /// Return a SCEV corresponding to ~V = -1-V 4129 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4130 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4131 4132 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4133 return getConstant( 4134 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4135 4136 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4137 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4138 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4139 SmallVector<const SCEV *, 2> MatchedOperands; 4140 for (const SCEV *Operand : MME->operands()) { 4141 const SCEV *Matched = MatchNotExpr(Operand); 4142 if (!Matched) 4143 return (const SCEV *)nullptr; 4144 MatchedOperands.push_back(Matched); 4145 } 4146 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4147 MatchedOperands); 4148 }; 4149 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4150 return Replaced; 4151 } 4152 4153 Type *Ty = V->getType(); 4154 Ty = getEffectiveSCEVType(Ty); 4155 return getMinusSCEV(getMinusOne(Ty), V); 4156 } 4157 4158 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4159 assert(P->getType()->isPointerTy()); 4160 4161 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4162 // The base of an AddRec is the first operand. 4163 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4164 Ops[0] = removePointerBase(Ops[0]); 4165 // Don't try to transfer nowrap flags for now. We could in some cases 4166 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4167 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4168 } 4169 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4170 // The base of an Add is the pointer operand. 4171 SmallVector<const SCEV *> Ops{Add->operands()}; 4172 const SCEV **PtrOp = nullptr; 4173 for (const SCEV *&AddOp : Ops) { 4174 if (AddOp->getType()->isPointerTy()) { 4175 assert(!PtrOp && "Cannot have multiple pointer ops"); 4176 PtrOp = &AddOp; 4177 } 4178 } 4179 *PtrOp = removePointerBase(*PtrOp); 4180 // Don't try to transfer nowrap flags for now. We could in some cases 4181 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4182 return getAddExpr(Ops); 4183 } 4184 // Any other expression must be a pointer base. 4185 return getZero(P->getType()); 4186 } 4187 4188 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4189 SCEV::NoWrapFlags Flags, 4190 unsigned Depth) { 4191 // Fast path: X - X --> 0. 4192 if (LHS == RHS) 4193 return getZero(LHS->getType()); 4194 4195 // If we subtract two pointers with different pointer bases, bail. 4196 // Eventually, we're going to add an assertion to getMulExpr that we 4197 // can't multiply by a pointer. 4198 if (RHS->getType()->isPointerTy()) { 4199 if (!LHS->getType()->isPointerTy() || 4200 getPointerBase(LHS) != getPointerBase(RHS)) 4201 return getCouldNotCompute(); 4202 LHS = removePointerBase(LHS); 4203 RHS = removePointerBase(RHS); 4204 } 4205 4206 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4207 // makes it so that we cannot make much use of NUW. 4208 auto AddFlags = SCEV::FlagAnyWrap; 4209 const bool RHSIsNotMinSigned = 4210 !getSignedRangeMin(RHS).isMinSignedValue(); 4211 if (hasFlags(Flags, SCEV::FlagNSW)) { 4212 // Let M be the minimum representable signed value. Then (-1)*RHS 4213 // signed-wraps if and only if RHS is M. That can happen even for 4214 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4215 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4216 // (-1)*RHS, we need to prove that RHS != M. 4217 // 4218 // If LHS is non-negative and we know that LHS - RHS does not 4219 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4220 // either by proving that RHS > M or that LHS >= 0. 4221 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4222 AddFlags = SCEV::FlagNSW; 4223 } 4224 } 4225 4226 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4227 // RHS is NSW and LHS >= 0. 4228 // 4229 // The difficulty here is that the NSW flag may have been proven 4230 // relative to a loop that is to be found in a recurrence in LHS and 4231 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4232 // larger scope than intended. 4233 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4234 4235 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4236 } 4237 4238 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4239 unsigned Depth) { 4240 Type *SrcTy = V->getType(); 4241 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4242 "Cannot truncate or zero extend with non-integer arguments!"); 4243 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4244 return V; // No conversion 4245 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4246 return getTruncateExpr(V, Ty, Depth); 4247 return getZeroExtendExpr(V, Ty, Depth); 4248 } 4249 4250 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4251 unsigned Depth) { 4252 Type *SrcTy = V->getType(); 4253 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4254 "Cannot truncate or zero extend with non-integer arguments!"); 4255 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4256 return V; // No conversion 4257 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4258 return getTruncateExpr(V, Ty, Depth); 4259 return getSignExtendExpr(V, Ty, Depth); 4260 } 4261 4262 const SCEV * 4263 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4264 Type *SrcTy = V->getType(); 4265 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4266 "Cannot noop or zero extend with non-integer arguments!"); 4267 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4268 "getNoopOrZeroExtend cannot truncate!"); 4269 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4270 return V; // No conversion 4271 return getZeroExtendExpr(V, Ty); 4272 } 4273 4274 const SCEV * 4275 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4276 Type *SrcTy = V->getType(); 4277 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4278 "Cannot noop or sign extend with non-integer arguments!"); 4279 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4280 "getNoopOrSignExtend cannot truncate!"); 4281 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4282 return V; // No conversion 4283 return getSignExtendExpr(V, Ty); 4284 } 4285 4286 const SCEV * 4287 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4288 Type *SrcTy = V->getType(); 4289 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4290 "Cannot noop or any extend with non-integer arguments!"); 4291 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4292 "getNoopOrAnyExtend cannot truncate!"); 4293 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4294 return V; // No conversion 4295 return getAnyExtendExpr(V, Ty); 4296 } 4297 4298 const SCEV * 4299 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4300 Type *SrcTy = V->getType(); 4301 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4302 "Cannot truncate or noop with non-integer arguments!"); 4303 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4304 "getTruncateOrNoop cannot extend!"); 4305 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4306 return V; // No conversion 4307 return getTruncateExpr(V, Ty); 4308 } 4309 4310 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4311 const SCEV *RHS) { 4312 const SCEV *PromotedLHS = LHS; 4313 const SCEV *PromotedRHS = RHS; 4314 4315 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4316 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4317 else 4318 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4319 4320 return getUMaxExpr(PromotedLHS, PromotedRHS); 4321 } 4322 4323 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4324 const SCEV *RHS) { 4325 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4326 return getUMinFromMismatchedTypes(Ops); 4327 } 4328 4329 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4330 SmallVectorImpl<const SCEV *> &Ops) { 4331 assert(!Ops.empty() && "At least one operand must be!"); 4332 // Trivial case. 4333 if (Ops.size() == 1) 4334 return Ops[0]; 4335 4336 // Find the max type first. 4337 Type *MaxType = nullptr; 4338 for (auto *S : Ops) 4339 if (MaxType) 4340 MaxType = getWiderType(MaxType, S->getType()); 4341 else 4342 MaxType = S->getType(); 4343 assert(MaxType && "Failed to find maximum type!"); 4344 4345 // Extend all ops to max type. 4346 SmallVector<const SCEV *, 2> PromotedOps; 4347 for (auto *S : Ops) 4348 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4349 4350 // Generate umin. 4351 return getUMinExpr(PromotedOps); 4352 } 4353 4354 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4355 // A pointer operand may evaluate to a nonpointer expression, such as null. 4356 if (!V->getType()->isPointerTy()) 4357 return V; 4358 4359 while (true) { 4360 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4361 V = AddRec->getStart(); 4362 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4363 const SCEV *PtrOp = nullptr; 4364 for (const SCEV *AddOp : Add->operands()) { 4365 if (AddOp->getType()->isPointerTy()) { 4366 assert(!PtrOp && "Cannot have multiple pointer ops"); 4367 PtrOp = AddOp; 4368 } 4369 } 4370 assert(PtrOp && "Must have pointer op"); 4371 V = PtrOp; 4372 } else // Not something we can look further into. 4373 return V; 4374 } 4375 } 4376 4377 /// Push users of the given Instruction onto the given Worklist. 4378 static void 4379 PushDefUseChildren(Instruction *I, 4380 SmallVectorImpl<Instruction *> &Worklist) { 4381 // Push the def-use children onto the Worklist stack. 4382 for (User *U : I->users()) 4383 Worklist.push_back(cast<Instruction>(U)); 4384 } 4385 4386 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4387 SmallVector<Instruction *, 16> Worklist; 4388 PushDefUseChildren(PN, Worklist); 4389 4390 SmallPtrSet<Instruction *, 8> Visited; 4391 Visited.insert(PN); 4392 while (!Worklist.empty()) { 4393 Instruction *I = Worklist.pop_back_val(); 4394 if (!Visited.insert(I).second) 4395 continue; 4396 4397 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4398 if (It != ValueExprMap.end()) { 4399 const SCEV *Old = It->second; 4400 4401 // Short-circuit the def-use traversal if the symbolic name 4402 // ceases to appear in expressions. 4403 if (Old != SymName && !hasOperand(Old, SymName)) 4404 continue; 4405 4406 // SCEVUnknown for a PHI either means that it has an unrecognized 4407 // structure, it's a PHI that's in the progress of being computed 4408 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4409 // additional loop trip count information isn't going to change anything. 4410 // In the second case, createNodeForPHI will perform the necessary 4411 // updates on its own when it gets to that point. In the third, we do 4412 // want to forget the SCEVUnknown. 4413 if (!isa<PHINode>(I) || 4414 !isa<SCEVUnknown>(Old) || 4415 (I != PN && Old == SymName)) { 4416 eraseValueFromMap(It->first); 4417 forgetMemoizedResults(Old); 4418 } 4419 } 4420 4421 PushDefUseChildren(I, Worklist); 4422 } 4423 } 4424 4425 namespace { 4426 4427 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4428 /// expression in case its Loop is L. If it is not L then 4429 /// if IgnoreOtherLoops is true then use AddRec itself 4430 /// otherwise rewrite cannot be done. 4431 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4432 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4433 public: 4434 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4435 bool IgnoreOtherLoops = true) { 4436 SCEVInitRewriter Rewriter(L, SE); 4437 const SCEV *Result = Rewriter.visit(S); 4438 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4439 return SE.getCouldNotCompute(); 4440 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4441 ? SE.getCouldNotCompute() 4442 : Result; 4443 } 4444 4445 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4446 if (!SE.isLoopInvariant(Expr, L)) 4447 SeenLoopVariantSCEVUnknown = true; 4448 return Expr; 4449 } 4450 4451 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4452 // Only re-write AddRecExprs for this loop. 4453 if (Expr->getLoop() == L) 4454 return Expr->getStart(); 4455 SeenOtherLoops = true; 4456 return Expr; 4457 } 4458 4459 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4460 4461 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4462 4463 private: 4464 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4465 : SCEVRewriteVisitor(SE), L(L) {} 4466 4467 const Loop *L; 4468 bool SeenLoopVariantSCEVUnknown = false; 4469 bool SeenOtherLoops = false; 4470 }; 4471 4472 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4473 /// increment expression in case its Loop is L. If it is not L then 4474 /// use AddRec itself. 4475 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4476 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4477 public: 4478 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4479 SCEVPostIncRewriter Rewriter(L, SE); 4480 const SCEV *Result = Rewriter.visit(S); 4481 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4482 ? SE.getCouldNotCompute() 4483 : Result; 4484 } 4485 4486 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4487 if (!SE.isLoopInvariant(Expr, L)) 4488 SeenLoopVariantSCEVUnknown = true; 4489 return Expr; 4490 } 4491 4492 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4493 // Only re-write AddRecExprs for this loop. 4494 if (Expr->getLoop() == L) 4495 return Expr->getPostIncExpr(SE); 4496 SeenOtherLoops = true; 4497 return Expr; 4498 } 4499 4500 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4501 4502 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4503 4504 private: 4505 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4506 : SCEVRewriteVisitor(SE), L(L) {} 4507 4508 const Loop *L; 4509 bool SeenLoopVariantSCEVUnknown = false; 4510 bool SeenOtherLoops = false; 4511 }; 4512 4513 /// This class evaluates the compare condition by matching it against the 4514 /// condition of loop latch. If there is a match we assume a true value 4515 /// for the condition while building SCEV nodes. 4516 class SCEVBackedgeConditionFolder 4517 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4518 public: 4519 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4520 ScalarEvolution &SE) { 4521 bool IsPosBECond = false; 4522 Value *BECond = nullptr; 4523 if (BasicBlock *Latch = L->getLoopLatch()) { 4524 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4525 if (BI && BI->isConditional()) { 4526 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4527 "Both outgoing branches should not target same header!"); 4528 BECond = BI->getCondition(); 4529 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4530 } else { 4531 return S; 4532 } 4533 } 4534 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4535 return Rewriter.visit(S); 4536 } 4537 4538 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4539 const SCEV *Result = Expr; 4540 bool InvariantF = SE.isLoopInvariant(Expr, L); 4541 4542 if (!InvariantF) { 4543 Instruction *I = cast<Instruction>(Expr->getValue()); 4544 switch (I->getOpcode()) { 4545 case Instruction::Select: { 4546 SelectInst *SI = cast<SelectInst>(I); 4547 Optional<const SCEV *> Res = 4548 compareWithBackedgeCondition(SI->getCondition()); 4549 if (Res.hasValue()) { 4550 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4551 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4552 } 4553 break; 4554 } 4555 default: { 4556 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4557 if (Res.hasValue()) 4558 Result = Res.getValue(); 4559 break; 4560 } 4561 } 4562 } 4563 return Result; 4564 } 4565 4566 private: 4567 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4568 bool IsPosBECond, ScalarEvolution &SE) 4569 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4570 IsPositiveBECond(IsPosBECond) {} 4571 4572 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4573 4574 const Loop *L; 4575 /// Loop back condition. 4576 Value *BackedgeCond = nullptr; 4577 /// Set to true if loop back is on positive branch condition. 4578 bool IsPositiveBECond; 4579 }; 4580 4581 Optional<const SCEV *> 4582 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4583 4584 // If value matches the backedge condition for loop latch, 4585 // then return a constant evolution node based on loopback 4586 // branch taken. 4587 if (BackedgeCond == IC) 4588 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4589 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4590 return None; 4591 } 4592 4593 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4594 public: 4595 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4596 ScalarEvolution &SE) { 4597 SCEVShiftRewriter Rewriter(L, SE); 4598 const SCEV *Result = Rewriter.visit(S); 4599 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4600 } 4601 4602 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4603 // Only allow AddRecExprs for this loop. 4604 if (!SE.isLoopInvariant(Expr, L)) 4605 Valid = false; 4606 return Expr; 4607 } 4608 4609 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4610 if (Expr->getLoop() == L && Expr->isAffine()) 4611 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4612 Valid = false; 4613 return Expr; 4614 } 4615 4616 bool isValid() { return Valid; } 4617 4618 private: 4619 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4620 : SCEVRewriteVisitor(SE), L(L) {} 4621 4622 const Loop *L; 4623 bool Valid = true; 4624 }; 4625 4626 } // end anonymous namespace 4627 4628 SCEV::NoWrapFlags 4629 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4630 if (!AR->isAffine()) 4631 return SCEV::FlagAnyWrap; 4632 4633 using OBO = OverflowingBinaryOperator; 4634 4635 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4636 4637 if (!AR->hasNoSignedWrap()) { 4638 ConstantRange AddRecRange = getSignedRange(AR); 4639 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4640 4641 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4642 Instruction::Add, IncRange, OBO::NoSignedWrap); 4643 if (NSWRegion.contains(AddRecRange)) 4644 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4645 } 4646 4647 if (!AR->hasNoUnsignedWrap()) { 4648 ConstantRange AddRecRange = getUnsignedRange(AR); 4649 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4650 4651 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4652 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4653 if (NUWRegion.contains(AddRecRange)) 4654 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4655 } 4656 4657 return Result; 4658 } 4659 4660 SCEV::NoWrapFlags 4661 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4662 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4663 4664 if (AR->hasNoSignedWrap()) 4665 return Result; 4666 4667 if (!AR->isAffine()) 4668 return Result; 4669 4670 const SCEV *Step = AR->getStepRecurrence(*this); 4671 const Loop *L = AR->getLoop(); 4672 4673 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4674 // Note that this serves two purposes: It filters out loops that are 4675 // simply not analyzable, and it covers the case where this code is 4676 // being called from within backedge-taken count analysis, such that 4677 // attempting to ask for the backedge-taken count would likely result 4678 // in infinite recursion. In the later case, the analysis code will 4679 // cope with a conservative value, and it will take care to purge 4680 // that value once it has finished. 4681 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4682 4683 // Normally, in the cases we can prove no-overflow via a 4684 // backedge guarding condition, we can also compute a backedge 4685 // taken count for the loop. The exceptions are assumptions and 4686 // guards present in the loop -- SCEV is not great at exploiting 4687 // these to compute max backedge taken counts, but can still use 4688 // these to prove lack of overflow. Use this fact to avoid 4689 // doing extra work that may not pay off. 4690 4691 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4692 AC.assumptions().empty()) 4693 return Result; 4694 4695 // If the backedge is guarded by a comparison with the pre-inc value the 4696 // addrec is safe. Also, if the entry is guarded by a comparison with the 4697 // start value and the backedge is guarded by a comparison with the post-inc 4698 // value, the addrec is safe. 4699 ICmpInst::Predicate Pred; 4700 const SCEV *OverflowLimit = 4701 getSignedOverflowLimitForStep(Step, &Pred, this); 4702 if (OverflowLimit && 4703 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4704 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4705 Result = setFlags(Result, SCEV::FlagNSW); 4706 } 4707 return Result; 4708 } 4709 SCEV::NoWrapFlags 4710 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4711 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4712 4713 if (AR->hasNoUnsignedWrap()) 4714 return Result; 4715 4716 if (!AR->isAffine()) 4717 return Result; 4718 4719 const SCEV *Step = AR->getStepRecurrence(*this); 4720 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4721 const Loop *L = AR->getLoop(); 4722 4723 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4724 // Note that this serves two purposes: It filters out loops that are 4725 // simply not analyzable, and it covers the case where this code is 4726 // being called from within backedge-taken count analysis, such that 4727 // attempting to ask for the backedge-taken count would likely result 4728 // in infinite recursion. In the later case, the analysis code will 4729 // cope with a conservative value, and it will take care to purge 4730 // that value once it has finished. 4731 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4732 4733 // Normally, in the cases we can prove no-overflow via a 4734 // backedge guarding condition, we can also compute a backedge 4735 // taken count for the loop. The exceptions are assumptions and 4736 // guards present in the loop -- SCEV is not great at exploiting 4737 // these to compute max backedge taken counts, but can still use 4738 // these to prove lack of overflow. Use this fact to avoid 4739 // doing extra work that may not pay off. 4740 4741 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4742 AC.assumptions().empty()) 4743 return Result; 4744 4745 // If the backedge is guarded by a comparison with the pre-inc value the 4746 // addrec is safe. Also, if the entry is guarded by a comparison with the 4747 // start value and the backedge is guarded by a comparison with the post-inc 4748 // value, the addrec is safe. 4749 if (isKnownPositive(Step)) { 4750 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4751 getUnsignedRangeMax(Step)); 4752 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4753 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4754 Result = setFlags(Result, SCEV::FlagNUW); 4755 } 4756 } 4757 4758 return Result; 4759 } 4760 4761 namespace { 4762 4763 /// Represents an abstract binary operation. This may exist as a 4764 /// normal instruction or constant expression, or may have been 4765 /// derived from an expression tree. 4766 struct BinaryOp { 4767 unsigned Opcode; 4768 Value *LHS; 4769 Value *RHS; 4770 bool IsNSW = false; 4771 bool IsNUW = false; 4772 4773 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4774 /// constant expression. 4775 Operator *Op = nullptr; 4776 4777 explicit BinaryOp(Operator *Op) 4778 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4779 Op(Op) { 4780 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4781 IsNSW = OBO->hasNoSignedWrap(); 4782 IsNUW = OBO->hasNoUnsignedWrap(); 4783 } 4784 } 4785 4786 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4787 bool IsNUW = false) 4788 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4789 }; 4790 4791 } // end anonymous namespace 4792 4793 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4794 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4795 auto *Op = dyn_cast<Operator>(V); 4796 if (!Op) 4797 return None; 4798 4799 // Implementation detail: all the cleverness here should happen without 4800 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4801 // SCEV expressions when possible, and we should not break that. 4802 4803 switch (Op->getOpcode()) { 4804 case Instruction::Add: 4805 case Instruction::Sub: 4806 case Instruction::Mul: 4807 case Instruction::UDiv: 4808 case Instruction::URem: 4809 case Instruction::And: 4810 case Instruction::Or: 4811 case Instruction::AShr: 4812 case Instruction::Shl: 4813 return BinaryOp(Op); 4814 4815 case Instruction::Xor: 4816 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4817 // If the RHS of the xor is a signmask, then this is just an add. 4818 // Instcombine turns add of signmask into xor as a strength reduction step. 4819 if (RHSC->getValue().isSignMask()) 4820 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4821 return BinaryOp(Op); 4822 4823 case Instruction::LShr: 4824 // Turn logical shift right of a constant into a unsigned divide. 4825 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4826 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4827 4828 // If the shift count is not less than the bitwidth, the result of 4829 // the shift is undefined. Don't try to analyze it, because the 4830 // resolution chosen here may differ from the resolution chosen in 4831 // other parts of the compiler. 4832 if (SA->getValue().ult(BitWidth)) { 4833 Constant *X = 4834 ConstantInt::get(SA->getContext(), 4835 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4836 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4837 } 4838 } 4839 return BinaryOp(Op); 4840 4841 case Instruction::ExtractValue: { 4842 auto *EVI = cast<ExtractValueInst>(Op); 4843 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4844 break; 4845 4846 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4847 if (!WO) 4848 break; 4849 4850 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4851 bool Signed = WO->isSigned(); 4852 // TODO: Should add nuw/nsw flags for mul as well. 4853 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4854 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4855 4856 // Now that we know that all uses of the arithmetic-result component of 4857 // CI are guarded by the overflow check, we can go ahead and pretend 4858 // that the arithmetic is non-overflowing. 4859 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4860 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4861 } 4862 4863 default: 4864 break; 4865 } 4866 4867 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4868 // semantics as a Sub, return a binary sub expression. 4869 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4870 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4871 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4872 4873 return None; 4874 } 4875 4876 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4877 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4878 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4879 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4880 /// follows one of the following patterns: 4881 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4882 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4883 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4884 /// we return the type of the truncation operation, and indicate whether the 4885 /// truncated type should be treated as signed/unsigned by setting 4886 /// \p Signed to true/false, respectively. 4887 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4888 bool &Signed, ScalarEvolution &SE) { 4889 // The case where Op == SymbolicPHI (that is, with no type conversions on 4890 // the way) is handled by the regular add recurrence creating logic and 4891 // would have already been triggered in createAddRecForPHI. Reaching it here 4892 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4893 // because one of the other operands of the SCEVAddExpr updating this PHI is 4894 // not invariant). 4895 // 4896 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4897 // this case predicates that allow us to prove that Op == SymbolicPHI will 4898 // be added. 4899 if (Op == SymbolicPHI) 4900 return nullptr; 4901 4902 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4903 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4904 if (SourceBits != NewBits) 4905 return nullptr; 4906 4907 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4908 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4909 if (!SExt && !ZExt) 4910 return nullptr; 4911 const SCEVTruncateExpr *Trunc = 4912 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4913 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4914 if (!Trunc) 4915 return nullptr; 4916 const SCEV *X = Trunc->getOperand(); 4917 if (X != SymbolicPHI) 4918 return nullptr; 4919 Signed = SExt != nullptr; 4920 return Trunc->getType(); 4921 } 4922 4923 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4924 if (!PN->getType()->isIntegerTy()) 4925 return nullptr; 4926 const Loop *L = LI.getLoopFor(PN->getParent()); 4927 if (!L || L->getHeader() != PN->getParent()) 4928 return nullptr; 4929 return L; 4930 } 4931 4932 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4933 // computation that updates the phi follows the following pattern: 4934 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4935 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4936 // If so, try to see if it can be rewritten as an AddRecExpr under some 4937 // Predicates. If successful, return them as a pair. Also cache the results 4938 // of the analysis. 4939 // 4940 // Example usage scenario: 4941 // Say the Rewriter is called for the following SCEV: 4942 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4943 // where: 4944 // %X = phi i64 (%Start, %BEValue) 4945 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4946 // and call this function with %SymbolicPHI = %X. 4947 // 4948 // The analysis will find that the value coming around the backedge has 4949 // the following SCEV: 4950 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4951 // Upon concluding that this matches the desired pattern, the function 4952 // will return the pair {NewAddRec, SmallPredsVec} where: 4953 // NewAddRec = {%Start,+,%Step} 4954 // SmallPredsVec = {P1, P2, P3} as follows: 4955 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4956 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4957 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4958 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4959 // under the predicates {P1,P2,P3}. 4960 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4961 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4962 // 4963 // TODO's: 4964 // 4965 // 1) Extend the Induction descriptor to also support inductions that involve 4966 // casts: When needed (namely, when we are called in the context of the 4967 // vectorizer induction analysis), a Set of cast instructions will be 4968 // populated by this method, and provided back to isInductionPHI. This is 4969 // needed to allow the vectorizer to properly record them to be ignored by 4970 // the cost model and to avoid vectorizing them (otherwise these casts, 4971 // which are redundant under the runtime overflow checks, will be 4972 // vectorized, which can be costly). 4973 // 4974 // 2) Support additional induction/PHISCEV patterns: We also want to support 4975 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4976 // after the induction update operation (the induction increment): 4977 // 4978 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4979 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4980 // 4981 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4982 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4983 // 4984 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4985 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4986 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4987 SmallVector<const SCEVPredicate *, 3> Predicates; 4988 4989 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4990 // return an AddRec expression under some predicate. 4991 4992 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4993 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4994 assert(L && "Expecting an integer loop header phi"); 4995 4996 // The loop may have multiple entrances or multiple exits; we can analyze 4997 // this phi as an addrec if it has a unique entry value and a unique 4998 // backedge value. 4999 Value *BEValueV = nullptr, *StartValueV = nullptr; 5000 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5001 Value *V = PN->getIncomingValue(i); 5002 if (L->contains(PN->getIncomingBlock(i))) { 5003 if (!BEValueV) { 5004 BEValueV = V; 5005 } else if (BEValueV != V) { 5006 BEValueV = nullptr; 5007 break; 5008 } 5009 } else if (!StartValueV) { 5010 StartValueV = V; 5011 } else if (StartValueV != V) { 5012 StartValueV = nullptr; 5013 break; 5014 } 5015 } 5016 if (!BEValueV || !StartValueV) 5017 return None; 5018 5019 const SCEV *BEValue = getSCEV(BEValueV); 5020 5021 // If the value coming around the backedge is an add with the symbolic 5022 // value we just inserted, possibly with casts that we can ignore under 5023 // an appropriate runtime guard, then we found a simple induction variable! 5024 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5025 if (!Add) 5026 return None; 5027 5028 // If there is a single occurrence of the symbolic value, possibly 5029 // casted, replace it with a recurrence. 5030 unsigned FoundIndex = Add->getNumOperands(); 5031 Type *TruncTy = nullptr; 5032 bool Signed; 5033 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5034 if ((TruncTy = 5035 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5036 if (FoundIndex == e) { 5037 FoundIndex = i; 5038 break; 5039 } 5040 5041 if (FoundIndex == Add->getNumOperands()) 5042 return None; 5043 5044 // Create an add with everything but the specified operand. 5045 SmallVector<const SCEV *, 8> Ops; 5046 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5047 if (i != FoundIndex) 5048 Ops.push_back(Add->getOperand(i)); 5049 const SCEV *Accum = getAddExpr(Ops); 5050 5051 // The runtime checks will not be valid if the step amount is 5052 // varying inside the loop. 5053 if (!isLoopInvariant(Accum, L)) 5054 return None; 5055 5056 // *** Part2: Create the predicates 5057 5058 // Analysis was successful: we have a phi-with-cast pattern for which we 5059 // can return an AddRec expression under the following predicates: 5060 // 5061 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5062 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5063 // P2: An Equal predicate that guarantees that 5064 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5065 // P3: An Equal predicate that guarantees that 5066 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5067 // 5068 // As we next prove, the above predicates guarantee that: 5069 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5070 // 5071 // 5072 // More formally, we want to prove that: 5073 // Expr(i+1) = Start + (i+1) * Accum 5074 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5075 // 5076 // Given that: 5077 // 1) Expr(0) = Start 5078 // 2) Expr(1) = Start + Accum 5079 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5080 // 3) Induction hypothesis (step i): 5081 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5082 // 5083 // Proof: 5084 // Expr(i+1) = 5085 // = Start + (i+1)*Accum 5086 // = (Start + i*Accum) + Accum 5087 // = Expr(i) + Accum 5088 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5089 // :: from step i 5090 // 5091 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5092 // 5093 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5094 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5095 // + Accum :: from P3 5096 // 5097 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5098 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5099 // 5100 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5101 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5102 // 5103 // By induction, the same applies to all iterations 1<=i<n: 5104 // 5105 5106 // Create a truncated addrec for which we will add a no overflow check (P1). 5107 const SCEV *StartVal = getSCEV(StartValueV); 5108 const SCEV *PHISCEV = 5109 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5110 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5111 5112 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5113 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5114 // will be constant. 5115 // 5116 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5117 // add P1. 5118 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5119 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5120 Signed ? SCEVWrapPredicate::IncrementNSSW 5121 : SCEVWrapPredicate::IncrementNUSW; 5122 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5123 Predicates.push_back(AddRecPred); 5124 } 5125 5126 // Create the Equal Predicates P2,P3: 5127 5128 // It is possible that the predicates P2 and/or P3 are computable at 5129 // compile time due to StartVal and/or Accum being constants. 5130 // If either one is, then we can check that now and escape if either P2 5131 // or P3 is false. 5132 5133 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5134 // for each of StartVal and Accum 5135 auto getExtendedExpr = [&](const SCEV *Expr, 5136 bool CreateSignExtend) -> const SCEV * { 5137 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5138 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5139 const SCEV *ExtendedExpr = 5140 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5141 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5142 return ExtendedExpr; 5143 }; 5144 5145 // Given: 5146 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5147 // = getExtendedExpr(Expr) 5148 // Determine whether the predicate P: Expr == ExtendedExpr 5149 // is known to be false at compile time 5150 auto PredIsKnownFalse = [&](const SCEV *Expr, 5151 const SCEV *ExtendedExpr) -> bool { 5152 return Expr != ExtendedExpr && 5153 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5154 }; 5155 5156 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5157 if (PredIsKnownFalse(StartVal, StartExtended)) { 5158 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5159 return None; 5160 } 5161 5162 // The Step is always Signed (because the overflow checks are either 5163 // NSSW or NUSW) 5164 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5165 if (PredIsKnownFalse(Accum, AccumExtended)) { 5166 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5167 return None; 5168 } 5169 5170 auto AppendPredicate = [&](const SCEV *Expr, 5171 const SCEV *ExtendedExpr) -> void { 5172 if (Expr != ExtendedExpr && 5173 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5174 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5175 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5176 Predicates.push_back(Pred); 5177 } 5178 }; 5179 5180 AppendPredicate(StartVal, StartExtended); 5181 AppendPredicate(Accum, AccumExtended); 5182 5183 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5184 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5185 // into NewAR if it will also add the runtime overflow checks specified in 5186 // Predicates. 5187 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5188 5189 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5190 std::make_pair(NewAR, Predicates); 5191 // Remember the result of the analysis for this SCEV at this locayyytion. 5192 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5193 return PredRewrite; 5194 } 5195 5196 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5197 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5198 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5199 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5200 if (!L) 5201 return None; 5202 5203 // Check to see if we already analyzed this PHI. 5204 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5205 if (I != PredicatedSCEVRewrites.end()) { 5206 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5207 I->second; 5208 // Analysis was done before and failed to create an AddRec: 5209 if (Rewrite.first == SymbolicPHI) 5210 return None; 5211 // Analysis was done before and succeeded to create an AddRec under 5212 // a predicate: 5213 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5214 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5215 return Rewrite; 5216 } 5217 5218 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5219 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5220 5221 // Record in the cache that the analysis failed 5222 if (!Rewrite) { 5223 SmallVector<const SCEVPredicate *, 3> Predicates; 5224 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5225 return None; 5226 } 5227 5228 return Rewrite; 5229 } 5230 5231 // FIXME: This utility is currently required because the Rewriter currently 5232 // does not rewrite this expression: 5233 // {0, +, (sext ix (trunc iy to ix) to iy)} 5234 // into {0, +, %step}, 5235 // even when the following Equal predicate exists: 5236 // "%step == (sext ix (trunc iy to ix) to iy)". 5237 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5238 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5239 if (AR1 == AR2) 5240 return true; 5241 5242 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5243 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5244 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5245 return false; 5246 return true; 5247 }; 5248 5249 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5250 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5251 return false; 5252 return true; 5253 } 5254 5255 /// A helper function for createAddRecFromPHI to handle simple cases. 5256 /// 5257 /// This function tries to find an AddRec expression for the simplest (yet most 5258 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5259 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5260 /// technique for finding the AddRec expression. 5261 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5262 Value *BEValueV, 5263 Value *StartValueV) { 5264 const Loop *L = LI.getLoopFor(PN->getParent()); 5265 assert(L && L->getHeader() == PN->getParent()); 5266 assert(BEValueV && StartValueV); 5267 5268 auto BO = MatchBinaryOp(BEValueV, DT); 5269 if (!BO) 5270 return nullptr; 5271 5272 if (BO->Opcode != Instruction::Add) 5273 return nullptr; 5274 5275 const SCEV *Accum = nullptr; 5276 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5277 Accum = getSCEV(BO->RHS); 5278 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5279 Accum = getSCEV(BO->LHS); 5280 5281 if (!Accum) 5282 return nullptr; 5283 5284 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5285 if (BO->IsNUW) 5286 Flags = setFlags(Flags, SCEV::FlagNUW); 5287 if (BO->IsNSW) 5288 Flags = setFlags(Flags, SCEV::FlagNSW); 5289 5290 const SCEV *StartVal = getSCEV(StartValueV); 5291 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5292 5293 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5294 5295 // We can add Flags to the post-inc expression only if we 5296 // know that it is *undefined behavior* for BEValueV to 5297 // overflow. 5298 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5299 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5300 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5301 5302 return PHISCEV; 5303 } 5304 5305 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5306 const Loop *L = LI.getLoopFor(PN->getParent()); 5307 if (!L || L->getHeader() != PN->getParent()) 5308 return nullptr; 5309 5310 // The loop may have multiple entrances or multiple exits; we can analyze 5311 // this phi as an addrec if it has a unique entry value and a unique 5312 // backedge value. 5313 Value *BEValueV = nullptr, *StartValueV = nullptr; 5314 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5315 Value *V = PN->getIncomingValue(i); 5316 if (L->contains(PN->getIncomingBlock(i))) { 5317 if (!BEValueV) { 5318 BEValueV = V; 5319 } else if (BEValueV != V) { 5320 BEValueV = nullptr; 5321 break; 5322 } 5323 } else if (!StartValueV) { 5324 StartValueV = V; 5325 } else if (StartValueV != V) { 5326 StartValueV = nullptr; 5327 break; 5328 } 5329 } 5330 if (!BEValueV || !StartValueV) 5331 return nullptr; 5332 5333 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5334 "PHI node already processed?"); 5335 5336 // First, try to find AddRec expression without creating a fictituos symbolic 5337 // value for PN. 5338 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5339 return S; 5340 5341 // Handle PHI node value symbolically. 5342 const SCEV *SymbolicName = getUnknown(PN); 5343 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5344 5345 // Using this symbolic name for the PHI, analyze the value coming around 5346 // the back-edge. 5347 const SCEV *BEValue = getSCEV(BEValueV); 5348 5349 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5350 // has a special value for the first iteration of the loop. 5351 5352 // If the value coming around the backedge is an add with the symbolic 5353 // value we just inserted, then we found a simple induction variable! 5354 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5355 // If there is a single occurrence of the symbolic value, replace it 5356 // with a recurrence. 5357 unsigned FoundIndex = Add->getNumOperands(); 5358 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5359 if (Add->getOperand(i) == SymbolicName) 5360 if (FoundIndex == e) { 5361 FoundIndex = i; 5362 break; 5363 } 5364 5365 if (FoundIndex != Add->getNumOperands()) { 5366 // Create an add with everything but the specified operand. 5367 SmallVector<const SCEV *, 8> Ops; 5368 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5369 if (i != FoundIndex) 5370 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5371 L, *this)); 5372 const SCEV *Accum = getAddExpr(Ops); 5373 5374 // This is not a valid addrec if the step amount is varying each 5375 // loop iteration, but is not itself an addrec in this loop. 5376 if (isLoopInvariant(Accum, L) || 5377 (isa<SCEVAddRecExpr>(Accum) && 5378 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5379 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5380 5381 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5382 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5383 if (BO->IsNUW) 5384 Flags = setFlags(Flags, SCEV::FlagNUW); 5385 if (BO->IsNSW) 5386 Flags = setFlags(Flags, SCEV::FlagNSW); 5387 } 5388 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5389 // If the increment is an inbounds GEP, then we know the address 5390 // space cannot be wrapped around. We cannot make any guarantee 5391 // about signed or unsigned overflow because pointers are 5392 // unsigned but we may have a negative index from the base 5393 // pointer. We can guarantee that no unsigned wrap occurs if the 5394 // indices form a positive value. 5395 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5396 Flags = setFlags(Flags, SCEV::FlagNW); 5397 5398 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5399 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5400 Flags = setFlags(Flags, SCEV::FlagNUW); 5401 } 5402 5403 // We cannot transfer nuw and nsw flags from subtraction 5404 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5405 // for instance. 5406 } 5407 5408 const SCEV *StartVal = getSCEV(StartValueV); 5409 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5410 5411 // Okay, for the entire analysis of this edge we assumed the PHI 5412 // to be symbolic. We now need to go back and purge all of the 5413 // entries for the scalars that use the symbolic expression. 5414 forgetSymbolicName(PN, SymbolicName); 5415 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5416 5417 // We can add Flags to the post-inc expression only if we 5418 // know that it is *undefined behavior* for BEValueV to 5419 // overflow. 5420 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5421 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5422 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5423 5424 return PHISCEV; 5425 } 5426 } 5427 } else { 5428 // Otherwise, this could be a loop like this: 5429 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5430 // In this case, j = {1,+,1} and BEValue is j. 5431 // Because the other in-value of i (0) fits the evolution of BEValue 5432 // i really is an addrec evolution. 5433 // 5434 // We can generalize this saying that i is the shifted value of BEValue 5435 // by one iteration: 5436 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5437 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5438 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5439 if (Shifted != getCouldNotCompute() && 5440 Start != getCouldNotCompute()) { 5441 const SCEV *StartVal = getSCEV(StartValueV); 5442 if (Start == StartVal) { 5443 // Okay, for the entire analysis of this edge we assumed the PHI 5444 // to be symbolic. We now need to go back and purge all of the 5445 // entries for the scalars that use the symbolic expression. 5446 forgetSymbolicName(PN, SymbolicName); 5447 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5448 return Shifted; 5449 } 5450 } 5451 } 5452 5453 // Remove the temporary PHI node SCEV that has been inserted while intending 5454 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5455 // as it will prevent later (possibly simpler) SCEV expressions to be added 5456 // to the ValueExprMap. 5457 eraseValueFromMap(PN); 5458 5459 return nullptr; 5460 } 5461 5462 // Checks if the SCEV S is available at BB. S is considered available at BB 5463 // if S can be materialized at BB without introducing a fault. 5464 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5465 BasicBlock *BB) { 5466 struct CheckAvailable { 5467 bool TraversalDone = false; 5468 bool Available = true; 5469 5470 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5471 BasicBlock *BB = nullptr; 5472 DominatorTree &DT; 5473 5474 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5475 : L(L), BB(BB), DT(DT) {} 5476 5477 bool setUnavailable() { 5478 TraversalDone = true; 5479 Available = false; 5480 return false; 5481 } 5482 5483 bool follow(const SCEV *S) { 5484 switch (S->getSCEVType()) { 5485 case scConstant: 5486 case scPtrToInt: 5487 case scTruncate: 5488 case scZeroExtend: 5489 case scSignExtend: 5490 case scAddExpr: 5491 case scMulExpr: 5492 case scUMaxExpr: 5493 case scSMaxExpr: 5494 case scUMinExpr: 5495 case scSMinExpr: 5496 // These expressions are available if their operand(s) is/are. 5497 return true; 5498 5499 case scAddRecExpr: { 5500 // We allow add recurrences that are on the loop BB is in, or some 5501 // outer loop. This guarantees availability because the value of the 5502 // add recurrence at BB is simply the "current" value of the induction 5503 // variable. We can relax this in the future; for instance an add 5504 // recurrence on a sibling dominating loop is also available at BB. 5505 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5506 if (L && (ARLoop == L || ARLoop->contains(L))) 5507 return true; 5508 5509 return setUnavailable(); 5510 } 5511 5512 case scUnknown: { 5513 // For SCEVUnknown, we check for simple dominance. 5514 const auto *SU = cast<SCEVUnknown>(S); 5515 Value *V = SU->getValue(); 5516 5517 if (isa<Argument>(V)) 5518 return false; 5519 5520 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5521 return false; 5522 5523 return setUnavailable(); 5524 } 5525 5526 case scUDivExpr: 5527 case scCouldNotCompute: 5528 // We do not try to smart about these at all. 5529 return setUnavailable(); 5530 } 5531 llvm_unreachable("Unknown SCEV kind!"); 5532 } 5533 5534 bool isDone() { return TraversalDone; } 5535 }; 5536 5537 CheckAvailable CA(L, BB, DT); 5538 SCEVTraversal<CheckAvailable> ST(CA); 5539 5540 ST.visitAll(S); 5541 return CA.Available; 5542 } 5543 5544 // Try to match a control flow sequence that branches out at BI and merges back 5545 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5546 // match. 5547 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5548 Value *&C, Value *&LHS, Value *&RHS) { 5549 C = BI->getCondition(); 5550 5551 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5552 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5553 5554 if (!LeftEdge.isSingleEdge()) 5555 return false; 5556 5557 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5558 5559 Use &LeftUse = Merge->getOperandUse(0); 5560 Use &RightUse = Merge->getOperandUse(1); 5561 5562 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5563 LHS = LeftUse; 5564 RHS = RightUse; 5565 return true; 5566 } 5567 5568 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5569 LHS = RightUse; 5570 RHS = LeftUse; 5571 return true; 5572 } 5573 5574 return false; 5575 } 5576 5577 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5578 auto IsReachable = 5579 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5580 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5581 const Loop *L = LI.getLoopFor(PN->getParent()); 5582 5583 // We don't want to break LCSSA, even in a SCEV expression tree. 5584 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5585 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5586 return nullptr; 5587 5588 // Try to match 5589 // 5590 // br %cond, label %left, label %right 5591 // left: 5592 // br label %merge 5593 // right: 5594 // br label %merge 5595 // merge: 5596 // V = phi [ %x, %left ], [ %y, %right ] 5597 // 5598 // as "select %cond, %x, %y" 5599 5600 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5601 assert(IDom && "At least the entry block should dominate PN"); 5602 5603 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5604 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5605 5606 if (BI && BI->isConditional() && 5607 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5608 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5609 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5610 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5611 } 5612 5613 return nullptr; 5614 } 5615 5616 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5617 if (const SCEV *S = createAddRecFromPHI(PN)) 5618 return S; 5619 5620 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5621 return S; 5622 5623 // If the PHI has a single incoming value, follow that value, unless the 5624 // PHI's incoming blocks are in a different loop, in which case doing so 5625 // risks breaking LCSSA form. Instcombine would normally zap these, but 5626 // it doesn't have DominatorTree information, so it may miss cases. 5627 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5628 if (LI.replacementPreservesLCSSAForm(PN, V)) 5629 return getSCEV(V); 5630 5631 // If it's not a loop phi, we can't handle it yet. 5632 return getUnknown(PN); 5633 } 5634 5635 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5636 Value *Cond, 5637 Value *TrueVal, 5638 Value *FalseVal) { 5639 // Handle "constant" branch or select. This can occur for instance when a 5640 // loop pass transforms an inner loop and moves on to process the outer loop. 5641 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5642 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5643 5644 // Try to match some simple smax or umax patterns. 5645 auto *ICI = dyn_cast<ICmpInst>(Cond); 5646 if (!ICI) 5647 return getUnknown(I); 5648 5649 Value *LHS = ICI->getOperand(0); 5650 Value *RHS = ICI->getOperand(1); 5651 5652 switch (ICI->getPredicate()) { 5653 case ICmpInst::ICMP_SLT: 5654 case ICmpInst::ICMP_SLE: 5655 case ICmpInst::ICMP_ULT: 5656 case ICmpInst::ICMP_ULE: 5657 std::swap(LHS, RHS); 5658 LLVM_FALLTHROUGH; 5659 case ICmpInst::ICMP_SGT: 5660 case ICmpInst::ICMP_SGE: 5661 case ICmpInst::ICMP_UGT: 5662 case ICmpInst::ICMP_UGE: 5663 // a > b ? a+x : b+x -> max(a, b)+x 5664 // a > b ? b+x : a+x -> min(a, b)+x 5665 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5666 bool Signed = ICI->isSigned(); 5667 const SCEV *LA = getSCEV(TrueVal); 5668 const SCEV *RA = getSCEV(FalseVal); 5669 const SCEV *LS = getSCEV(LHS); 5670 const SCEV *RS = getSCEV(RHS); 5671 if (LA->getType()->isPointerTy()) { 5672 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5673 // Need to make sure we can't produce weird expressions involving 5674 // negated pointers. 5675 if (LA == LS && RA == RS) 5676 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5677 if (LA == RS && RA == LS) 5678 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5679 } 5680 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5681 if (Op->getType()->isPointerTy()) { 5682 Op = getLosslessPtrToIntExpr(Op); 5683 if (isa<SCEVCouldNotCompute>(Op)) 5684 return Op; 5685 } 5686 if (Signed) 5687 Op = getNoopOrSignExtend(Op, I->getType()); 5688 else 5689 Op = getNoopOrZeroExtend(Op, I->getType()); 5690 return Op; 5691 }; 5692 LS = CoerceOperand(LS); 5693 RS = CoerceOperand(RS); 5694 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5695 break; 5696 const SCEV *LDiff = getMinusSCEV(LA, LS); 5697 const SCEV *RDiff = getMinusSCEV(RA, RS); 5698 if (LDiff == RDiff) 5699 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5700 LDiff); 5701 LDiff = getMinusSCEV(LA, RS); 5702 RDiff = getMinusSCEV(RA, LS); 5703 if (LDiff == RDiff) 5704 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5705 LDiff); 5706 } 5707 break; 5708 case ICmpInst::ICMP_NE: 5709 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5710 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5711 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5712 const SCEV *One = getOne(I->getType()); 5713 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5714 const SCEV *LA = getSCEV(TrueVal); 5715 const SCEV *RA = getSCEV(FalseVal); 5716 const SCEV *LDiff = getMinusSCEV(LA, LS); 5717 const SCEV *RDiff = getMinusSCEV(RA, One); 5718 if (LDiff == RDiff) 5719 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5720 } 5721 break; 5722 case ICmpInst::ICMP_EQ: 5723 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5724 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5725 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5726 const SCEV *One = getOne(I->getType()); 5727 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5728 const SCEV *LA = getSCEV(TrueVal); 5729 const SCEV *RA = getSCEV(FalseVal); 5730 const SCEV *LDiff = getMinusSCEV(LA, One); 5731 const SCEV *RDiff = getMinusSCEV(RA, LS); 5732 if (LDiff == RDiff) 5733 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5734 } 5735 break; 5736 default: 5737 break; 5738 } 5739 5740 return getUnknown(I); 5741 } 5742 5743 /// Expand GEP instructions into add and multiply operations. This allows them 5744 /// to be analyzed by regular SCEV code. 5745 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5746 // Don't attempt to analyze GEPs over unsized objects. 5747 if (!GEP->getSourceElementType()->isSized()) 5748 return getUnknown(GEP); 5749 5750 SmallVector<const SCEV *, 4> IndexExprs; 5751 for (Value *Index : GEP->indices()) 5752 IndexExprs.push_back(getSCEV(Index)); 5753 return getGEPExpr(GEP, IndexExprs); 5754 } 5755 5756 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5757 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5758 return C->getAPInt().countTrailingZeros(); 5759 5760 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5761 return GetMinTrailingZeros(I->getOperand()); 5762 5763 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5764 return std::min(GetMinTrailingZeros(T->getOperand()), 5765 (uint32_t)getTypeSizeInBits(T->getType())); 5766 5767 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5768 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5769 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5770 ? getTypeSizeInBits(E->getType()) 5771 : OpRes; 5772 } 5773 5774 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5775 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5776 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5777 ? getTypeSizeInBits(E->getType()) 5778 : OpRes; 5779 } 5780 5781 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5782 // The result is the min of all operands results. 5783 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5784 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5785 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5786 return MinOpRes; 5787 } 5788 5789 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5790 // The result is the sum of all operands results. 5791 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5792 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5793 for (unsigned i = 1, e = M->getNumOperands(); 5794 SumOpRes != BitWidth && i != e; ++i) 5795 SumOpRes = 5796 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5797 return SumOpRes; 5798 } 5799 5800 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5801 // The result is the min of all operands results. 5802 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5803 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5804 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5805 return MinOpRes; 5806 } 5807 5808 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5809 // The result is the min of all operands results. 5810 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5811 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5812 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5813 return MinOpRes; 5814 } 5815 5816 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5817 // The result is the min of all operands results. 5818 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5819 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5820 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5821 return MinOpRes; 5822 } 5823 5824 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5825 // For a SCEVUnknown, ask ValueTracking. 5826 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5827 return Known.countMinTrailingZeros(); 5828 } 5829 5830 // SCEVUDivExpr 5831 return 0; 5832 } 5833 5834 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5835 auto I = MinTrailingZerosCache.find(S); 5836 if (I != MinTrailingZerosCache.end()) 5837 return I->second; 5838 5839 uint32_t Result = GetMinTrailingZerosImpl(S); 5840 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5841 assert(InsertPair.second && "Should insert a new key"); 5842 return InsertPair.first->second; 5843 } 5844 5845 /// Helper method to assign a range to V from metadata present in the IR. 5846 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5847 if (Instruction *I = dyn_cast<Instruction>(V)) 5848 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5849 return getConstantRangeFromMetadata(*MD); 5850 5851 return None; 5852 } 5853 5854 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5855 SCEV::NoWrapFlags Flags) { 5856 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5857 AddRec->setNoWrapFlags(Flags); 5858 UnsignedRanges.erase(AddRec); 5859 SignedRanges.erase(AddRec); 5860 } 5861 } 5862 5863 ConstantRange ScalarEvolution:: 5864 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5865 const DataLayout &DL = getDataLayout(); 5866 5867 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5868 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5869 5870 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5871 // use information about the trip count to improve our available range. Note 5872 // that the trip count independent cases are already handled by known bits. 5873 // WARNING: The definition of recurrence used here is subtly different than 5874 // the one used by AddRec (and thus most of this file). Step is allowed to 5875 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5876 // and other addrecs in the same loop (for non-affine addrecs). The code 5877 // below intentionally handles the case where step is not loop invariant. 5878 auto *P = dyn_cast<PHINode>(U->getValue()); 5879 if (!P) 5880 return FullSet; 5881 5882 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5883 // even the values that are not available in these blocks may come from them, 5884 // and this leads to false-positive recurrence test. 5885 for (auto *Pred : predecessors(P->getParent())) 5886 if (!DT.isReachableFromEntry(Pred)) 5887 return FullSet; 5888 5889 BinaryOperator *BO; 5890 Value *Start, *Step; 5891 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5892 return FullSet; 5893 5894 // If we found a recurrence in reachable code, we must be in a loop. Note 5895 // that BO might be in some subloop of L, and that's completely okay. 5896 auto *L = LI.getLoopFor(P->getParent()); 5897 assert(L && L->getHeader() == P->getParent()); 5898 if (!L->contains(BO->getParent())) 5899 // NOTE: This bailout should be an assert instead. However, asserting 5900 // the condition here exposes a case where LoopFusion is querying SCEV 5901 // with malformed loop information during the midst of the transform. 5902 // There doesn't appear to be an obvious fix, so for the moment bailout 5903 // until the caller issue can be fixed. PR49566 tracks the bug. 5904 return FullSet; 5905 5906 // TODO: Extend to other opcodes such as mul, and div 5907 switch (BO->getOpcode()) { 5908 default: 5909 return FullSet; 5910 case Instruction::AShr: 5911 case Instruction::LShr: 5912 case Instruction::Shl: 5913 break; 5914 }; 5915 5916 if (BO->getOperand(0) != P) 5917 // TODO: Handle the power function forms some day. 5918 return FullSet; 5919 5920 unsigned TC = getSmallConstantMaxTripCount(L); 5921 if (!TC || TC >= BitWidth) 5922 return FullSet; 5923 5924 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5925 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5926 assert(KnownStart.getBitWidth() == BitWidth && 5927 KnownStep.getBitWidth() == BitWidth); 5928 5929 // Compute total shift amount, being careful of overflow and bitwidths. 5930 auto MaxShiftAmt = KnownStep.getMaxValue(); 5931 APInt TCAP(BitWidth, TC-1); 5932 bool Overflow = false; 5933 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5934 if (Overflow) 5935 return FullSet; 5936 5937 switch (BO->getOpcode()) { 5938 default: 5939 llvm_unreachable("filtered out above"); 5940 case Instruction::AShr: { 5941 // For each ashr, three cases: 5942 // shift = 0 => unchanged value 5943 // saturation => 0 or -1 5944 // other => a value closer to zero (of the same sign) 5945 // Thus, the end value is closer to zero than the start. 5946 auto KnownEnd = KnownBits::ashr(KnownStart, 5947 KnownBits::makeConstant(TotalShift)); 5948 if (KnownStart.isNonNegative()) 5949 // Analogous to lshr (simply not yet canonicalized) 5950 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5951 KnownStart.getMaxValue() + 1); 5952 if (KnownStart.isNegative()) 5953 // End >=u Start && End <=s Start 5954 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5955 KnownEnd.getMaxValue() + 1); 5956 break; 5957 } 5958 case Instruction::LShr: { 5959 // For each lshr, three cases: 5960 // shift = 0 => unchanged value 5961 // saturation => 0 5962 // other => a smaller positive number 5963 // Thus, the low end of the unsigned range is the last value produced. 5964 auto KnownEnd = KnownBits::lshr(KnownStart, 5965 KnownBits::makeConstant(TotalShift)); 5966 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5967 KnownStart.getMaxValue() + 1); 5968 } 5969 case Instruction::Shl: { 5970 // Iff no bits are shifted out, value increases on every shift. 5971 auto KnownEnd = KnownBits::shl(KnownStart, 5972 KnownBits::makeConstant(TotalShift)); 5973 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5974 return ConstantRange(KnownStart.getMinValue(), 5975 KnownEnd.getMaxValue() + 1); 5976 break; 5977 } 5978 }; 5979 return FullSet; 5980 } 5981 5982 /// Determine the range for a particular SCEV. If SignHint is 5983 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5984 /// with a "cleaner" unsigned (resp. signed) representation. 5985 const ConstantRange & 5986 ScalarEvolution::getRangeRef(const SCEV *S, 5987 ScalarEvolution::RangeSignHint SignHint) { 5988 DenseMap<const SCEV *, ConstantRange> &Cache = 5989 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5990 : SignedRanges; 5991 ConstantRange::PreferredRangeType RangeType = 5992 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5993 ? ConstantRange::Unsigned : ConstantRange::Signed; 5994 5995 // See if we've computed this range already. 5996 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5997 if (I != Cache.end()) 5998 return I->second; 5999 6000 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6001 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6002 6003 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6004 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6005 using OBO = OverflowingBinaryOperator; 6006 6007 // If the value has known zeros, the maximum value will have those known zeros 6008 // as well. 6009 uint32_t TZ = GetMinTrailingZeros(S); 6010 if (TZ != 0) { 6011 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6012 ConservativeResult = 6013 ConstantRange(APInt::getMinValue(BitWidth), 6014 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6015 else 6016 ConservativeResult = ConstantRange( 6017 APInt::getSignedMinValue(BitWidth), 6018 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6019 } 6020 6021 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6022 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6023 unsigned WrapType = OBO::AnyWrap; 6024 if (Add->hasNoSignedWrap()) 6025 WrapType |= OBO::NoSignedWrap; 6026 if (Add->hasNoUnsignedWrap()) 6027 WrapType |= OBO::NoUnsignedWrap; 6028 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6029 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6030 WrapType, RangeType); 6031 return setRange(Add, SignHint, 6032 ConservativeResult.intersectWith(X, RangeType)); 6033 } 6034 6035 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6036 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6037 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6038 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6039 return setRange(Mul, SignHint, 6040 ConservativeResult.intersectWith(X, RangeType)); 6041 } 6042 6043 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6044 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6045 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6046 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6047 return setRange(SMax, SignHint, 6048 ConservativeResult.intersectWith(X, RangeType)); 6049 } 6050 6051 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6052 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6053 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6054 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6055 return setRange(UMax, SignHint, 6056 ConservativeResult.intersectWith(X, RangeType)); 6057 } 6058 6059 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6060 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6061 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6062 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6063 return setRange(SMin, SignHint, 6064 ConservativeResult.intersectWith(X, RangeType)); 6065 } 6066 6067 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6068 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6069 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6070 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6071 return setRange(UMin, SignHint, 6072 ConservativeResult.intersectWith(X, RangeType)); 6073 } 6074 6075 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6076 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6077 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6078 return setRange(UDiv, SignHint, 6079 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6080 } 6081 6082 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6083 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6084 return setRange(ZExt, SignHint, 6085 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6086 RangeType)); 6087 } 6088 6089 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6090 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6091 return setRange(SExt, SignHint, 6092 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6093 RangeType)); 6094 } 6095 6096 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6097 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6098 return setRange(PtrToInt, SignHint, X); 6099 } 6100 6101 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6102 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6103 return setRange(Trunc, SignHint, 6104 ConservativeResult.intersectWith(X.truncate(BitWidth), 6105 RangeType)); 6106 } 6107 6108 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6109 // If there's no unsigned wrap, the value will never be less than its 6110 // initial value. 6111 if (AddRec->hasNoUnsignedWrap()) { 6112 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6113 if (!UnsignedMinValue.isNullValue()) 6114 ConservativeResult = ConservativeResult.intersectWith( 6115 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6116 } 6117 6118 // If there's no signed wrap, and all the operands except initial value have 6119 // the same sign or zero, the value won't ever be: 6120 // 1: smaller than initial value if operands are non negative, 6121 // 2: bigger than initial value if operands are non positive. 6122 // For both cases, value can not cross signed min/max boundary. 6123 if (AddRec->hasNoSignedWrap()) { 6124 bool AllNonNeg = true; 6125 bool AllNonPos = true; 6126 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6127 if (!isKnownNonNegative(AddRec->getOperand(i))) 6128 AllNonNeg = false; 6129 if (!isKnownNonPositive(AddRec->getOperand(i))) 6130 AllNonPos = false; 6131 } 6132 if (AllNonNeg) 6133 ConservativeResult = ConservativeResult.intersectWith( 6134 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6135 APInt::getSignedMinValue(BitWidth)), 6136 RangeType); 6137 else if (AllNonPos) 6138 ConservativeResult = ConservativeResult.intersectWith( 6139 ConstantRange::getNonEmpty( 6140 APInt::getSignedMinValue(BitWidth), 6141 getSignedRangeMax(AddRec->getStart()) + 1), 6142 RangeType); 6143 } 6144 6145 // TODO: non-affine addrec 6146 if (AddRec->isAffine()) { 6147 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6148 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6149 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6150 auto RangeFromAffine = getRangeForAffineAR( 6151 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6152 BitWidth); 6153 ConservativeResult = 6154 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6155 6156 auto RangeFromFactoring = getRangeViaFactoring( 6157 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6158 BitWidth); 6159 ConservativeResult = 6160 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6161 } 6162 6163 // Now try symbolic BE count and more powerful methods. 6164 if (UseExpensiveRangeSharpening) { 6165 const SCEV *SymbolicMaxBECount = 6166 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6167 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6168 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6169 AddRec->hasNoSelfWrap()) { 6170 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6171 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6172 ConservativeResult = 6173 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6174 } 6175 } 6176 } 6177 6178 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6179 } 6180 6181 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6182 6183 // Check if the IR explicitly contains !range metadata. 6184 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6185 if (MDRange.hasValue()) 6186 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6187 RangeType); 6188 6189 // Use facts about recurrences in the underlying IR. Note that add 6190 // recurrences are AddRecExprs and thus don't hit this path. This 6191 // primarily handles shift recurrences. 6192 auto CR = getRangeForUnknownRecurrence(U); 6193 ConservativeResult = ConservativeResult.intersectWith(CR); 6194 6195 // See if ValueTracking can give us a useful range. 6196 const DataLayout &DL = getDataLayout(); 6197 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6198 if (Known.getBitWidth() != BitWidth) 6199 Known = Known.zextOrTrunc(BitWidth); 6200 6201 // ValueTracking may be able to compute a tighter result for the number of 6202 // sign bits than for the value of those sign bits. 6203 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6204 if (U->getType()->isPointerTy()) { 6205 // If the pointer size is larger than the index size type, this can cause 6206 // NS to be larger than BitWidth. So compensate for this. 6207 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6208 int ptrIdxDiff = ptrSize - BitWidth; 6209 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6210 NS -= ptrIdxDiff; 6211 } 6212 6213 if (NS > 1) { 6214 // If we know any of the sign bits, we know all of the sign bits. 6215 if (!Known.Zero.getHiBits(NS).isNullValue()) 6216 Known.Zero.setHighBits(NS); 6217 if (!Known.One.getHiBits(NS).isNullValue()) 6218 Known.One.setHighBits(NS); 6219 } 6220 6221 if (Known.getMinValue() != Known.getMaxValue() + 1) 6222 ConservativeResult = ConservativeResult.intersectWith( 6223 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6224 RangeType); 6225 if (NS > 1) 6226 ConservativeResult = ConservativeResult.intersectWith( 6227 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6228 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6229 RangeType); 6230 6231 // A range of Phi is a subset of union of all ranges of its input. 6232 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6233 // Make sure that we do not run over cycled Phis. 6234 if (PendingPhiRanges.insert(Phi).second) { 6235 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6236 for (auto &Op : Phi->operands()) { 6237 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6238 RangeFromOps = RangeFromOps.unionWith(OpRange); 6239 // No point to continue if we already have a full set. 6240 if (RangeFromOps.isFullSet()) 6241 break; 6242 } 6243 ConservativeResult = 6244 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6245 bool Erased = PendingPhiRanges.erase(Phi); 6246 assert(Erased && "Failed to erase Phi properly?"); 6247 (void) Erased; 6248 } 6249 } 6250 6251 return setRange(U, SignHint, std::move(ConservativeResult)); 6252 } 6253 6254 return setRange(S, SignHint, std::move(ConservativeResult)); 6255 } 6256 6257 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6258 // values that the expression can take. Initially, the expression has a value 6259 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6260 // argument defines if we treat Step as signed or unsigned. 6261 static ConstantRange getRangeForAffineARHelper(APInt Step, 6262 const ConstantRange &StartRange, 6263 const APInt &MaxBECount, 6264 unsigned BitWidth, bool Signed) { 6265 // If either Step or MaxBECount is 0, then the expression won't change, and we 6266 // just need to return the initial range. 6267 if (Step == 0 || MaxBECount == 0) 6268 return StartRange; 6269 6270 // If we don't know anything about the initial value (i.e. StartRange is 6271 // FullRange), then we don't know anything about the final range either. 6272 // Return FullRange. 6273 if (StartRange.isFullSet()) 6274 return ConstantRange::getFull(BitWidth); 6275 6276 // If Step is signed and negative, then we use its absolute value, but we also 6277 // note that we're moving in the opposite direction. 6278 bool Descending = Signed && Step.isNegative(); 6279 6280 if (Signed) 6281 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6282 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6283 // This equations hold true due to the well-defined wrap-around behavior of 6284 // APInt. 6285 Step = Step.abs(); 6286 6287 // Check if Offset is more than full span of BitWidth. If it is, the 6288 // expression is guaranteed to overflow. 6289 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6290 return ConstantRange::getFull(BitWidth); 6291 6292 // Offset is by how much the expression can change. Checks above guarantee no 6293 // overflow here. 6294 APInt Offset = Step * MaxBECount; 6295 6296 // Minimum value of the final range will match the minimal value of StartRange 6297 // if the expression is increasing and will be decreased by Offset otherwise. 6298 // Maximum value of the final range will match the maximal value of StartRange 6299 // if the expression is decreasing and will be increased by Offset otherwise. 6300 APInt StartLower = StartRange.getLower(); 6301 APInt StartUpper = StartRange.getUpper() - 1; 6302 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6303 : (StartUpper + std::move(Offset)); 6304 6305 // It's possible that the new minimum/maximum value will fall into the initial 6306 // range (due to wrap around). This means that the expression can take any 6307 // value in this bitwidth, and we have to return full range. 6308 if (StartRange.contains(MovedBoundary)) 6309 return ConstantRange::getFull(BitWidth); 6310 6311 APInt NewLower = 6312 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6313 APInt NewUpper = 6314 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6315 NewUpper += 1; 6316 6317 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6318 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6319 } 6320 6321 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6322 const SCEV *Step, 6323 const SCEV *MaxBECount, 6324 unsigned BitWidth) { 6325 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6326 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6327 "Precondition!"); 6328 6329 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6330 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6331 6332 // First, consider step signed. 6333 ConstantRange StartSRange = getSignedRange(Start); 6334 ConstantRange StepSRange = getSignedRange(Step); 6335 6336 // If Step can be both positive and negative, we need to find ranges for the 6337 // maximum absolute step values in both directions and union them. 6338 ConstantRange SR = 6339 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6340 MaxBECountValue, BitWidth, /* Signed = */ true); 6341 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6342 StartSRange, MaxBECountValue, 6343 BitWidth, /* Signed = */ true)); 6344 6345 // Next, consider step unsigned. 6346 ConstantRange UR = getRangeForAffineARHelper( 6347 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6348 MaxBECountValue, BitWidth, /* Signed = */ false); 6349 6350 // Finally, intersect signed and unsigned ranges. 6351 return SR.intersectWith(UR, ConstantRange::Smallest); 6352 } 6353 6354 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6355 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6356 ScalarEvolution::RangeSignHint SignHint) { 6357 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6358 assert(AddRec->hasNoSelfWrap() && 6359 "This only works for non-self-wrapping AddRecs!"); 6360 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6361 const SCEV *Step = AddRec->getStepRecurrence(*this); 6362 // Only deal with constant step to save compile time. 6363 if (!isa<SCEVConstant>(Step)) 6364 return ConstantRange::getFull(BitWidth); 6365 // Let's make sure that we can prove that we do not self-wrap during 6366 // MaxBECount iterations. We need this because MaxBECount is a maximum 6367 // iteration count estimate, and we might infer nw from some exit for which we 6368 // do not know max exit count (or any other side reasoning). 6369 // TODO: Turn into assert at some point. 6370 if (getTypeSizeInBits(MaxBECount->getType()) > 6371 getTypeSizeInBits(AddRec->getType())) 6372 return ConstantRange::getFull(BitWidth); 6373 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6374 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6375 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6376 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6377 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6378 MaxItersWithoutWrap)) 6379 return ConstantRange::getFull(BitWidth); 6380 6381 ICmpInst::Predicate LEPred = 6382 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6383 ICmpInst::Predicate GEPred = 6384 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6385 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6386 6387 // We know that there is no self-wrap. Let's take Start and End values and 6388 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6389 // the iteration. They either lie inside the range [Min(Start, End), 6390 // Max(Start, End)] or outside it: 6391 // 6392 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6393 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6394 // 6395 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6396 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6397 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6398 // Start <= End and step is positive, or Start >= End and step is negative. 6399 const SCEV *Start = AddRec->getStart(); 6400 ConstantRange StartRange = getRangeRef(Start, SignHint); 6401 ConstantRange EndRange = getRangeRef(End, SignHint); 6402 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6403 // If they already cover full iteration space, we will know nothing useful 6404 // even if we prove what we want to prove. 6405 if (RangeBetween.isFullSet()) 6406 return RangeBetween; 6407 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6408 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6409 : RangeBetween.isWrappedSet(); 6410 if (IsWrappedSet) 6411 return ConstantRange::getFull(BitWidth); 6412 6413 if (isKnownPositive(Step) && 6414 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6415 return RangeBetween; 6416 else if (isKnownNegative(Step) && 6417 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6418 return RangeBetween; 6419 return ConstantRange::getFull(BitWidth); 6420 } 6421 6422 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6423 const SCEV *Step, 6424 const SCEV *MaxBECount, 6425 unsigned BitWidth) { 6426 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6427 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6428 6429 struct SelectPattern { 6430 Value *Condition = nullptr; 6431 APInt TrueValue; 6432 APInt FalseValue; 6433 6434 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6435 const SCEV *S) { 6436 Optional<unsigned> CastOp; 6437 APInt Offset(BitWidth, 0); 6438 6439 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6440 "Should be!"); 6441 6442 // Peel off a constant offset: 6443 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6444 // In the future we could consider being smarter here and handle 6445 // {Start+Step,+,Step} too. 6446 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6447 return; 6448 6449 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6450 S = SA->getOperand(1); 6451 } 6452 6453 // Peel off a cast operation 6454 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6455 CastOp = SCast->getSCEVType(); 6456 S = SCast->getOperand(); 6457 } 6458 6459 using namespace llvm::PatternMatch; 6460 6461 auto *SU = dyn_cast<SCEVUnknown>(S); 6462 const APInt *TrueVal, *FalseVal; 6463 if (!SU || 6464 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6465 m_APInt(FalseVal)))) { 6466 Condition = nullptr; 6467 return; 6468 } 6469 6470 TrueValue = *TrueVal; 6471 FalseValue = *FalseVal; 6472 6473 // Re-apply the cast we peeled off earlier 6474 if (CastOp.hasValue()) 6475 switch (*CastOp) { 6476 default: 6477 llvm_unreachable("Unknown SCEV cast type!"); 6478 6479 case scTruncate: 6480 TrueValue = TrueValue.trunc(BitWidth); 6481 FalseValue = FalseValue.trunc(BitWidth); 6482 break; 6483 case scZeroExtend: 6484 TrueValue = TrueValue.zext(BitWidth); 6485 FalseValue = FalseValue.zext(BitWidth); 6486 break; 6487 case scSignExtend: 6488 TrueValue = TrueValue.sext(BitWidth); 6489 FalseValue = FalseValue.sext(BitWidth); 6490 break; 6491 } 6492 6493 // Re-apply the constant offset we peeled off earlier 6494 TrueValue += Offset; 6495 FalseValue += Offset; 6496 } 6497 6498 bool isRecognized() { return Condition != nullptr; } 6499 }; 6500 6501 SelectPattern StartPattern(*this, BitWidth, Start); 6502 if (!StartPattern.isRecognized()) 6503 return ConstantRange::getFull(BitWidth); 6504 6505 SelectPattern StepPattern(*this, BitWidth, Step); 6506 if (!StepPattern.isRecognized()) 6507 return ConstantRange::getFull(BitWidth); 6508 6509 if (StartPattern.Condition != StepPattern.Condition) { 6510 // We don't handle this case today; but we could, by considering four 6511 // possibilities below instead of two. I'm not sure if there are cases where 6512 // that will help over what getRange already does, though. 6513 return ConstantRange::getFull(BitWidth); 6514 } 6515 6516 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6517 // construct arbitrary general SCEV expressions here. This function is called 6518 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6519 // say) can end up caching a suboptimal value. 6520 6521 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6522 // C2352 and C2512 (otherwise it isn't needed). 6523 6524 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6525 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6526 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6527 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6528 6529 ConstantRange TrueRange = 6530 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6531 ConstantRange FalseRange = 6532 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6533 6534 return TrueRange.unionWith(FalseRange); 6535 } 6536 6537 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6538 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6539 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6540 6541 // Return early if there are no flags to propagate to the SCEV. 6542 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6543 if (BinOp->hasNoUnsignedWrap()) 6544 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6545 if (BinOp->hasNoSignedWrap()) 6546 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6547 if (Flags == SCEV::FlagAnyWrap) 6548 return SCEV::FlagAnyWrap; 6549 6550 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6551 } 6552 6553 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6554 // Here we check that I is in the header of the innermost loop containing I, 6555 // since we only deal with instructions in the loop header. The actual loop we 6556 // need to check later will come from an add recurrence, but getting that 6557 // requires computing the SCEV of the operands, which can be expensive. This 6558 // check we can do cheaply to rule out some cases early. 6559 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6560 if (InnermostContainingLoop == nullptr || 6561 InnermostContainingLoop->getHeader() != I->getParent()) 6562 return false; 6563 6564 // Only proceed if we can prove that I does not yield poison. 6565 if (!programUndefinedIfPoison(I)) 6566 return false; 6567 6568 // At this point we know that if I is executed, then it does not wrap 6569 // according to at least one of NSW or NUW. If I is not executed, then we do 6570 // not know if the calculation that I represents would wrap. Multiple 6571 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6572 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6573 // derived from other instructions that map to the same SCEV. We cannot make 6574 // that guarantee for cases where I is not executed. So we need to find the 6575 // loop that I is considered in relation to and prove that I is executed for 6576 // every iteration of that loop. That implies that the value that I 6577 // calculates does not wrap anywhere in the loop, so then we can apply the 6578 // flags to the SCEV. 6579 // 6580 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6581 // from different loops, so that we know which loop to prove that I is 6582 // executed in. 6583 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6584 // I could be an extractvalue from a call to an overflow intrinsic. 6585 // TODO: We can do better here in some cases. 6586 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6587 return false; 6588 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6589 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6590 bool AllOtherOpsLoopInvariant = true; 6591 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6592 ++OtherOpIndex) { 6593 if (OtherOpIndex != OpIndex) { 6594 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6595 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6596 AllOtherOpsLoopInvariant = false; 6597 break; 6598 } 6599 } 6600 } 6601 if (AllOtherOpsLoopInvariant && 6602 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6603 return true; 6604 } 6605 } 6606 return false; 6607 } 6608 6609 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6610 // If we know that \c I can never be poison period, then that's enough. 6611 if (isSCEVExprNeverPoison(I)) 6612 return true; 6613 6614 // For an add recurrence specifically, we assume that infinite loops without 6615 // side effects are undefined behavior, and then reason as follows: 6616 // 6617 // If the add recurrence is poison in any iteration, it is poison on all 6618 // future iterations (since incrementing poison yields poison). If the result 6619 // of the add recurrence is fed into the loop latch condition and the loop 6620 // does not contain any throws or exiting blocks other than the latch, we now 6621 // have the ability to "choose" whether the backedge is taken or not (by 6622 // choosing a sufficiently evil value for the poison feeding into the branch) 6623 // for every iteration including and after the one in which \p I first became 6624 // poison. There are two possibilities (let's call the iteration in which \p 6625 // I first became poison as K): 6626 // 6627 // 1. In the set of iterations including and after K, the loop body executes 6628 // no side effects. In this case executing the backege an infinte number 6629 // of times will yield undefined behavior. 6630 // 6631 // 2. In the set of iterations including and after K, the loop body executes 6632 // at least one side effect. In this case, that specific instance of side 6633 // effect is control dependent on poison, which also yields undefined 6634 // behavior. 6635 6636 auto *ExitingBB = L->getExitingBlock(); 6637 auto *LatchBB = L->getLoopLatch(); 6638 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6639 return false; 6640 6641 SmallPtrSet<const Instruction *, 16> Pushed; 6642 SmallVector<const Instruction *, 8> PoisonStack; 6643 6644 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6645 // things that are known to be poison under that assumption go on the 6646 // PoisonStack. 6647 Pushed.insert(I); 6648 PoisonStack.push_back(I); 6649 6650 bool LatchControlDependentOnPoison = false; 6651 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6652 const Instruction *Poison = PoisonStack.pop_back_val(); 6653 6654 for (auto *PoisonUser : Poison->users()) { 6655 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6656 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6657 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6658 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6659 assert(BI->isConditional() && "Only possibility!"); 6660 if (BI->getParent() == LatchBB) { 6661 LatchControlDependentOnPoison = true; 6662 break; 6663 } 6664 } 6665 } 6666 } 6667 6668 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6669 } 6670 6671 ScalarEvolution::LoopProperties 6672 ScalarEvolution::getLoopProperties(const Loop *L) { 6673 using LoopProperties = ScalarEvolution::LoopProperties; 6674 6675 auto Itr = LoopPropertiesCache.find(L); 6676 if (Itr == LoopPropertiesCache.end()) { 6677 auto HasSideEffects = [](Instruction *I) { 6678 if (auto *SI = dyn_cast<StoreInst>(I)) 6679 return !SI->isSimple(); 6680 6681 return I->mayThrow() || I->mayWriteToMemory(); 6682 }; 6683 6684 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6685 /*HasNoSideEffects*/ true}; 6686 6687 for (auto *BB : L->getBlocks()) 6688 for (auto &I : *BB) { 6689 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6690 LP.HasNoAbnormalExits = false; 6691 if (HasSideEffects(&I)) 6692 LP.HasNoSideEffects = false; 6693 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6694 break; // We're already as pessimistic as we can get. 6695 } 6696 6697 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6698 assert(InsertPair.second && "We just checked!"); 6699 Itr = InsertPair.first; 6700 } 6701 6702 return Itr->second; 6703 } 6704 6705 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6706 // A mustprogress loop without side effects must be finite. 6707 // TODO: The check used here is very conservative. It's only *specific* 6708 // side effects which are well defined in infinite loops. 6709 return isMustProgress(L) && loopHasNoSideEffects(L); 6710 } 6711 6712 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6713 if (!isSCEVable(V->getType())) 6714 return getUnknown(V); 6715 6716 if (Instruction *I = dyn_cast<Instruction>(V)) { 6717 // Don't attempt to analyze instructions in blocks that aren't 6718 // reachable. Such instructions don't matter, and they aren't required 6719 // to obey basic rules for definitions dominating uses which this 6720 // analysis depends on. 6721 if (!DT.isReachableFromEntry(I->getParent())) 6722 return getUnknown(UndefValue::get(V->getType())); 6723 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6724 return getConstant(CI); 6725 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6726 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6727 else if (!isa<ConstantExpr>(V)) 6728 return getUnknown(V); 6729 6730 Operator *U = cast<Operator>(V); 6731 if (auto BO = MatchBinaryOp(U, DT)) { 6732 switch (BO->Opcode) { 6733 case Instruction::Add: { 6734 // The simple thing to do would be to just call getSCEV on both operands 6735 // and call getAddExpr with the result. However if we're looking at a 6736 // bunch of things all added together, this can be quite inefficient, 6737 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6738 // Instead, gather up all the operands and make a single getAddExpr call. 6739 // LLVM IR canonical form means we need only traverse the left operands. 6740 SmallVector<const SCEV *, 4> AddOps; 6741 do { 6742 if (BO->Op) { 6743 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6744 AddOps.push_back(OpSCEV); 6745 break; 6746 } 6747 6748 // If a NUW or NSW flag can be applied to the SCEV for this 6749 // addition, then compute the SCEV for this addition by itself 6750 // with a separate call to getAddExpr. We need to do that 6751 // instead of pushing the operands of the addition onto AddOps, 6752 // since the flags are only known to apply to this particular 6753 // addition - they may not apply to other additions that can be 6754 // formed with operands from AddOps. 6755 const SCEV *RHS = getSCEV(BO->RHS); 6756 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6757 if (Flags != SCEV::FlagAnyWrap) { 6758 const SCEV *LHS = getSCEV(BO->LHS); 6759 if (BO->Opcode == Instruction::Sub) 6760 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6761 else 6762 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6763 break; 6764 } 6765 } 6766 6767 if (BO->Opcode == Instruction::Sub) 6768 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6769 else 6770 AddOps.push_back(getSCEV(BO->RHS)); 6771 6772 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6773 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6774 NewBO->Opcode != Instruction::Sub)) { 6775 AddOps.push_back(getSCEV(BO->LHS)); 6776 break; 6777 } 6778 BO = NewBO; 6779 } while (true); 6780 6781 return getAddExpr(AddOps); 6782 } 6783 6784 case Instruction::Mul: { 6785 SmallVector<const SCEV *, 4> MulOps; 6786 do { 6787 if (BO->Op) { 6788 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6789 MulOps.push_back(OpSCEV); 6790 break; 6791 } 6792 6793 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6794 if (Flags != SCEV::FlagAnyWrap) { 6795 MulOps.push_back( 6796 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6797 break; 6798 } 6799 } 6800 6801 MulOps.push_back(getSCEV(BO->RHS)); 6802 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6803 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6804 MulOps.push_back(getSCEV(BO->LHS)); 6805 break; 6806 } 6807 BO = NewBO; 6808 } while (true); 6809 6810 return getMulExpr(MulOps); 6811 } 6812 case Instruction::UDiv: 6813 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6814 case Instruction::URem: 6815 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6816 case Instruction::Sub: { 6817 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6818 if (BO->Op) 6819 Flags = getNoWrapFlagsFromUB(BO->Op); 6820 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6821 } 6822 case Instruction::And: 6823 // For an expression like x&255 that merely masks off the high bits, 6824 // use zext(trunc(x)) as the SCEV expression. 6825 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6826 if (CI->isZero()) 6827 return getSCEV(BO->RHS); 6828 if (CI->isMinusOne()) 6829 return getSCEV(BO->LHS); 6830 const APInt &A = CI->getValue(); 6831 6832 // Instcombine's ShrinkDemandedConstant may strip bits out of 6833 // constants, obscuring what would otherwise be a low-bits mask. 6834 // Use computeKnownBits to compute what ShrinkDemandedConstant 6835 // knew about to reconstruct a low-bits mask value. 6836 unsigned LZ = A.countLeadingZeros(); 6837 unsigned TZ = A.countTrailingZeros(); 6838 unsigned BitWidth = A.getBitWidth(); 6839 KnownBits Known(BitWidth); 6840 computeKnownBits(BO->LHS, Known, getDataLayout(), 6841 0, &AC, nullptr, &DT); 6842 6843 APInt EffectiveMask = 6844 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6845 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6846 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6847 const SCEV *LHS = getSCEV(BO->LHS); 6848 const SCEV *ShiftedLHS = nullptr; 6849 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6850 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6851 // For an expression like (x * 8) & 8, simplify the multiply. 6852 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6853 unsigned GCD = std::min(MulZeros, TZ); 6854 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6855 SmallVector<const SCEV*, 4> MulOps; 6856 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6857 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6858 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6859 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6860 } 6861 } 6862 if (!ShiftedLHS) 6863 ShiftedLHS = getUDivExpr(LHS, MulCount); 6864 return getMulExpr( 6865 getZeroExtendExpr( 6866 getTruncateExpr(ShiftedLHS, 6867 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6868 BO->LHS->getType()), 6869 MulCount); 6870 } 6871 } 6872 break; 6873 6874 case Instruction::Or: 6875 // If the RHS of the Or is a constant, we may have something like: 6876 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6877 // optimizations will transparently handle this case. 6878 // 6879 // In order for this transformation to be safe, the LHS must be of the 6880 // form X*(2^n) and the Or constant must be less than 2^n. 6881 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6882 const SCEV *LHS = getSCEV(BO->LHS); 6883 const APInt &CIVal = CI->getValue(); 6884 if (GetMinTrailingZeros(LHS) >= 6885 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6886 // Build a plain add SCEV. 6887 return getAddExpr(LHS, getSCEV(CI), 6888 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6889 } 6890 } 6891 break; 6892 6893 case Instruction::Xor: 6894 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6895 // If the RHS of xor is -1, then this is a not operation. 6896 if (CI->isMinusOne()) 6897 return getNotSCEV(getSCEV(BO->LHS)); 6898 6899 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6900 // This is a variant of the check for xor with -1, and it handles 6901 // the case where instcombine has trimmed non-demanded bits out 6902 // of an xor with -1. 6903 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6904 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6905 if (LBO->getOpcode() == Instruction::And && 6906 LCI->getValue() == CI->getValue()) 6907 if (const SCEVZeroExtendExpr *Z = 6908 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6909 Type *UTy = BO->LHS->getType(); 6910 const SCEV *Z0 = Z->getOperand(); 6911 Type *Z0Ty = Z0->getType(); 6912 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6913 6914 // If C is a low-bits mask, the zero extend is serving to 6915 // mask off the high bits. Complement the operand and 6916 // re-apply the zext. 6917 if (CI->getValue().isMask(Z0TySize)) 6918 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6919 6920 // If C is a single bit, it may be in the sign-bit position 6921 // before the zero-extend. In this case, represent the xor 6922 // using an add, which is equivalent, and re-apply the zext. 6923 APInt Trunc = CI->getValue().trunc(Z0TySize); 6924 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6925 Trunc.isSignMask()) 6926 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6927 UTy); 6928 } 6929 } 6930 break; 6931 6932 case Instruction::Shl: 6933 // Turn shift left of a constant amount into a multiply. 6934 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6935 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6936 6937 // If the shift count is not less than the bitwidth, the result of 6938 // the shift is undefined. Don't try to analyze it, because the 6939 // resolution chosen here may differ from the resolution chosen in 6940 // other parts of the compiler. 6941 if (SA->getValue().uge(BitWidth)) 6942 break; 6943 6944 // We can safely preserve the nuw flag in all cases. It's also safe to 6945 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6946 // requires special handling. It can be preserved as long as we're not 6947 // left shifting by bitwidth - 1. 6948 auto Flags = SCEV::FlagAnyWrap; 6949 if (BO->Op) { 6950 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6951 if ((MulFlags & SCEV::FlagNSW) && 6952 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6953 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6954 if (MulFlags & SCEV::FlagNUW) 6955 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6956 } 6957 6958 Constant *X = ConstantInt::get( 6959 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6960 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6961 } 6962 break; 6963 6964 case Instruction::AShr: { 6965 // AShr X, C, where C is a constant. 6966 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6967 if (!CI) 6968 break; 6969 6970 Type *OuterTy = BO->LHS->getType(); 6971 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6972 // If the shift count is not less than the bitwidth, the result of 6973 // the shift is undefined. Don't try to analyze it, because the 6974 // resolution chosen here may differ from the resolution chosen in 6975 // other parts of the compiler. 6976 if (CI->getValue().uge(BitWidth)) 6977 break; 6978 6979 if (CI->isZero()) 6980 return getSCEV(BO->LHS); // shift by zero --> noop 6981 6982 uint64_t AShrAmt = CI->getZExtValue(); 6983 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6984 6985 Operator *L = dyn_cast<Operator>(BO->LHS); 6986 if (L && L->getOpcode() == Instruction::Shl) { 6987 // X = Shl A, n 6988 // Y = AShr X, m 6989 // Both n and m are constant. 6990 6991 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6992 if (L->getOperand(1) == BO->RHS) 6993 // For a two-shift sext-inreg, i.e. n = m, 6994 // use sext(trunc(x)) as the SCEV expression. 6995 return getSignExtendExpr( 6996 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6997 6998 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6999 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7000 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7001 if (ShlAmt > AShrAmt) { 7002 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7003 // expression. We already checked that ShlAmt < BitWidth, so 7004 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7005 // ShlAmt - AShrAmt < Amt. 7006 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7007 ShlAmt - AShrAmt); 7008 return getSignExtendExpr( 7009 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7010 getConstant(Mul)), OuterTy); 7011 } 7012 } 7013 } 7014 break; 7015 } 7016 } 7017 } 7018 7019 switch (U->getOpcode()) { 7020 case Instruction::Trunc: 7021 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7022 7023 case Instruction::ZExt: 7024 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7025 7026 case Instruction::SExt: 7027 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7028 // The NSW flag of a subtract does not always survive the conversion to 7029 // A + (-1)*B. By pushing sign extension onto its operands we are much 7030 // more likely to preserve NSW and allow later AddRec optimisations. 7031 // 7032 // NOTE: This is effectively duplicating this logic from getSignExtend: 7033 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7034 // but by that point the NSW information has potentially been lost. 7035 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7036 Type *Ty = U->getType(); 7037 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7038 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7039 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7040 } 7041 } 7042 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7043 7044 case Instruction::BitCast: 7045 // BitCasts are no-op casts so we just eliminate the cast. 7046 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7047 return getSCEV(U->getOperand(0)); 7048 break; 7049 7050 case Instruction::PtrToInt: { 7051 // Pointer to integer cast is straight-forward, so do model it. 7052 const SCEV *Op = getSCEV(U->getOperand(0)); 7053 Type *DstIntTy = U->getType(); 7054 // But only if effective SCEV (integer) type is wide enough to represent 7055 // all possible pointer values. 7056 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7057 if (isa<SCEVCouldNotCompute>(IntOp)) 7058 return getUnknown(V); 7059 return IntOp; 7060 } 7061 case Instruction::IntToPtr: 7062 // Just don't deal with inttoptr casts. 7063 return getUnknown(V); 7064 7065 case Instruction::SDiv: 7066 // If both operands are non-negative, this is just an udiv. 7067 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7068 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7069 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7070 break; 7071 7072 case Instruction::SRem: 7073 // If both operands are non-negative, this is just an urem. 7074 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7075 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7076 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7077 break; 7078 7079 case Instruction::GetElementPtr: 7080 return createNodeForGEP(cast<GEPOperator>(U)); 7081 7082 case Instruction::PHI: 7083 return createNodeForPHI(cast<PHINode>(U)); 7084 7085 case Instruction::Select: 7086 // U can also be a select constant expr, which let fall through. Since 7087 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7088 // constant expressions cannot have instructions as operands, we'd have 7089 // returned getUnknown for a select constant expressions anyway. 7090 if (isa<Instruction>(U)) 7091 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7092 U->getOperand(1), U->getOperand(2)); 7093 break; 7094 7095 case Instruction::Call: 7096 case Instruction::Invoke: 7097 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7098 return getSCEV(RV); 7099 7100 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7101 switch (II->getIntrinsicID()) { 7102 case Intrinsic::abs: 7103 return getAbsExpr( 7104 getSCEV(II->getArgOperand(0)), 7105 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7106 case Intrinsic::umax: 7107 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7108 getSCEV(II->getArgOperand(1))); 7109 case Intrinsic::umin: 7110 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7111 getSCEV(II->getArgOperand(1))); 7112 case Intrinsic::smax: 7113 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7114 getSCEV(II->getArgOperand(1))); 7115 case Intrinsic::smin: 7116 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7117 getSCEV(II->getArgOperand(1))); 7118 case Intrinsic::usub_sat: { 7119 const SCEV *X = getSCEV(II->getArgOperand(0)); 7120 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7121 const SCEV *ClampedY = getUMinExpr(X, Y); 7122 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7123 } 7124 case Intrinsic::uadd_sat: { 7125 const SCEV *X = getSCEV(II->getArgOperand(0)); 7126 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7127 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7128 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7129 } 7130 case Intrinsic::start_loop_iterations: 7131 // A start_loop_iterations is just equivalent to the first operand for 7132 // SCEV purposes. 7133 return getSCEV(II->getArgOperand(0)); 7134 default: 7135 break; 7136 } 7137 } 7138 break; 7139 } 7140 7141 return getUnknown(V); 7142 } 7143 7144 //===----------------------------------------------------------------------===// 7145 // Iteration Count Computation Code 7146 // 7147 7148 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7149 // Get the trip count from the BE count by adding 1. Overflow, results 7150 // in zero which means "unknown". 7151 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7152 } 7153 7154 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7155 if (!ExitCount) 7156 return 0; 7157 7158 ConstantInt *ExitConst = ExitCount->getValue(); 7159 7160 // Guard against huge trip counts. 7161 if (ExitConst->getValue().getActiveBits() > 32) 7162 return 0; 7163 7164 // In case of integer overflow, this returns 0, which is correct. 7165 return ((unsigned)ExitConst->getZExtValue()) + 1; 7166 } 7167 7168 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7169 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7170 return getConstantTripCount(ExitCount); 7171 } 7172 7173 unsigned 7174 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7175 const BasicBlock *ExitingBlock) { 7176 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7177 assert(L->isLoopExiting(ExitingBlock) && 7178 "Exiting block must actually branch out of the loop!"); 7179 const SCEVConstant *ExitCount = 7180 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7181 return getConstantTripCount(ExitCount); 7182 } 7183 7184 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7185 const auto *MaxExitCount = 7186 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7187 return getConstantTripCount(MaxExitCount); 7188 } 7189 7190 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7191 SmallVector<BasicBlock *, 8> ExitingBlocks; 7192 L->getExitingBlocks(ExitingBlocks); 7193 7194 Optional<unsigned> Res = None; 7195 for (auto *ExitingBB : ExitingBlocks) { 7196 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7197 if (!Res) 7198 Res = Multiple; 7199 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7200 } 7201 return Res.getValueOr(1); 7202 } 7203 7204 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7205 const SCEV *ExitCount) { 7206 if (ExitCount == getCouldNotCompute()) 7207 return 1; 7208 7209 // Get the trip count 7210 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7211 7212 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7213 if (!TC) 7214 // Attempt to factor more general cases. Returns the greatest power of 7215 // two divisor. If overflow happens, the trip count expression is still 7216 // divisible by the greatest power of 2 divisor returned. 7217 return 1U << std::min((uint32_t)31, 7218 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7219 7220 ConstantInt *Result = TC->getValue(); 7221 7222 // Guard against huge trip counts (this requires checking 7223 // for zero to handle the case where the trip count == -1 and the 7224 // addition wraps). 7225 if (!Result || Result->getValue().getActiveBits() > 32 || 7226 Result->getValue().getActiveBits() == 0) 7227 return 1; 7228 7229 return (unsigned)Result->getZExtValue(); 7230 } 7231 7232 /// Returns the largest constant divisor of the trip count of this loop as a 7233 /// normal unsigned value, if possible. This means that the actual trip count is 7234 /// always a multiple of the returned value (don't forget the trip count could 7235 /// very well be zero as well!). 7236 /// 7237 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7238 /// multiple of a constant (which is also the case if the trip count is simply 7239 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7240 /// if the trip count is very large (>= 2^32). 7241 /// 7242 /// As explained in the comments for getSmallConstantTripCount, this assumes 7243 /// that control exits the loop via ExitingBlock. 7244 unsigned 7245 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7246 const BasicBlock *ExitingBlock) { 7247 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7248 assert(L->isLoopExiting(ExitingBlock) && 7249 "Exiting block must actually branch out of the loop!"); 7250 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7251 return getSmallConstantTripMultiple(L, ExitCount); 7252 } 7253 7254 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7255 const BasicBlock *ExitingBlock, 7256 ExitCountKind Kind) { 7257 switch (Kind) { 7258 case Exact: 7259 case SymbolicMaximum: 7260 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7261 case ConstantMaximum: 7262 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7263 }; 7264 llvm_unreachable("Invalid ExitCountKind!"); 7265 } 7266 7267 const SCEV * 7268 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7269 SCEVUnionPredicate &Preds) { 7270 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7271 } 7272 7273 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7274 ExitCountKind Kind) { 7275 switch (Kind) { 7276 case Exact: 7277 return getBackedgeTakenInfo(L).getExact(L, this); 7278 case ConstantMaximum: 7279 return getBackedgeTakenInfo(L).getConstantMax(this); 7280 case SymbolicMaximum: 7281 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7282 }; 7283 llvm_unreachable("Invalid ExitCountKind!"); 7284 } 7285 7286 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7287 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7288 } 7289 7290 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7291 static void 7292 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7293 BasicBlock *Header = L->getHeader(); 7294 7295 // Push all Loop-header PHIs onto the Worklist stack. 7296 for (PHINode &PN : Header->phis()) 7297 Worklist.push_back(&PN); 7298 } 7299 7300 const ScalarEvolution::BackedgeTakenInfo & 7301 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7302 auto &BTI = getBackedgeTakenInfo(L); 7303 if (BTI.hasFullInfo()) 7304 return BTI; 7305 7306 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7307 7308 if (!Pair.second) 7309 return Pair.first->second; 7310 7311 BackedgeTakenInfo Result = 7312 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7313 7314 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7315 } 7316 7317 ScalarEvolution::BackedgeTakenInfo & 7318 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7319 // Initially insert an invalid entry for this loop. If the insertion 7320 // succeeds, proceed to actually compute a backedge-taken count and 7321 // update the value. The temporary CouldNotCompute value tells SCEV 7322 // code elsewhere that it shouldn't attempt to request a new 7323 // backedge-taken count, which could result in infinite recursion. 7324 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7325 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7326 if (!Pair.second) 7327 return Pair.first->second; 7328 7329 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7330 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7331 // must be cleared in this scope. 7332 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7333 7334 // In product build, there are no usage of statistic. 7335 (void)NumTripCountsComputed; 7336 (void)NumTripCountsNotComputed; 7337 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7338 const SCEV *BEExact = Result.getExact(L, this); 7339 if (BEExact != getCouldNotCompute()) { 7340 assert(isLoopInvariant(BEExact, L) && 7341 isLoopInvariant(Result.getConstantMax(this), L) && 7342 "Computed backedge-taken count isn't loop invariant for loop!"); 7343 ++NumTripCountsComputed; 7344 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7345 isa<PHINode>(L->getHeader()->begin())) { 7346 // Only count loops that have phi nodes as not being computable. 7347 ++NumTripCountsNotComputed; 7348 } 7349 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7350 7351 // Now that we know more about the trip count for this loop, forget any 7352 // existing SCEV values for PHI nodes in this loop since they are only 7353 // conservative estimates made without the benefit of trip count 7354 // information. This is similar to the code in forgetLoop, except that 7355 // it handles SCEVUnknown PHI nodes specially. 7356 if (Result.hasAnyInfo()) { 7357 SmallVector<Instruction *, 16> Worklist; 7358 PushLoopPHIs(L, Worklist); 7359 7360 SmallPtrSet<Instruction *, 8> Discovered; 7361 while (!Worklist.empty()) { 7362 Instruction *I = Worklist.pop_back_val(); 7363 7364 ValueExprMapType::iterator It = 7365 ValueExprMap.find_as(static_cast<Value *>(I)); 7366 if (It != ValueExprMap.end()) { 7367 const SCEV *Old = It->second; 7368 7369 // SCEVUnknown for a PHI either means that it has an unrecognized 7370 // structure, or it's a PHI that's in the progress of being computed 7371 // by createNodeForPHI. In the former case, additional loop trip 7372 // count information isn't going to change anything. In the later 7373 // case, createNodeForPHI will perform the necessary updates on its 7374 // own when it gets to that point. 7375 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7376 eraseValueFromMap(It->first); 7377 forgetMemoizedResults(Old); 7378 } 7379 if (PHINode *PN = dyn_cast<PHINode>(I)) 7380 ConstantEvolutionLoopExitValue.erase(PN); 7381 } 7382 7383 // Since we don't need to invalidate anything for correctness and we're 7384 // only invalidating to make SCEV's results more precise, we get to stop 7385 // early to avoid invalidating too much. This is especially important in 7386 // cases like: 7387 // 7388 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7389 // loop0: 7390 // %pn0 = phi 7391 // ... 7392 // loop1: 7393 // %pn1 = phi 7394 // ... 7395 // 7396 // where both loop0 and loop1's backedge taken count uses the SCEV 7397 // expression for %v. If we don't have the early stop below then in cases 7398 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7399 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7400 // count for loop1, effectively nullifying SCEV's trip count cache. 7401 for (auto *U : I->users()) 7402 if (auto *I = dyn_cast<Instruction>(U)) { 7403 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7404 if (LoopForUser && L->contains(LoopForUser) && 7405 Discovered.insert(I).second) 7406 Worklist.push_back(I); 7407 } 7408 } 7409 } 7410 7411 // Re-lookup the insert position, since the call to 7412 // computeBackedgeTakenCount above could result in a 7413 // recusive call to getBackedgeTakenInfo (on a different 7414 // loop), which would invalidate the iterator computed 7415 // earlier. 7416 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7417 } 7418 7419 void ScalarEvolution::forgetAllLoops() { 7420 // This method is intended to forget all info about loops. It should 7421 // invalidate caches as if the following happened: 7422 // - The trip counts of all loops have changed arbitrarily 7423 // - Every llvm::Value has been updated in place to produce a different 7424 // result. 7425 BackedgeTakenCounts.clear(); 7426 PredicatedBackedgeTakenCounts.clear(); 7427 LoopPropertiesCache.clear(); 7428 ConstantEvolutionLoopExitValue.clear(); 7429 ValueExprMap.clear(); 7430 ValuesAtScopes.clear(); 7431 LoopDispositions.clear(); 7432 BlockDispositions.clear(); 7433 UnsignedRanges.clear(); 7434 SignedRanges.clear(); 7435 ExprValueMap.clear(); 7436 HasRecMap.clear(); 7437 MinTrailingZerosCache.clear(); 7438 PredicatedSCEVRewrites.clear(); 7439 } 7440 7441 void ScalarEvolution::forgetLoop(const Loop *L) { 7442 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7443 SmallVector<Instruction *, 32> Worklist; 7444 SmallPtrSet<Instruction *, 16> Visited; 7445 7446 // Iterate over all the loops and sub-loops to drop SCEV information. 7447 while (!LoopWorklist.empty()) { 7448 auto *CurrL = LoopWorklist.pop_back_val(); 7449 7450 // Drop any stored trip count value. 7451 BackedgeTakenCounts.erase(CurrL); 7452 PredicatedBackedgeTakenCounts.erase(CurrL); 7453 7454 // Drop information about predicated SCEV rewrites for this loop. 7455 for (auto I = PredicatedSCEVRewrites.begin(); 7456 I != PredicatedSCEVRewrites.end();) { 7457 std::pair<const SCEV *, const Loop *> Entry = I->first; 7458 if (Entry.second == CurrL) 7459 PredicatedSCEVRewrites.erase(I++); 7460 else 7461 ++I; 7462 } 7463 7464 auto LoopUsersItr = LoopUsers.find(CurrL); 7465 if (LoopUsersItr != LoopUsers.end()) { 7466 for (auto *S : LoopUsersItr->second) 7467 forgetMemoizedResults(S); 7468 LoopUsers.erase(LoopUsersItr); 7469 } 7470 7471 // Drop information about expressions based on loop-header PHIs. 7472 PushLoopPHIs(CurrL, Worklist); 7473 7474 while (!Worklist.empty()) { 7475 Instruction *I = Worklist.pop_back_val(); 7476 if (!Visited.insert(I).second) 7477 continue; 7478 7479 ValueExprMapType::iterator It = 7480 ValueExprMap.find_as(static_cast<Value *>(I)); 7481 if (It != ValueExprMap.end()) { 7482 eraseValueFromMap(It->first); 7483 forgetMemoizedResults(It->second); 7484 if (PHINode *PN = dyn_cast<PHINode>(I)) 7485 ConstantEvolutionLoopExitValue.erase(PN); 7486 } 7487 7488 PushDefUseChildren(I, Worklist); 7489 } 7490 7491 LoopPropertiesCache.erase(CurrL); 7492 // Forget all contained loops too, to avoid dangling entries in the 7493 // ValuesAtScopes map. 7494 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7495 } 7496 } 7497 7498 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7499 while (Loop *Parent = L->getParentLoop()) 7500 L = Parent; 7501 forgetLoop(L); 7502 } 7503 7504 void ScalarEvolution::forgetValue(Value *V) { 7505 Instruction *I = dyn_cast<Instruction>(V); 7506 if (!I) return; 7507 7508 // Drop information about expressions based on loop-header PHIs. 7509 SmallVector<Instruction *, 16> Worklist; 7510 Worklist.push_back(I); 7511 7512 SmallPtrSet<Instruction *, 8> Visited; 7513 while (!Worklist.empty()) { 7514 I = Worklist.pop_back_val(); 7515 if (!Visited.insert(I).second) 7516 continue; 7517 7518 ValueExprMapType::iterator It = 7519 ValueExprMap.find_as(static_cast<Value *>(I)); 7520 if (It != ValueExprMap.end()) { 7521 eraseValueFromMap(It->first); 7522 forgetMemoizedResults(It->second); 7523 if (PHINode *PN = dyn_cast<PHINode>(I)) 7524 ConstantEvolutionLoopExitValue.erase(PN); 7525 } 7526 7527 PushDefUseChildren(I, Worklist); 7528 } 7529 } 7530 7531 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7532 LoopDispositions.clear(); 7533 } 7534 7535 /// Get the exact loop backedge taken count considering all loop exits. A 7536 /// computable result can only be returned for loops with all exiting blocks 7537 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7538 /// is never skipped. This is a valid assumption as long as the loop exits via 7539 /// that test. For precise results, it is the caller's responsibility to specify 7540 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7541 const SCEV * 7542 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7543 SCEVUnionPredicate *Preds) const { 7544 // If any exits were not computable, the loop is not computable. 7545 if (!isComplete() || ExitNotTaken.empty()) 7546 return SE->getCouldNotCompute(); 7547 7548 const BasicBlock *Latch = L->getLoopLatch(); 7549 // All exiting blocks we have collected must dominate the only backedge. 7550 if (!Latch) 7551 return SE->getCouldNotCompute(); 7552 7553 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7554 // count is simply a minimum out of all these calculated exit counts. 7555 SmallVector<const SCEV *, 2> Ops; 7556 for (auto &ENT : ExitNotTaken) { 7557 const SCEV *BECount = ENT.ExactNotTaken; 7558 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7559 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7560 "We should only have known counts for exiting blocks that dominate " 7561 "latch!"); 7562 7563 Ops.push_back(BECount); 7564 7565 if (Preds && !ENT.hasAlwaysTruePredicate()) 7566 Preds->add(ENT.Predicate.get()); 7567 7568 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7569 "Predicate should be always true!"); 7570 } 7571 7572 return SE->getUMinFromMismatchedTypes(Ops); 7573 } 7574 7575 /// Get the exact not taken count for this loop exit. 7576 const SCEV * 7577 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7578 ScalarEvolution *SE) const { 7579 for (auto &ENT : ExitNotTaken) 7580 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7581 return ENT.ExactNotTaken; 7582 7583 return SE->getCouldNotCompute(); 7584 } 7585 7586 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7587 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7588 for (auto &ENT : ExitNotTaken) 7589 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7590 return ENT.MaxNotTaken; 7591 7592 return SE->getCouldNotCompute(); 7593 } 7594 7595 /// getConstantMax - Get the constant max backedge taken count for the loop. 7596 const SCEV * 7597 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7598 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7599 return !ENT.hasAlwaysTruePredicate(); 7600 }; 7601 7602 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7603 return SE->getCouldNotCompute(); 7604 7605 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7606 isa<SCEVConstant>(getConstantMax())) && 7607 "No point in having a non-constant max backedge taken count!"); 7608 return getConstantMax(); 7609 } 7610 7611 const SCEV * 7612 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7613 ScalarEvolution *SE) { 7614 if (!SymbolicMax) 7615 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7616 return SymbolicMax; 7617 } 7618 7619 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7620 ScalarEvolution *SE) const { 7621 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7622 return !ENT.hasAlwaysTruePredicate(); 7623 }; 7624 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7625 } 7626 7627 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7628 return Operands.contains(S); 7629 } 7630 7631 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7632 : ExitLimit(E, E, false, None) { 7633 } 7634 7635 ScalarEvolution::ExitLimit::ExitLimit( 7636 const SCEV *E, const SCEV *M, bool MaxOrZero, 7637 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7638 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7639 // If we prove the max count is zero, so is the symbolic bound. This happens 7640 // in practice due to differences in a) how context sensitive we've chosen 7641 // to be and b) how we reason about bounds impied by UB. 7642 if (MaxNotTaken->isZero()) 7643 ExactNotTaken = MaxNotTaken; 7644 7645 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7646 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7647 "Exact is not allowed to be less precise than Max"); 7648 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7649 isa<SCEVConstant>(MaxNotTaken)) && 7650 "No point in having a non-constant max backedge taken count!"); 7651 for (auto *PredSet : PredSetList) 7652 for (auto *P : *PredSet) 7653 addPredicate(P); 7654 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7655 "Backedge count should be int"); 7656 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7657 "Max backedge count should be int"); 7658 } 7659 7660 ScalarEvolution::ExitLimit::ExitLimit( 7661 const SCEV *E, const SCEV *M, bool MaxOrZero, 7662 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7663 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7664 } 7665 7666 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7667 bool MaxOrZero) 7668 : ExitLimit(E, M, MaxOrZero, None) { 7669 } 7670 7671 class SCEVRecordOperands { 7672 SmallPtrSetImpl<const SCEV *> &Operands; 7673 7674 public: 7675 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7676 : Operands(Operands) {} 7677 bool follow(const SCEV *S) { 7678 Operands.insert(S); 7679 return true; 7680 } 7681 bool isDone() { return false; } 7682 }; 7683 7684 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7685 /// computable exit into a persistent ExitNotTakenInfo array. 7686 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7687 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7688 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7689 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7690 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7691 7692 ExitNotTaken.reserve(ExitCounts.size()); 7693 std::transform( 7694 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7695 [&](const EdgeExitInfo &EEI) { 7696 BasicBlock *ExitBB = EEI.first; 7697 const ExitLimit &EL = EEI.second; 7698 if (EL.Predicates.empty()) 7699 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7700 nullptr); 7701 7702 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7703 for (auto *Pred : EL.Predicates) 7704 Predicate->add(Pred); 7705 7706 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7707 std::move(Predicate)); 7708 }); 7709 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7710 isa<SCEVConstant>(ConstantMax)) && 7711 "No point in having a non-constant max backedge taken count!"); 7712 7713 SCEVRecordOperands RecordOperands(Operands); 7714 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7715 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7716 ST.visitAll(ConstantMax); 7717 for (auto &ENT : ExitNotTaken) 7718 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7719 ST.visitAll(ENT.ExactNotTaken); 7720 } 7721 7722 /// Compute the number of times the backedge of the specified loop will execute. 7723 ScalarEvolution::BackedgeTakenInfo 7724 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7725 bool AllowPredicates) { 7726 SmallVector<BasicBlock *, 8> ExitingBlocks; 7727 L->getExitingBlocks(ExitingBlocks); 7728 7729 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7730 7731 SmallVector<EdgeExitInfo, 4> ExitCounts; 7732 bool CouldComputeBECount = true; 7733 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7734 const SCEV *MustExitMaxBECount = nullptr; 7735 const SCEV *MayExitMaxBECount = nullptr; 7736 bool MustExitMaxOrZero = false; 7737 7738 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7739 // and compute maxBECount. 7740 // Do a union of all the predicates here. 7741 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7742 BasicBlock *ExitBB = ExitingBlocks[i]; 7743 7744 // We canonicalize untaken exits to br (constant), ignore them so that 7745 // proving an exit untaken doesn't negatively impact our ability to reason 7746 // about the loop as whole. 7747 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7748 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7749 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7750 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7751 continue; 7752 } 7753 7754 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7755 7756 assert((AllowPredicates || EL.Predicates.empty()) && 7757 "Predicated exit limit when predicates are not allowed!"); 7758 7759 // 1. For each exit that can be computed, add an entry to ExitCounts. 7760 // CouldComputeBECount is true only if all exits can be computed. 7761 if (EL.ExactNotTaken == getCouldNotCompute()) 7762 // We couldn't compute an exact value for this exit, so 7763 // we won't be able to compute an exact value for the loop. 7764 CouldComputeBECount = false; 7765 else 7766 ExitCounts.emplace_back(ExitBB, EL); 7767 7768 // 2. Derive the loop's MaxBECount from each exit's max number of 7769 // non-exiting iterations. Partition the loop exits into two kinds: 7770 // LoopMustExits and LoopMayExits. 7771 // 7772 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7773 // is a LoopMayExit. If any computable LoopMustExit is found, then 7774 // MaxBECount is the minimum EL.MaxNotTaken of computable 7775 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7776 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7777 // computable EL.MaxNotTaken. 7778 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7779 DT.dominates(ExitBB, Latch)) { 7780 if (!MustExitMaxBECount) { 7781 MustExitMaxBECount = EL.MaxNotTaken; 7782 MustExitMaxOrZero = EL.MaxOrZero; 7783 } else { 7784 MustExitMaxBECount = 7785 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7786 } 7787 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7788 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7789 MayExitMaxBECount = EL.MaxNotTaken; 7790 else { 7791 MayExitMaxBECount = 7792 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7793 } 7794 } 7795 } 7796 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7797 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7798 // The loop backedge will be taken the maximum or zero times if there's 7799 // a single exit that must be taken the maximum or zero times. 7800 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7801 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7802 MaxBECount, MaxOrZero); 7803 } 7804 7805 ScalarEvolution::ExitLimit 7806 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7807 bool AllowPredicates) { 7808 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7809 // If our exiting block does not dominate the latch, then its connection with 7810 // loop's exit limit may be far from trivial. 7811 const BasicBlock *Latch = L->getLoopLatch(); 7812 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7813 return getCouldNotCompute(); 7814 7815 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7816 Instruction *Term = ExitingBlock->getTerminator(); 7817 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7818 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7819 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7820 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7821 "It should have one successor in loop and one exit block!"); 7822 // Proceed to the next level to examine the exit condition expression. 7823 return computeExitLimitFromCond( 7824 L, BI->getCondition(), ExitIfTrue, 7825 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7826 } 7827 7828 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7829 // For switch, make sure that there is a single exit from the loop. 7830 BasicBlock *Exit = nullptr; 7831 for (auto *SBB : successors(ExitingBlock)) 7832 if (!L->contains(SBB)) { 7833 if (Exit) // Multiple exit successors. 7834 return getCouldNotCompute(); 7835 Exit = SBB; 7836 } 7837 assert(Exit && "Exiting block must have at least one exit"); 7838 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7839 /*ControlsExit=*/IsOnlyExit); 7840 } 7841 7842 return getCouldNotCompute(); 7843 } 7844 7845 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7846 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7847 bool ControlsExit, bool AllowPredicates) { 7848 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7849 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7850 ControlsExit, AllowPredicates); 7851 } 7852 7853 Optional<ScalarEvolution::ExitLimit> 7854 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7855 bool ExitIfTrue, bool ControlsExit, 7856 bool AllowPredicates) { 7857 (void)this->L; 7858 (void)this->ExitIfTrue; 7859 (void)this->AllowPredicates; 7860 7861 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7862 this->AllowPredicates == AllowPredicates && 7863 "Variance in assumed invariant key components!"); 7864 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7865 if (Itr == TripCountMap.end()) 7866 return None; 7867 return Itr->second; 7868 } 7869 7870 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7871 bool ExitIfTrue, 7872 bool ControlsExit, 7873 bool AllowPredicates, 7874 const ExitLimit &EL) { 7875 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7876 this->AllowPredicates == AllowPredicates && 7877 "Variance in assumed invariant key components!"); 7878 7879 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7880 assert(InsertResult.second && "Expected successful insertion!"); 7881 (void)InsertResult; 7882 (void)ExitIfTrue; 7883 } 7884 7885 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7886 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7887 bool ControlsExit, bool AllowPredicates) { 7888 7889 if (auto MaybeEL = 7890 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7891 return *MaybeEL; 7892 7893 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7894 ControlsExit, AllowPredicates); 7895 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7896 return EL; 7897 } 7898 7899 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7900 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7901 bool ControlsExit, bool AllowPredicates) { 7902 // Handle BinOp conditions (And, Or). 7903 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7904 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7905 return *LimitFromBinOp; 7906 7907 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7908 // Proceed to the next level to examine the icmp. 7909 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7910 ExitLimit EL = 7911 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7912 if (EL.hasFullInfo() || !AllowPredicates) 7913 return EL; 7914 7915 // Try again, but use SCEV predicates this time. 7916 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7917 /*AllowPredicates=*/true); 7918 } 7919 7920 // Check for a constant condition. These are normally stripped out by 7921 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7922 // preserve the CFG and is temporarily leaving constant conditions 7923 // in place. 7924 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7925 if (ExitIfTrue == !CI->getZExtValue()) 7926 // The backedge is always taken. 7927 return getCouldNotCompute(); 7928 else 7929 // The backedge is never taken. 7930 return getZero(CI->getType()); 7931 } 7932 7933 // If it's not an integer or pointer comparison then compute it the hard way. 7934 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7935 } 7936 7937 Optional<ScalarEvolution::ExitLimit> 7938 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7939 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7940 bool ControlsExit, bool AllowPredicates) { 7941 // Check if the controlling expression for this loop is an And or Or. 7942 Value *Op0, *Op1; 7943 bool IsAnd = false; 7944 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7945 IsAnd = true; 7946 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7947 IsAnd = false; 7948 else 7949 return None; 7950 7951 // EitherMayExit is true in these two cases: 7952 // br (and Op0 Op1), loop, exit 7953 // br (or Op0 Op1), exit, loop 7954 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7955 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7956 ControlsExit && !EitherMayExit, 7957 AllowPredicates); 7958 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7959 ControlsExit && !EitherMayExit, 7960 AllowPredicates); 7961 7962 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7963 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7964 if (isa<ConstantInt>(Op1)) 7965 return Op1 == NeutralElement ? EL0 : EL1; 7966 if (isa<ConstantInt>(Op0)) 7967 return Op0 == NeutralElement ? EL1 : EL0; 7968 7969 const SCEV *BECount = getCouldNotCompute(); 7970 const SCEV *MaxBECount = getCouldNotCompute(); 7971 if (EitherMayExit) { 7972 // Both conditions must be same for the loop to continue executing. 7973 // Choose the less conservative count. 7974 // If ExitCond is a short-circuit form (select), using 7975 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7976 // To see the detailed examples, please see 7977 // test/Analysis/ScalarEvolution/exit-count-select.ll 7978 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7979 if (!PoisonSafe) 7980 // Even if ExitCond is select, we can safely derive BECount using both 7981 // EL0 and EL1 in these cases: 7982 // (1) EL0.ExactNotTaken is non-zero 7983 // (2) EL1.ExactNotTaken is non-poison 7984 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7985 // it cannot be umin(0, ..)) 7986 // The PoisonSafe assignment below is simplified and the assertion after 7987 // BECount calculation fully guarantees the condition (3). 7988 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7989 isa<SCEVConstant>(EL1.ExactNotTaken); 7990 if (EL0.ExactNotTaken != getCouldNotCompute() && 7991 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7992 BECount = 7993 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7994 7995 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7996 // it should have been simplified to zero (see the condition (3) above) 7997 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7998 BECount->isZero()); 7999 } 8000 if (EL0.MaxNotTaken == getCouldNotCompute()) 8001 MaxBECount = EL1.MaxNotTaken; 8002 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8003 MaxBECount = EL0.MaxNotTaken; 8004 else 8005 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8006 } else { 8007 // Both conditions must be same at the same time for the loop to exit. 8008 // For now, be conservative. 8009 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8010 BECount = EL0.ExactNotTaken; 8011 } 8012 8013 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8014 // to be more aggressive when computing BECount than when computing 8015 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8016 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8017 // to not. 8018 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8019 !isa<SCEVCouldNotCompute>(BECount)) 8020 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8021 8022 return ExitLimit(BECount, MaxBECount, false, 8023 { &EL0.Predicates, &EL1.Predicates }); 8024 } 8025 8026 ScalarEvolution::ExitLimit 8027 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8028 ICmpInst *ExitCond, 8029 bool ExitIfTrue, 8030 bool ControlsExit, 8031 bool AllowPredicates) { 8032 // If the condition was exit on true, convert the condition to exit on false 8033 ICmpInst::Predicate Pred; 8034 if (!ExitIfTrue) 8035 Pred = ExitCond->getPredicate(); 8036 else 8037 Pred = ExitCond->getInversePredicate(); 8038 const ICmpInst::Predicate OriginalPred = Pred; 8039 8040 // Handle common loops like: for (X = "string"; *X; ++X) 8041 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 8042 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 8043 ExitLimit ItCnt = 8044 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 8045 if (ItCnt.hasAnyInfo()) 8046 return ItCnt; 8047 } 8048 8049 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8050 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8051 8052 // Try to evaluate any dependencies out of the loop. 8053 LHS = getSCEVAtScope(LHS, L); 8054 RHS = getSCEVAtScope(RHS, L); 8055 8056 // At this point, we would like to compute how many iterations of the 8057 // loop the predicate will return true for these inputs. 8058 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8059 // If there is a loop-invariant, force it into the RHS. 8060 std::swap(LHS, RHS); 8061 Pred = ICmpInst::getSwappedPredicate(Pred); 8062 } 8063 8064 // Simplify the operands before analyzing them. 8065 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8066 8067 // If we have a comparison of a chrec against a constant, try to use value 8068 // ranges to answer this query. 8069 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8070 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8071 if (AddRec->getLoop() == L) { 8072 // Form the constant range. 8073 ConstantRange CompRange = 8074 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8075 8076 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8077 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8078 } 8079 8080 switch (Pred) { 8081 case ICmpInst::ICMP_NE: { // while (X != Y) 8082 // Convert to: while (X-Y != 0) 8083 if (LHS->getType()->isPointerTy()) { 8084 LHS = getLosslessPtrToIntExpr(LHS); 8085 if (isa<SCEVCouldNotCompute>(LHS)) 8086 return LHS; 8087 } 8088 if (RHS->getType()->isPointerTy()) { 8089 RHS = getLosslessPtrToIntExpr(RHS); 8090 if (isa<SCEVCouldNotCompute>(RHS)) 8091 return RHS; 8092 } 8093 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8094 AllowPredicates); 8095 if (EL.hasAnyInfo()) return EL; 8096 break; 8097 } 8098 case ICmpInst::ICMP_EQ: { // while (X == Y) 8099 // Convert to: while (X-Y == 0) 8100 if (LHS->getType()->isPointerTy()) { 8101 LHS = getLosslessPtrToIntExpr(LHS); 8102 if (isa<SCEVCouldNotCompute>(LHS)) 8103 return LHS; 8104 } 8105 if (RHS->getType()->isPointerTy()) { 8106 RHS = getLosslessPtrToIntExpr(RHS); 8107 if (isa<SCEVCouldNotCompute>(RHS)) 8108 return RHS; 8109 } 8110 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8111 if (EL.hasAnyInfo()) return EL; 8112 break; 8113 } 8114 case ICmpInst::ICMP_SLT: 8115 case ICmpInst::ICMP_ULT: { // while (X < Y) 8116 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8117 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8118 AllowPredicates); 8119 if (EL.hasAnyInfo()) return EL; 8120 break; 8121 } 8122 case ICmpInst::ICMP_SGT: 8123 case ICmpInst::ICMP_UGT: { // while (X > Y) 8124 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8125 ExitLimit EL = 8126 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8127 AllowPredicates); 8128 if (EL.hasAnyInfo()) return EL; 8129 break; 8130 } 8131 default: 8132 break; 8133 } 8134 8135 auto *ExhaustiveCount = 8136 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8137 8138 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8139 return ExhaustiveCount; 8140 8141 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8142 ExitCond->getOperand(1), L, OriginalPred); 8143 } 8144 8145 ScalarEvolution::ExitLimit 8146 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8147 SwitchInst *Switch, 8148 BasicBlock *ExitingBlock, 8149 bool ControlsExit) { 8150 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8151 8152 // Give up if the exit is the default dest of a switch. 8153 if (Switch->getDefaultDest() == ExitingBlock) 8154 return getCouldNotCompute(); 8155 8156 assert(L->contains(Switch->getDefaultDest()) && 8157 "Default case must not exit the loop!"); 8158 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8159 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8160 8161 // while (X != Y) --> while (X-Y != 0) 8162 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8163 if (EL.hasAnyInfo()) 8164 return EL; 8165 8166 return getCouldNotCompute(); 8167 } 8168 8169 static ConstantInt * 8170 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8171 ScalarEvolution &SE) { 8172 const SCEV *InVal = SE.getConstant(C); 8173 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8174 assert(isa<SCEVConstant>(Val) && 8175 "Evaluation of SCEV at constant didn't fold correctly?"); 8176 return cast<SCEVConstant>(Val)->getValue(); 8177 } 8178 8179 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8180 /// compute the backedge execution count. 8181 ScalarEvolution::ExitLimit 8182 ScalarEvolution::computeLoadConstantCompareExitLimit( 8183 LoadInst *LI, 8184 Constant *RHS, 8185 const Loop *L, 8186 ICmpInst::Predicate predicate) { 8187 if (LI->isVolatile()) return getCouldNotCompute(); 8188 8189 // Check to see if the loaded pointer is a getelementptr of a global. 8190 // TODO: Use SCEV instead of manually grubbing with GEPs. 8191 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8192 if (!GEP) return getCouldNotCompute(); 8193 8194 // Make sure that it is really a constant global we are gepping, with an 8195 // initializer, and make sure the first IDX is really 0. 8196 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8197 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8198 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8199 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8200 return getCouldNotCompute(); 8201 8202 // Okay, we allow one non-constant index into the GEP instruction. 8203 Value *VarIdx = nullptr; 8204 std::vector<Constant*> Indexes; 8205 unsigned VarIdxNum = 0; 8206 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8207 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8208 Indexes.push_back(CI); 8209 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8210 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8211 VarIdx = GEP->getOperand(i); 8212 VarIdxNum = i-2; 8213 Indexes.push_back(nullptr); 8214 } 8215 8216 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8217 if (!VarIdx) 8218 return getCouldNotCompute(); 8219 8220 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8221 // Check to see if X is a loop variant variable value now. 8222 const SCEV *Idx = getSCEV(VarIdx); 8223 Idx = getSCEVAtScope(Idx, L); 8224 8225 // We can only recognize very limited forms of loop index expressions, in 8226 // particular, only affine AddRec's like {C1,+,C2}<L>. 8227 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8228 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8229 isLoopInvariant(IdxExpr, L) || 8230 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8231 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8232 return getCouldNotCompute(); 8233 8234 unsigned MaxSteps = MaxBruteForceIterations; 8235 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8236 ConstantInt *ItCst = ConstantInt::get( 8237 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8238 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8239 8240 // Form the GEP offset. 8241 Indexes[VarIdxNum] = Val; 8242 8243 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8244 Indexes); 8245 if (!Result) break; // Cannot compute! 8246 8247 // Evaluate the condition for this iteration. 8248 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8249 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8250 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8251 ++NumArrayLenItCounts; 8252 return getConstant(ItCst); // Found terminating iteration! 8253 } 8254 } 8255 return getCouldNotCompute(); 8256 } 8257 8258 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8259 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8260 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8261 if (!RHS) 8262 return getCouldNotCompute(); 8263 8264 const BasicBlock *Latch = L->getLoopLatch(); 8265 if (!Latch) 8266 return getCouldNotCompute(); 8267 8268 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8269 if (!Predecessor) 8270 return getCouldNotCompute(); 8271 8272 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8273 // Return LHS in OutLHS and shift_opt in OutOpCode. 8274 auto MatchPositiveShift = 8275 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8276 8277 using namespace PatternMatch; 8278 8279 ConstantInt *ShiftAmt; 8280 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8281 OutOpCode = Instruction::LShr; 8282 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8283 OutOpCode = Instruction::AShr; 8284 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8285 OutOpCode = Instruction::Shl; 8286 else 8287 return false; 8288 8289 return ShiftAmt->getValue().isStrictlyPositive(); 8290 }; 8291 8292 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8293 // 8294 // loop: 8295 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8296 // %iv.shifted = lshr i32 %iv, <positive constant> 8297 // 8298 // Return true on a successful match. Return the corresponding PHI node (%iv 8299 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8300 auto MatchShiftRecurrence = 8301 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8302 Optional<Instruction::BinaryOps> PostShiftOpCode; 8303 8304 { 8305 Instruction::BinaryOps OpC; 8306 Value *V; 8307 8308 // If we encounter a shift instruction, "peel off" the shift operation, 8309 // and remember that we did so. Later when we inspect %iv's backedge 8310 // value, we will make sure that the backedge value uses the same 8311 // operation. 8312 // 8313 // Note: the peeled shift operation does not have to be the same 8314 // instruction as the one feeding into the PHI's backedge value. We only 8315 // really care about it being the same *kind* of shift instruction -- 8316 // that's all that is required for our later inferences to hold. 8317 if (MatchPositiveShift(LHS, V, OpC)) { 8318 PostShiftOpCode = OpC; 8319 LHS = V; 8320 } 8321 } 8322 8323 PNOut = dyn_cast<PHINode>(LHS); 8324 if (!PNOut || PNOut->getParent() != L->getHeader()) 8325 return false; 8326 8327 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8328 Value *OpLHS; 8329 8330 return 8331 // The backedge value for the PHI node must be a shift by a positive 8332 // amount 8333 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8334 8335 // of the PHI node itself 8336 OpLHS == PNOut && 8337 8338 // and the kind of shift should be match the kind of shift we peeled 8339 // off, if any. 8340 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8341 }; 8342 8343 PHINode *PN; 8344 Instruction::BinaryOps OpCode; 8345 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8346 return getCouldNotCompute(); 8347 8348 const DataLayout &DL = getDataLayout(); 8349 8350 // The key rationale for this optimization is that for some kinds of shift 8351 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8352 // within a finite number of iterations. If the condition guarding the 8353 // backedge (in the sense that the backedge is taken if the condition is true) 8354 // is false for the value the shift recurrence stabilizes to, then we know 8355 // that the backedge is taken only a finite number of times. 8356 8357 ConstantInt *StableValue = nullptr; 8358 switch (OpCode) { 8359 default: 8360 llvm_unreachable("Impossible case!"); 8361 8362 case Instruction::AShr: { 8363 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8364 // bitwidth(K) iterations. 8365 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8366 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8367 Predecessor->getTerminator(), &DT); 8368 auto *Ty = cast<IntegerType>(RHS->getType()); 8369 if (Known.isNonNegative()) 8370 StableValue = ConstantInt::get(Ty, 0); 8371 else if (Known.isNegative()) 8372 StableValue = ConstantInt::get(Ty, -1, true); 8373 else 8374 return getCouldNotCompute(); 8375 8376 break; 8377 } 8378 case Instruction::LShr: 8379 case Instruction::Shl: 8380 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8381 // stabilize to 0 in at most bitwidth(K) iterations. 8382 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8383 break; 8384 } 8385 8386 auto *Result = 8387 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8388 assert(Result->getType()->isIntegerTy(1) && 8389 "Otherwise cannot be an operand to a branch instruction"); 8390 8391 if (Result->isZeroValue()) { 8392 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8393 const SCEV *UpperBound = 8394 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8395 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8396 } 8397 8398 return getCouldNotCompute(); 8399 } 8400 8401 /// Return true if we can constant fold an instruction of the specified type, 8402 /// assuming that all operands were constants. 8403 static bool CanConstantFold(const Instruction *I) { 8404 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8405 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8406 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8407 return true; 8408 8409 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8410 if (const Function *F = CI->getCalledFunction()) 8411 return canConstantFoldCallTo(CI, F); 8412 return false; 8413 } 8414 8415 /// Determine whether this instruction can constant evolve within this loop 8416 /// assuming its operands can all constant evolve. 8417 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8418 // An instruction outside of the loop can't be derived from a loop PHI. 8419 if (!L->contains(I)) return false; 8420 8421 if (isa<PHINode>(I)) { 8422 // We don't currently keep track of the control flow needed to evaluate 8423 // PHIs, so we cannot handle PHIs inside of loops. 8424 return L->getHeader() == I->getParent(); 8425 } 8426 8427 // If we won't be able to constant fold this expression even if the operands 8428 // are constants, bail early. 8429 return CanConstantFold(I); 8430 } 8431 8432 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8433 /// recursing through each instruction operand until reaching a loop header phi. 8434 static PHINode * 8435 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8436 DenseMap<Instruction *, PHINode *> &PHIMap, 8437 unsigned Depth) { 8438 if (Depth > MaxConstantEvolvingDepth) 8439 return nullptr; 8440 8441 // Otherwise, we can evaluate this instruction if all of its operands are 8442 // constant or derived from a PHI node themselves. 8443 PHINode *PHI = nullptr; 8444 for (Value *Op : UseInst->operands()) { 8445 if (isa<Constant>(Op)) continue; 8446 8447 Instruction *OpInst = dyn_cast<Instruction>(Op); 8448 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8449 8450 PHINode *P = dyn_cast<PHINode>(OpInst); 8451 if (!P) 8452 // If this operand is already visited, reuse the prior result. 8453 // We may have P != PHI if this is the deepest point at which the 8454 // inconsistent paths meet. 8455 P = PHIMap.lookup(OpInst); 8456 if (!P) { 8457 // Recurse and memoize the results, whether a phi is found or not. 8458 // This recursive call invalidates pointers into PHIMap. 8459 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8460 PHIMap[OpInst] = P; 8461 } 8462 if (!P) 8463 return nullptr; // Not evolving from PHI 8464 if (PHI && PHI != P) 8465 return nullptr; // Evolving from multiple different PHIs. 8466 PHI = P; 8467 } 8468 // This is a expression evolving from a constant PHI! 8469 return PHI; 8470 } 8471 8472 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8473 /// in the loop that V is derived from. We allow arbitrary operations along the 8474 /// way, but the operands of an operation must either be constants or a value 8475 /// derived from a constant PHI. If this expression does not fit with these 8476 /// constraints, return null. 8477 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8478 Instruction *I = dyn_cast<Instruction>(V); 8479 if (!I || !canConstantEvolve(I, L)) return nullptr; 8480 8481 if (PHINode *PN = dyn_cast<PHINode>(I)) 8482 return PN; 8483 8484 // Record non-constant instructions contained by the loop. 8485 DenseMap<Instruction *, PHINode *> PHIMap; 8486 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8487 } 8488 8489 /// EvaluateExpression - Given an expression that passes the 8490 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8491 /// in the loop has the value PHIVal. If we can't fold this expression for some 8492 /// reason, return null. 8493 static Constant *EvaluateExpression(Value *V, const Loop *L, 8494 DenseMap<Instruction *, Constant *> &Vals, 8495 const DataLayout &DL, 8496 const TargetLibraryInfo *TLI) { 8497 // Convenient constant check, but redundant for recursive calls. 8498 if (Constant *C = dyn_cast<Constant>(V)) return C; 8499 Instruction *I = dyn_cast<Instruction>(V); 8500 if (!I) return nullptr; 8501 8502 if (Constant *C = Vals.lookup(I)) return C; 8503 8504 // An instruction inside the loop depends on a value outside the loop that we 8505 // weren't given a mapping for, or a value such as a call inside the loop. 8506 if (!canConstantEvolve(I, L)) return nullptr; 8507 8508 // An unmapped PHI can be due to a branch or another loop inside this loop, 8509 // or due to this not being the initial iteration through a loop where we 8510 // couldn't compute the evolution of this particular PHI last time. 8511 if (isa<PHINode>(I)) return nullptr; 8512 8513 std::vector<Constant*> Operands(I->getNumOperands()); 8514 8515 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8516 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8517 if (!Operand) { 8518 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8519 if (!Operands[i]) return nullptr; 8520 continue; 8521 } 8522 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8523 Vals[Operand] = C; 8524 if (!C) return nullptr; 8525 Operands[i] = C; 8526 } 8527 8528 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8529 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8530 Operands[1], DL, TLI); 8531 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8532 if (!LI->isVolatile()) 8533 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8534 } 8535 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8536 } 8537 8538 8539 // If every incoming value to PN except the one for BB is a specific Constant, 8540 // return that, else return nullptr. 8541 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8542 Constant *IncomingVal = nullptr; 8543 8544 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8545 if (PN->getIncomingBlock(i) == BB) 8546 continue; 8547 8548 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8549 if (!CurrentVal) 8550 return nullptr; 8551 8552 if (IncomingVal != CurrentVal) { 8553 if (IncomingVal) 8554 return nullptr; 8555 IncomingVal = CurrentVal; 8556 } 8557 } 8558 8559 return IncomingVal; 8560 } 8561 8562 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8563 /// in the header of its containing loop, we know the loop executes a 8564 /// constant number of times, and the PHI node is just a recurrence 8565 /// involving constants, fold it. 8566 Constant * 8567 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8568 const APInt &BEs, 8569 const Loop *L) { 8570 auto I = ConstantEvolutionLoopExitValue.find(PN); 8571 if (I != ConstantEvolutionLoopExitValue.end()) 8572 return I->second; 8573 8574 if (BEs.ugt(MaxBruteForceIterations)) 8575 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8576 8577 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8578 8579 DenseMap<Instruction *, Constant *> CurrentIterVals; 8580 BasicBlock *Header = L->getHeader(); 8581 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8582 8583 BasicBlock *Latch = L->getLoopLatch(); 8584 if (!Latch) 8585 return nullptr; 8586 8587 for (PHINode &PHI : Header->phis()) { 8588 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8589 CurrentIterVals[&PHI] = StartCST; 8590 } 8591 if (!CurrentIterVals.count(PN)) 8592 return RetVal = nullptr; 8593 8594 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8595 8596 // Execute the loop symbolically to determine the exit value. 8597 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8598 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8599 8600 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8601 unsigned IterationNum = 0; 8602 const DataLayout &DL = getDataLayout(); 8603 for (; ; ++IterationNum) { 8604 if (IterationNum == NumIterations) 8605 return RetVal = CurrentIterVals[PN]; // Got exit value! 8606 8607 // Compute the value of the PHIs for the next iteration. 8608 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8609 DenseMap<Instruction *, Constant *> NextIterVals; 8610 Constant *NextPHI = 8611 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8612 if (!NextPHI) 8613 return nullptr; // Couldn't evaluate! 8614 NextIterVals[PN] = NextPHI; 8615 8616 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8617 8618 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8619 // cease to be able to evaluate one of them or if they stop evolving, 8620 // because that doesn't necessarily prevent us from computing PN. 8621 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8622 for (const auto &I : CurrentIterVals) { 8623 PHINode *PHI = dyn_cast<PHINode>(I.first); 8624 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8625 PHIsToCompute.emplace_back(PHI, I.second); 8626 } 8627 // We use two distinct loops because EvaluateExpression may invalidate any 8628 // iterators into CurrentIterVals. 8629 for (const auto &I : PHIsToCompute) { 8630 PHINode *PHI = I.first; 8631 Constant *&NextPHI = NextIterVals[PHI]; 8632 if (!NextPHI) { // Not already computed. 8633 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8634 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8635 } 8636 if (NextPHI != I.second) 8637 StoppedEvolving = false; 8638 } 8639 8640 // If all entries in CurrentIterVals == NextIterVals then we can stop 8641 // iterating, the loop can't continue to change. 8642 if (StoppedEvolving) 8643 return RetVal = CurrentIterVals[PN]; 8644 8645 CurrentIterVals.swap(NextIterVals); 8646 } 8647 } 8648 8649 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8650 Value *Cond, 8651 bool ExitWhen) { 8652 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8653 if (!PN) return getCouldNotCompute(); 8654 8655 // If the loop is canonicalized, the PHI will have exactly two entries. 8656 // That's the only form we support here. 8657 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8658 8659 DenseMap<Instruction *, Constant *> CurrentIterVals; 8660 BasicBlock *Header = L->getHeader(); 8661 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8662 8663 BasicBlock *Latch = L->getLoopLatch(); 8664 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8665 8666 for (PHINode &PHI : Header->phis()) { 8667 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8668 CurrentIterVals[&PHI] = StartCST; 8669 } 8670 if (!CurrentIterVals.count(PN)) 8671 return getCouldNotCompute(); 8672 8673 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8674 // the loop symbolically to determine when the condition gets a value of 8675 // "ExitWhen". 8676 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8677 const DataLayout &DL = getDataLayout(); 8678 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8679 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8680 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8681 8682 // Couldn't symbolically evaluate. 8683 if (!CondVal) return getCouldNotCompute(); 8684 8685 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8686 ++NumBruteForceTripCountsComputed; 8687 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8688 } 8689 8690 // Update all the PHI nodes for the next iteration. 8691 DenseMap<Instruction *, Constant *> NextIterVals; 8692 8693 // Create a list of which PHIs we need to compute. We want to do this before 8694 // calling EvaluateExpression on them because that may invalidate iterators 8695 // into CurrentIterVals. 8696 SmallVector<PHINode *, 8> PHIsToCompute; 8697 for (const auto &I : CurrentIterVals) { 8698 PHINode *PHI = dyn_cast<PHINode>(I.first); 8699 if (!PHI || PHI->getParent() != Header) continue; 8700 PHIsToCompute.push_back(PHI); 8701 } 8702 for (PHINode *PHI : PHIsToCompute) { 8703 Constant *&NextPHI = NextIterVals[PHI]; 8704 if (NextPHI) continue; // Already computed! 8705 8706 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8707 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8708 } 8709 CurrentIterVals.swap(NextIterVals); 8710 } 8711 8712 // Too many iterations were needed to evaluate. 8713 return getCouldNotCompute(); 8714 } 8715 8716 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8717 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8718 ValuesAtScopes[V]; 8719 // Check to see if we've folded this expression at this loop before. 8720 for (auto &LS : Values) 8721 if (LS.first == L) 8722 return LS.second ? LS.second : V; 8723 8724 Values.emplace_back(L, nullptr); 8725 8726 // Otherwise compute it. 8727 const SCEV *C = computeSCEVAtScope(V, L); 8728 for (auto &LS : reverse(ValuesAtScopes[V])) 8729 if (LS.first == L) { 8730 LS.second = C; 8731 break; 8732 } 8733 return C; 8734 } 8735 8736 /// This builds up a Constant using the ConstantExpr interface. That way, we 8737 /// will return Constants for objects which aren't represented by a 8738 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8739 /// Returns NULL if the SCEV isn't representable as a Constant. 8740 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8741 switch (V->getSCEVType()) { 8742 case scCouldNotCompute: 8743 case scAddRecExpr: 8744 return nullptr; 8745 case scConstant: 8746 return cast<SCEVConstant>(V)->getValue(); 8747 case scUnknown: 8748 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8749 case scSignExtend: { 8750 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8751 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8752 return ConstantExpr::getSExt(CastOp, SS->getType()); 8753 return nullptr; 8754 } 8755 case scZeroExtend: { 8756 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8757 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8758 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8759 return nullptr; 8760 } 8761 case scPtrToInt: { 8762 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8763 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8764 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8765 8766 return nullptr; 8767 } 8768 case scTruncate: { 8769 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8770 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8771 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8772 return nullptr; 8773 } 8774 case scAddExpr: { 8775 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8776 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8777 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8778 unsigned AS = PTy->getAddressSpace(); 8779 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8780 C = ConstantExpr::getBitCast(C, DestPtrTy); 8781 } 8782 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8783 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8784 if (!C2) 8785 return nullptr; 8786 8787 // First pointer! 8788 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8789 unsigned AS = C2->getType()->getPointerAddressSpace(); 8790 std::swap(C, C2); 8791 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8792 // The offsets have been converted to bytes. We can add bytes to an 8793 // i8* by GEP with the byte count in the first index. 8794 C = ConstantExpr::getBitCast(C, DestPtrTy); 8795 } 8796 8797 // Don't bother trying to sum two pointers. We probably can't 8798 // statically compute a load that results from it anyway. 8799 if (C2->getType()->isPointerTy()) 8800 return nullptr; 8801 8802 if (C->getType()->isPointerTy()) { 8803 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8804 C, C2); 8805 } else { 8806 C = ConstantExpr::getAdd(C, C2); 8807 } 8808 } 8809 return C; 8810 } 8811 return nullptr; 8812 } 8813 case scMulExpr: { 8814 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8815 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8816 // Don't bother with pointers at all. 8817 if (C->getType()->isPointerTy()) 8818 return nullptr; 8819 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8820 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8821 if (!C2 || C2->getType()->isPointerTy()) 8822 return nullptr; 8823 C = ConstantExpr::getMul(C, C2); 8824 } 8825 return C; 8826 } 8827 return nullptr; 8828 } 8829 case scUDivExpr: { 8830 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8831 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8832 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8833 if (LHS->getType() == RHS->getType()) 8834 return ConstantExpr::getUDiv(LHS, RHS); 8835 return nullptr; 8836 } 8837 case scSMaxExpr: 8838 case scUMaxExpr: 8839 case scSMinExpr: 8840 case scUMinExpr: 8841 return nullptr; // TODO: smax, umax, smin, umax. 8842 } 8843 llvm_unreachable("Unknown SCEV kind!"); 8844 } 8845 8846 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8847 if (isa<SCEVConstant>(V)) return V; 8848 8849 // If this instruction is evolved from a constant-evolving PHI, compute the 8850 // exit value from the loop without using SCEVs. 8851 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8852 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8853 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8854 const Loop *CurrLoop = this->LI[I->getParent()]; 8855 // Looking for loop exit value. 8856 if (CurrLoop && CurrLoop->getParentLoop() == L && 8857 PN->getParent() == CurrLoop->getHeader()) { 8858 // Okay, there is no closed form solution for the PHI node. Check 8859 // to see if the loop that contains it has a known backedge-taken 8860 // count. If so, we may be able to force computation of the exit 8861 // value. 8862 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8863 // This trivial case can show up in some degenerate cases where 8864 // the incoming IR has not yet been fully simplified. 8865 if (BackedgeTakenCount->isZero()) { 8866 Value *InitValue = nullptr; 8867 bool MultipleInitValues = false; 8868 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8869 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8870 if (!InitValue) 8871 InitValue = PN->getIncomingValue(i); 8872 else if (InitValue != PN->getIncomingValue(i)) { 8873 MultipleInitValues = true; 8874 break; 8875 } 8876 } 8877 } 8878 if (!MultipleInitValues && InitValue) 8879 return getSCEV(InitValue); 8880 } 8881 // Do we have a loop invariant value flowing around the backedge 8882 // for a loop which must execute the backedge? 8883 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8884 isKnownPositive(BackedgeTakenCount) && 8885 PN->getNumIncomingValues() == 2) { 8886 8887 unsigned InLoopPred = 8888 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8889 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8890 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8891 return getSCEV(BackedgeVal); 8892 } 8893 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8894 // Okay, we know how many times the containing loop executes. If 8895 // this is a constant evolving PHI node, get the final value at 8896 // the specified iteration number. 8897 Constant *RV = getConstantEvolutionLoopExitValue( 8898 PN, BTCC->getAPInt(), CurrLoop); 8899 if (RV) return getSCEV(RV); 8900 } 8901 } 8902 8903 // If there is a single-input Phi, evaluate it at our scope. If we can 8904 // prove that this replacement does not break LCSSA form, use new value. 8905 if (PN->getNumOperands() == 1) { 8906 const SCEV *Input = getSCEV(PN->getOperand(0)); 8907 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8908 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8909 // for the simplest case just support constants. 8910 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8911 } 8912 } 8913 8914 // Okay, this is an expression that we cannot symbolically evaluate 8915 // into a SCEV. Check to see if it's possible to symbolically evaluate 8916 // the arguments into constants, and if so, try to constant propagate the 8917 // result. This is particularly useful for computing loop exit values. 8918 if (CanConstantFold(I)) { 8919 SmallVector<Constant *, 4> Operands; 8920 bool MadeImprovement = false; 8921 for (Value *Op : I->operands()) { 8922 if (Constant *C = dyn_cast<Constant>(Op)) { 8923 Operands.push_back(C); 8924 continue; 8925 } 8926 8927 // If any of the operands is non-constant and if they are 8928 // non-integer and non-pointer, don't even try to analyze them 8929 // with scev techniques. 8930 if (!isSCEVable(Op->getType())) 8931 return V; 8932 8933 const SCEV *OrigV = getSCEV(Op); 8934 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8935 MadeImprovement |= OrigV != OpV; 8936 8937 Constant *C = BuildConstantFromSCEV(OpV); 8938 if (!C) return V; 8939 if (C->getType() != Op->getType()) 8940 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8941 Op->getType(), 8942 false), 8943 C, Op->getType()); 8944 Operands.push_back(C); 8945 } 8946 8947 // Check to see if getSCEVAtScope actually made an improvement. 8948 if (MadeImprovement) { 8949 Constant *C = nullptr; 8950 const DataLayout &DL = getDataLayout(); 8951 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8952 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8953 Operands[1], DL, &TLI); 8954 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8955 if (!Load->isVolatile()) 8956 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8957 DL); 8958 } else 8959 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8960 if (!C) return V; 8961 return getSCEV(C); 8962 } 8963 } 8964 } 8965 8966 // This is some other type of SCEVUnknown, just return it. 8967 return V; 8968 } 8969 8970 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8971 // Avoid performing the look-up in the common case where the specified 8972 // expression has no loop-variant portions. 8973 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8974 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8975 if (OpAtScope != Comm->getOperand(i)) { 8976 // Okay, at least one of these operands is loop variant but might be 8977 // foldable. Build a new instance of the folded commutative expression. 8978 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8979 Comm->op_begin()+i); 8980 NewOps.push_back(OpAtScope); 8981 8982 for (++i; i != e; ++i) { 8983 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8984 NewOps.push_back(OpAtScope); 8985 } 8986 if (isa<SCEVAddExpr>(Comm)) 8987 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8988 if (isa<SCEVMulExpr>(Comm)) 8989 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8990 if (isa<SCEVMinMaxExpr>(Comm)) 8991 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8992 llvm_unreachable("Unknown commutative SCEV type!"); 8993 } 8994 } 8995 // If we got here, all operands are loop invariant. 8996 return Comm; 8997 } 8998 8999 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9000 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9001 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9002 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9003 return Div; // must be loop invariant 9004 return getUDivExpr(LHS, RHS); 9005 } 9006 9007 // If this is a loop recurrence for a loop that does not contain L, then we 9008 // are dealing with the final value computed by the loop. 9009 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9010 // First, attempt to evaluate each operand. 9011 // Avoid performing the look-up in the common case where the specified 9012 // expression has no loop-variant portions. 9013 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9014 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9015 if (OpAtScope == AddRec->getOperand(i)) 9016 continue; 9017 9018 // Okay, at least one of these operands is loop variant but might be 9019 // foldable. Build a new instance of the folded commutative expression. 9020 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9021 AddRec->op_begin()+i); 9022 NewOps.push_back(OpAtScope); 9023 for (++i; i != e; ++i) 9024 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9025 9026 const SCEV *FoldedRec = 9027 getAddRecExpr(NewOps, AddRec->getLoop(), 9028 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9029 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9030 // The addrec may be folded to a nonrecurrence, for example, if the 9031 // induction variable is multiplied by zero after constant folding. Go 9032 // ahead and return the folded value. 9033 if (!AddRec) 9034 return FoldedRec; 9035 break; 9036 } 9037 9038 // If the scope is outside the addrec's loop, evaluate it by using the 9039 // loop exit value of the addrec. 9040 if (!AddRec->getLoop()->contains(L)) { 9041 // To evaluate this recurrence, we need to know how many times the AddRec 9042 // loop iterates. Compute this now. 9043 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9044 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9045 9046 // Then, evaluate the AddRec. 9047 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9048 } 9049 9050 return AddRec; 9051 } 9052 9053 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9054 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9055 if (Op == Cast->getOperand()) 9056 return Cast; // must be loop invariant 9057 return getZeroExtendExpr(Op, Cast->getType()); 9058 } 9059 9060 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9061 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9062 if (Op == Cast->getOperand()) 9063 return Cast; // must be loop invariant 9064 return getSignExtendExpr(Op, Cast->getType()); 9065 } 9066 9067 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9068 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9069 if (Op == Cast->getOperand()) 9070 return Cast; // must be loop invariant 9071 return getTruncateExpr(Op, Cast->getType()); 9072 } 9073 9074 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9075 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9076 if (Op == Cast->getOperand()) 9077 return Cast; // must be loop invariant 9078 return getPtrToIntExpr(Op, Cast->getType()); 9079 } 9080 9081 llvm_unreachable("Unknown SCEV type!"); 9082 } 9083 9084 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9085 return getSCEVAtScope(getSCEV(V), L); 9086 } 9087 9088 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9089 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9090 return stripInjectiveFunctions(ZExt->getOperand()); 9091 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9092 return stripInjectiveFunctions(SExt->getOperand()); 9093 return S; 9094 } 9095 9096 /// Finds the minimum unsigned root of the following equation: 9097 /// 9098 /// A * X = B (mod N) 9099 /// 9100 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9101 /// A and B isn't important. 9102 /// 9103 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9104 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9105 ScalarEvolution &SE) { 9106 uint32_t BW = A.getBitWidth(); 9107 assert(BW == SE.getTypeSizeInBits(B->getType())); 9108 assert(A != 0 && "A must be non-zero."); 9109 9110 // 1. D = gcd(A, N) 9111 // 9112 // The gcd of A and N may have only one prime factor: 2. The number of 9113 // trailing zeros in A is its multiplicity 9114 uint32_t Mult2 = A.countTrailingZeros(); 9115 // D = 2^Mult2 9116 9117 // 2. Check if B is divisible by D. 9118 // 9119 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9120 // is not less than multiplicity of this prime factor for D. 9121 if (SE.GetMinTrailingZeros(B) < Mult2) 9122 return SE.getCouldNotCompute(); 9123 9124 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9125 // modulo (N / D). 9126 // 9127 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9128 // (N / D) in general. The inverse itself always fits into BW bits, though, 9129 // so we immediately truncate it. 9130 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9131 APInt Mod(BW + 1, 0); 9132 Mod.setBit(BW - Mult2); // Mod = N / D 9133 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9134 9135 // 4. Compute the minimum unsigned root of the equation: 9136 // I * (B / D) mod (N / D) 9137 // To simplify the computation, we factor out the divide by D: 9138 // (I * B mod N) / D 9139 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9140 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9141 } 9142 9143 /// For a given quadratic addrec, generate coefficients of the corresponding 9144 /// quadratic equation, multiplied by a common value to ensure that they are 9145 /// integers. 9146 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9147 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9148 /// were multiplied by, and BitWidth is the bit width of the original addrec 9149 /// coefficients. 9150 /// This function returns None if the addrec coefficients are not compile- 9151 /// time constants. 9152 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9153 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9154 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9155 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9156 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9157 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9158 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9159 << *AddRec << '\n'); 9160 9161 // We currently can only solve this if the coefficients are constants. 9162 if (!LC || !MC || !NC) { 9163 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9164 return None; 9165 } 9166 9167 APInt L = LC->getAPInt(); 9168 APInt M = MC->getAPInt(); 9169 APInt N = NC->getAPInt(); 9170 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9171 9172 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9173 unsigned NewWidth = BitWidth + 1; 9174 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9175 << BitWidth << '\n'); 9176 // The sign-extension (as opposed to a zero-extension) here matches the 9177 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9178 N = N.sext(NewWidth); 9179 M = M.sext(NewWidth); 9180 L = L.sext(NewWidth); 9181 9182 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9183 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9184 // L+M, L+2M+N, L+3M+3N, ... 9185 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9186 // 9187 // The equation Acc = 0 is then 9188 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9189 // In a quadratic form it becomes: 9190 // N n^2 + (2M-N) n + 2L = 0. 9191 9192 APInt A = N; 9193 APInt B = 2 * M - A; 9194 APInt C = 2 * L; 9195 APInt T = APInt(NewWidth, 2); 9196 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9197 << "x + " << C << ", coeff bw: " << NewWidth 9198 << ", multiplied by " << T << '\n'); 9199 return std::make_tuple(A, B, C, T, BitWidth); 9200 } 9201 9202 /// Helper function to compare optional APInts: 9203 /// (a) if X and Y both exist, return min(X, Y), 9204 /// (b) if neither X nor Y exist, return None, 9205 /// (c) if exactly one of X and Y exists, return that value. 9206 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9207 if (X.hasValue() && Y.hasValue()) { 9208 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9209 APInt XW = X->sextOrSelf(W); 9210 APInt YW = Y->sextOrSelf(W); 9211 return XW.slt(YW) ? *X : *Y; 9212 } 9213 if (!X.hasValue() && !Y.hasValue()) 9214 return None; 9215 return X.hasValue() ? *X : *Y; 9216 } 9217 9218 /// Helper function to truncate an optional APInt to a given BitWidth. 9219 /// When solving addrec-related equations, it is preferable to return a value 9220 /// that has the same bit width as the original addrec's coefficients. If the 9221 /// solution fits in the original bit width, truncate it (except for i1). 9222 /// Returning a value of a different bit width may inhibit some optimizations. 9223 /// 9224 /// In general, a solution to a quadratic equation generated from an addrec 9225 /// may require BW+1 bits, where BW is the bit width of the addrec's 9226 /// coefficients. The reason is that the coefficients of the quadratic 9227 /// equation are BW+1 bits wide (to avoid truncation when converting from 9228 /// the addrec to the equation). 9229 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9230 if (!X.hasValue()) 9231 return None; 9232 unsigned W = X->getBitWidth(); 9233 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9234 return X->trunc(BitWidth); 9235 return X; 9236 } 9237 9238 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9239 /// iterations. The values L, M, N are assumed to be signed, and they 9240 /// should all have the same bit widths. 9241 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9242 /// where BW is the bit width of the addrec's coefficients. 9243 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9244 /// returned as such, otherwise the bit width of the returned value may 9245 /// be greater than BW. 9246 /// 9247 /// This function returns None if 9248 /// (a) the addrec coefficients are not constant, or 9249 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9250 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9251 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9252 static Optional<APInt> 9253 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9254 APInt A, B, C, M; 9255 unsigned BitWidth; 9256 auto T = GetQuadraticEquation(AddRec); 9257 if (!T.hasValue()) 9258 return None; 9259 9260 std::tie(A, B, C, M, BitWidth) = *T; 9261 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9262 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9263 if (!X.hasValue()) 9264 return None; 9265 9266 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9267 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9268 if (!V->isZero()) 9269 return None; 9270 9271 return TruncIfPossible(X, BitWidth); 9272 } 9273 9274 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9275 /// iterations. The values M, N are assumed to be signed, and they 9276 /// should all have the same bit widths. 9277 /// Find the least n such that c(n) does not belong to the given range, 9278 /// while c(n-1) does. 9279 /// 9280 /// This function returns None if 9281 /// (a) the addrec coefficients are not constant, or 9282 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9283 /// bounds of the range. 9284 static Optional<APInt> 9285 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9286 const ConstantRange &Range, ScalarEvolution &SE) { 9287 assert(AddRec->getOperand(0)->isZero() && 9288 "Starting value of addrec should be 0"); 9289 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9290 << Range << ", addrec " << *AddRec << '\n'); 9291 // This case is handled in getNumIterationsInRange. Here we can assume that 9292 // we start in the range. 9293 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9294 "Addrec's initial value should be in range"); 9295 9296 APInt A, B, C, M; 9297 unsigned BitWidth; 9298 auto T = GetQuadraticEquation(AddRec); 9299 if (!T.hasValue()) 9300 return None; 9301 9302 // Be careful about the return value: there can be two reasons for not 9303 // returning an actual number. First, if no solutions to the equations 9304 // were found, and second, if the solutions don't leave the given range. 9305 // The first case means that the actual solution is "unknown", the second 9306 // means that it's known, but not valid. If the solution is unknown, we 9307 // cannot make any conclusions. 9308 // Return a pair: the optional solution and a flag indicating if the 9309 // solution was found. 9310 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9311 // Solve for signed overflow and unsigned overflow, pick the lower 9312 // solution. 9313 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9314 << Bound << " (before multiplying by " << M << ")\n"); 9315 Bound *= M; // The quadratic equation multiplier. 9316 9317 Optional<APInt> SO = None; 9318 if (BitWidth > 1) { 9319 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9320 "signed overflow\n"); 9321 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9322 } 9323 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9324 "unsigned overflow\n"); 9325 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9326 BitWidth+1); 9327 9328 auto LeavesRange = [&] (const APInt &X) { 9329 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9330 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9331 if (Range.contains(V0->getValue())) 9332 return false; 9333 // X should be at least 1, so X-1 is non-negative. 9334 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9335 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9336 if (Range.contains(V1->getValue())) 9337 return true; 9338 return false; 9339 }; 9340 9341 // If SolveQuadraticEquationWrap returns None, it means that there can 9342 // be a solution, but the function failed to find it. We cannot treat it 9343 // as "no solution". 9344 if (!SO.hasValue() || !UO.hasValue()) 9345 return { None, false }; 9346 9347 // Check the smaller value first to see if it leaves the range. 9348 // At this point, both SO and UO must have values. 9349 Optional<APInt> Min = MinOptional(SO, UO); 9350 if (LeavesRange(*Min)) 9351 return { Min, true }; 9352 Optional<APInt> Max = Min == SO ? UO : SO; 9353 if (LeavesRange(*Max)) 9354 return { Max, true }; 9355 9356 // Solutions were found, but were eliminated, hence the "true". 9357 return { None, true }; 9358 }; 9359 9360 std::tie(A, B, C, M, BitWidth) = *T; 9361 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9362 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9363 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9364 auto SL = SolveForBoundary(Lower); 9365 auto SU = SolveForBoundary(Upper); 9366 // If any of the solutions was unknown, no meaninigful conclusions can 9367 // be made. 9368 if (!SL.second || !SU.second) 9369 return None; 9370 9371 // Claim: The correct solution is not some value between Min and Max. 9372 // 9373 // Justification: Assuming that Min and Max are different values, one of 9374 // them is when the first signed overflow happens, the other is when the 9375 // first unsigned overflow happens. Crossing the range boundary is only 9376 // possible via an overflow (treating 0 as a special case of it, modeling 9377 // an overflow as crossing k*2^W for some k). 9378 // 9379 // The interesting case here is when Min was eliminated as an invalid 9380 // solution, but Max was not. The argument is that if there was another 9381 // overflow between Min and Max, it would also have been eliminated if 9382 // it was considered. 9383 // 9384 // For a given boundary, it is possible to have two overflows of the same 9385 // type (signed/unsigned) without having the other type in between: this 9386 // can happen when the vertex of the parabola is between the iterations 9387 // corresponding to the overflows. This is only possible when the two 9388 // overflows cross k*2^W for the same k. In such case, if the second one 9389 // left the range (and was the first one to do so), the first overflow 9390 // would have to enter the range, which would mean that either we had left 9391 // the range before or that we started outside of it. Both of these cases 9392 // are contradictions. 9393 // 9394 // Claim: In the case where SolveForBoundary returns None, the correct 9395 // solution is not some value between the Max for this boundary and the 9396 // Min of the other boundary. 9397 // 9398 // Justification: Assume that we had such Max_A and Min_B corresponding 9399 // to range boundaries A and B and such that Max_A < Min_B. If there was 9400 // a solution between Max_A and Min_B, it would have to be caused by an 9401 // overflow corresponding to either A or B. It cannot correspond to B, 9402 // since Min_B is the first occurrence of such an overflow. If it 9403 // corresponded to A, it would have to be either a signed or an unsigned 9404 // overflow that is larger than both eliminated overflows for A. But 9405 // between the eliminated overflows and this overflow, the values would 9406 // cover the entire value space, thus crossing the other boundary, which 9407 // is a contradiction. 9408 9409 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9410 } 9411 9412 ScalarEvolution::ExitLimit 9413 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9414 bool AllowPredicates) { 9415 9416 // This is only used for loops with a "x != y" exit test. The exit condition 9417 // is now expressed as a single expression, V = x-y. So the exit test is 9418 // effectively V != 0. We know and take advantage of the fact that this 9419 // expression only being used in a comparison by zero context. 9420 9421 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9422 // If the value is a constant 9423 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9424 // If the value is already zero, the branch will execute zero times. 9425 if (C->getValue()->isZero()) return C; 9426 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9427 } 9428 9429 const SCEVAddRecExpr *AddRec = 9430 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9431 9432 if (!AddRec && AllowPredicates) 9433 // Try to make this an AddRec using runtime tests, in the first X 9434 // iterations of this loop, where X is the SCEV expression found by the 9435 // algorithm below. 9436 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9437 9438 if (!AddRec || AddRec->getLoop() != L) 9439 return getCouldNotCompute(); 9440 9441 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9442 // the quadratic equation to solve it. 9443 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9444 // We can only use this value if the chrec ends up with an exact zero 9445 // value at this index. When solving for "X*X != 5", for example, we 9446 // should not accept a root of 2. 9447 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9448 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9449 return ExitLimit(R, R, false, Predicates); 9450 } 9451 return getCouldNotCompute(); 9452 } 9453 9454 // Otherwise we can only handle this if it is affine. 9455 if (!AddRec->isAffine()) 9456 return getCouldNotCompute(); 9457 9458 // If this is an affine expression, the execution count of this branch is 9459 // the minimum unsigned root of the following equation: 9460 // 9461 // Start + Step*N = 0 (mod 2^BW) 9462 // 9463 // equivalent to: 9464 // 9465 // Step*N = -Start (mod 2^BW) 9466 // 9467 // where BW is the common bit width of Start and Step. 9468 9469 // Get the initial value for the loop. 9470 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9471 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9472 9473 // For now we handle only constant steps. 9474 // 9475 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9476 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9477 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9478 // We have not yet seen any such cases. 9479 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9480 if (!StepC || StepC->getValue()->isZero()) 9481 return getCouldNotCompute(); 9482 9483 // For positive steps (counting up until unsigned overflow): 9484 // N = -Start/Step (as unsigned) 9485 // For negative steps (counting down to zero): 9486 // N = Start/-Step 9487 // First compute the unsigned distance from zero in the direction of Step. 9488 bool CountDown = StepC->getAPInt().isNegative(); 9489 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9490 9491 // Handle unitary steps, which cannot wraparound. 9492 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9493 // N = Distance (as unsigned) 9494 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9495 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9496 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9497 if (MaxBECountBase.ult(MaxBECount)) 9498 MaxBECount = MaxBECountBase; 9499 9500 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9501 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9502 // case, and see if we can improve the bound. 9503 // 9504 // Explicitly handling this here is necessary because getUnsignedRange 9505 // isn't context-sensitive; it doesn't know that we only care about the 9506 // range inside the loop. 9507 const SCEV *Zero = getZero(Distance->getType()); 9508 const SCEV *One = getOne(Distance->getType()); 9509 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9510 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9511 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9512 // as "unsigned_max(Distance + 1) - 1". 9513 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9514 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9515 } 9516 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9517 } 9518 9519 // If the condition controls loop exit (the loop exits only if the expression 9520 // is true) and the addition is no-wrap we can use unsigned divide to 9521 // compute the backedge count. In this case, the step may not divide the 9522 // distance, but we don't care because if the condition is "missed" the loop 9523 // will have undefined behavior due to wrapping. 9524 if (ControlsExit && AddRec->hasNoSelfWrap() && 9525 loopHasNoAbnormalExits(AddRec->getLoop())) { 9526 const SCEV *Exact = 9527 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9528 const SCEV *Max = getCouldNotCompute(); 9529 if (Exact != getCouldNotCompute()) { 9530 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9531 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9532 if (BaseMaxInt.ult(MaxInt)) 9533 Max = getConstant(BaseMaxInt); 9534 else 9535 Max = getConstant(MaxInt); 9536 } 9537 return ExitLimit(Exact, Max, false, Predicates); 9538 } 9539 9540 // Solve the general equation. 9541 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9542 getNegativeSCEV(Start), *this); 9543 const SCEV *M = E == getCouldNotCompute() 9544 ? E 9545 : getConstant(getUnsignedRangeMax(E)); 9546 return ExitLimit(E, M, false, Predicates); 9547 } 9548 9549 ScalarEvolution::ExitLimit 9550 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9551 // Loops that look like: while (X == 0) are very strange indeed. We don't 9552 // handle them yet except for the trivial case. This could be expanded in the 9553 // future as needed. 9554 9555 // If the value is a constant, check to see if it is known to be non-zero 9556 // already. If so, the backedge will execute zero times. 9557 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9558 if (!C->getValue()->isZero()) 9559 return getZero(C->getType()); 9560 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9561 } 9562 9563 // We could implement others, but I really doubt anyone writes loops like 9564 // this, and if they did, they would already be constant folded. 9565 return getCouldNotCompute(); 9566 } 9567 9568 std::pair<const BasicBlock *, const BasicBlock *> 9569 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9570 const { 9571 // If the block has a unique predecessor, then there is no path from the 9572 // predecessor to the block that does not go through the direct edge 9573 // from the predecessor to the block. 9574 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9575 return {Pred, BB}; 9576 9577 // A loop's header is defined to be a block that dominates the loop. 9578 // If the header has a unique predecessor outside the loop, it must be 9579 // a block that has exactly one successor that can reach the loop. 9580 if (const Loop *L = LI.getLoopFor(BB)) 9581 return {L->getLoopPredecessor(), L->getHeader()}; 9582 9583 return {nullptr, nullptr}; 9584 } 9585 9586 /// SCEV structural equivalence is usually sufficient for testing whether two 9587 /// expressions are equal, however for the purposes of looking for a condition 9588 /// guarding a loop, it can be useful to be a little more general, since a 9589 /// front-end may have replicated the controlling expression. 9590 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9591 // Quick check to see if they are the same SCEV. 9592 if (A == B) return true; 9593 9594 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9595 // Not all instructions that are "identical" compute the same value. For 9596 // instance, two distinct alloca instructions allocating the same type are 9597 // identical and do not read memory; but compute distinct values. 9598 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9599 }; 9600 9601 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9602 // two different instructions with the same value. Check for this case. 9603 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9604 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9605 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9606 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9607 if (ComputesEqualValues(AI, BI)) 9608 return true; 9609 9610 // Otherwise assume they may have a different value. 9611 return false; 9612 } 9613 9614 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9615 const SCEV *&LHS, const SCEV *&RHS, 9616 unsigned Depth) { 9617 bool Changed = false; 9618 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9619 // '0 != 0'. 9620 auto TrivialCase = [&](bool TriviallyTrue) { 9621 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9622 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9623 return true; 9624 }; 9625 // If we hit the max recursion limit bail out. 9626 if (Depth >= 3) 9627 return false; 9628 9629 // Canonicalize a constant to the right side. 9630 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9631 // Check for both operands constant. 9632 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9633 if (ConstantExpr::getICmp(Pred, 9634 LHSC->getValue(), 9635 RHSC->getValue())->isNullValue()) 9636 return TrivialCase(false); 9637 else 9638 return TrivialCase(true); 9639 } 9640 // Otherwise swap the operands to put the constant on the right. 9641 std::swap(LHS, RHS); 9642 Pred = ICmpInst::getSwappedPredicate(Pred); 9643 Changed = true; 9644 } 9645 9646 // If we're comparing an addrec with a value which is loop-invariant in the 9647 // addrec's loop, put the addrec on the left. Also make a dominance check, 9648 // as both operands could be addrecs loop-invariant in each other's loop. 9649 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9650 const Loop *L = AR->getLoop(); 9651 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9652 std::swap(LHS, RHS); 9653 Pred = ICmpInst::getSwappedPredicate(Pred); 9654 Changed = true; 9655 } 9656 } 9657 9658 // If there's a constant operand, canonicalize comparisons with boundary 9659 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9660 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9661 const APInt &RA = RC->getAPInt(); 9662 9663 bool SimplifiedByConstantRange = false; 9664 9665 if (!ICmpInst::isEquality(Pred)) { 9666 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9667 if (ExactCR.isFullSet()) 9668 return TrivialCase(true); 9669 else if (ExactCR.isEmptySet()) 9670 return TrivialCase(false); 9671 9672 APInt NewRHS; 9673 CmpInst::Predicate NewPred; 9674 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9675 ICmpInst::isEquality(NewPred)) { 9676 // We were able to convert an inequality to an equality. 9677 Pred = NewPred; 9678 RHS = getConstant(NewRHS); 9679 Changed = SimplifiedByConstantRange = true; 9680 } 9681 } 9682 9683 if (!SimplifiedByConstantRange) { 9684 switch (Pred) { 9685 default: 9686 break; 9687 case ICmpInst::ICMP_EQ: 9688 case ICmpInst::ICMP_NE: 9689 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9690 if (!RA) 9691 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9692 if (const SCEVMulExpr *ME = 9693 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9694 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9695 ME->getOperand(0)->isAllOnesValue()) { 9696 RHS = AE->getOperand(1); 9697 LHS = ME->getOperand(1); 9698 Changed = true; 9699 } 9700 break; 9701 9702 9703 // The "Should have been caught earlier!" messages refer to the fact 9704 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9705 // should have fired on the corresponding cases, and canonicalized the 9706 // check to trivial case. 9707 9708 case ICmpInst::ICMP_UGE: 9709 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9710 Pred = ICmpInst::ICMP_UGT; 9711 RHS = getConstant(RA - 1); 9712 Changed = true; 9713 break; 9714 case ICmpInst::ICMP_ULE: 9715 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9716 Pred = ICmpInst::ICMP_ULT; 9717 RHS = getConstant(RA + 1); 9718 Changed = true; 9719 break; 9720 case ICmpInst::ICMP_SGE: 9721 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9722 Pred = ICmpInst::ICMP_SGT; 9723 RHS = getConstant(RA - 1); 9724 Changed = true; 9725 break; 9726 case ICmpInst::ICMP_SLE: 9727 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9728 Pred = ICmpInst::ICMP_SLT; 9729 RHS = getConstant(RA + 1); 9730 Changed = true; 9731 break; 9732 } 9733 } 9734 } 9735 9736 // Check for obvious equality. 9737 if (HasSameValue(LHS, RHS)) { 9738 if (ICmpInst::isTrueWhenEqual(Pred)) 9739 return TrivialCase(true); 9740 if (ICmpInst::isFalseWhenEqual(Pred)) 9741 return TrivialCase(false); 9742 } 9743 9744 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9745 // adding or subtracting 1 from one of the operands. 9746 switch (Pred) { 9747 case ICmpInst::ICMP_SLE: 9748 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9749 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9750 SCEV::FlagNSW); 9751 Pred = ICmpInst::ICMP_SLT; 9752 Changed = true; 9753 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9754 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9755 SCEV::FlagNSW); 9756 Pred = ICmpInst::ICMP_SLT; 9757 Changed = true; 9758 } 9759 break; 9760 case ICmpInst::ICMP_SGE: 9761 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9762 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9763 SCEV::FlagNSW); 9764 Pred = ICmpInst::ICMP_SGT; 9765 Changed = true; 9766 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9767 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9768 SCEV::FlagNSW); 9769 Pred = ICmpInst::ICMP_SGT; 9770 Changed = true; 9771 } 9772 break; 9773 case ICmpInst::ICMP_ULE: 9774 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9775 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9776 SCEV::FlagNUW); 9777 Pred = ICmpInst::ICMP_ULT; 9778 Changed = true; 9779 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9780 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9781 Pred = ICmpInst::ICMP_ULT; 9782 Changed = true; 9783 } 9784 break; 9785 case ICmpInst::ICMP_UGE: 9786 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9787 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9788 Pred = ICmpInst::ICMP_UGT; 9789 Changed = true; 9790 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9791 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9792 SCEV::FlagNUW); 9793 Pred = ICmpInst::ICMP_UGT; 9794 Changed = true; 9795 } 9796 break; 9797 default: 9798 break; 9799 } 9800 9801 // TODO: More simplifications are possible here. 9802 9803 // Recursively simplify until we either hit a recursion limit or nothing 9804 // changes. 9805 if (Changed) 9806 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9807 9808 return Changed; 9809 } 9810 9811 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9812 return getSignedRangeMax(S).isNegative(); 9813 } 9814 9815 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9816 return getSignedRangeMin(S).isStrictlyPositive(); 9817 } 9818 9819 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9820 return !getSignedRangeMin(S).isNegative(); 9821 } 9822 9823 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9824 return !getSignedRangeMax(S).isStrictlyPositive(); 9825 } 9826 9827 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9828 return getUnsignedRangeMin(S) != 0; 9829 } 9830 9831 std::pair<const SCEV *, const SCEV *> 9832 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9833 // Compute SCEV on entry of loop L. 9834 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9835 if (Start == getCouldNotCompute()) 9836 return { Start, Start }; 9837 // Compute post increment SCEV for loop L. 9838 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9839 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9840 return { Start, PostInc }; 9841 } 9842 9843 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9844 const SCEV *LHS, const SCEV *RHS) { 9845 // First collect all loops. 9846 SmallPtrSet<const Loop *, 8> LoopsUsed; 9847 getUsedLoops(LHS, LoopsUsed); 9848 getUsedLoops(RHS, LoopsUsed); 9849 9850 if (LoopsUsed.empty()) 9851 return false; 9852 9853 // Domination relationship must be a linear order on collected loops. 9854 #ifndef NDEBUG 9855 for (auto *L1 : LoopsUsed) 9856 for (auto *L2 : LoopsUsed) 9857 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9858 DT.dominates(L2->getHeader(), L1->getHeader())) && 9859 "Domination relationship is not a linear order"); 9860 #endif 9861 9862 const Loop *MDL = 9863 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9864 [&](const Loop *L1, const Loop *L2) { 9865 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9866 }); 9867 9868 // Get init and post increment value for LHS. 9869 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9870 // if LHS contains unknown non-invariant SCEV then bail out. 9871 if (SplitLHS.first == getCouldNotCompute()) 9872 return false; 9873 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9874 // Get init and post increment value for RHS. 9875 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9876 // if RHS contains unknown non-invariant SCEV then bail out. 9877 if (SplitRHS.first == getCouldNotCompute()) 9878 return false; 9879 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9880 // It is possible that init SCEV contains an invariant load but it does 9881 // not dominate MDL and is not available at MDL loop entry, so we should 9882 // check it here. 9883 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9884 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9885 return false; 9886 9887 // It seems backedge guard check is faster than entry one so in some cases 9888 // it can speed up whole estimation by short circuit 9889 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9890 SplitRHS.second) && 9891 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9892 } 9893 9894 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9895 const SCEV *LHS, const SCEV *RHS) { 9896 // Canonicalize the inputs first. 9897 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9898 9899 if (isKnownViaInduction(Pred, LHS, RHS)) 9900 return true; 9901 9902 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9903 return true; 9904 9905 // Otherwise see what can be done with some simple reasoning. 9906 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9907 } 9908 9909 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9910 const SCEV *LHS, 9911 const SCEV *RHS) { 9912 if (isKnownPredicate(Pred, LHS, RHS)) 9913 return true; 9914 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9915 return false; 9916 return None; 9917 } 9918 9919 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9920 const SCEV *LHS, const SCEV *RHS, 9921 const Instruction *Context) { 9922 // TODO: Analyze guards and assumes from Context's block. 9923 return isKnownPredicate(Pred, LHS, RHS) || 9924 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9925 } 9926 9927 Optional<bool> 9928 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9929 const SCEV *RHS, 9930 const Instruction *Context) { 9931 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9932 if (KnownWithoutContext) 9933 return KnownWithoutContext; 9934 9935 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9936 return true; 9937 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9938 ICmpInst::getInversePredicate(Pred), 9939 LHS, RHS)) 9940 return false; 9941 return None; 9942 } 9943 9944 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9945 const SCEVAddRecExpr *LHS, 9946 const SCEV *RHS) { 9947 const Loop *L = LHS->getLoop(); 9948 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9949 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9950 } 9951 9952 Optional<ScalarEvolution::MonotonicPredicateType> 9953 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9954 ICmpInst::Predicate Pred) { 9955 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9956 9957 #ifndef NDEBUG 9958 // Verify an invariant: inverting the predicate should turn a monotonically 9959 // increasing change to a monotonically decreasing one, and vice versa. 9960 if (Result) { 9961 auto ResultSwapped = 9962 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9963 9964 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9965 assert(ResultSwapped.getValue() != Result.getValue() && 9966 "monotonicity should flip as we flip the predicate"); 9967 } 9968 #endif 9969 9970 return Result; 9971 } 9972 9973 Optional<ScalarEvolution::MonotonicPredicateType> 9974 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9975 ICmpInst::Predicate Pred) { 9976 // A zero step value for LHS means the induction variable is essentially a 9977 // loop invariant value. We don't really depend on the predicate actually 9978 // flipping from false to true (for increasing predicates, and the other way 9979 // around for decreasing predicates), all we care about is that *if* the 9980 // predicate changes then it only changes from false to true. 9981 // 9982 // A zero step value in itself is not very useful, but there may be places 9983 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9984 // as general as possible. 9985 9986 // Only handle LE/LT/GE/GT predicates. 9987 if (!ICmpInst::isRelational(Pred)) 9988 return None; 9989 9990 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9991 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9992 "Should be greater or less!"); 9993 9994 // Check that AR does not wrap. 9995 if (ICmpInst::isUnsigned(Pred)) { 9996 if (!LHS->hasNoUnsignedWrap()) 9997 return None; 9998 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9999 } else { 10000 assert(ICmpInst::isSigned(Pred) && 10001 "Relational predicate is either signed or unsigned!"); 10002 if (!LHS->hasNoSignedWrap()) 10003 return None; 10004 10005 const SCEV *Step = LHS->getStepRecurrence(*this); 10006 10007 if (isKnownNonNegative(Step)) 10008 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10009 10010 if (isKnownNonPositive(Step)) 10011 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10012 10013 return None; 10014 } 10015 } 10016 10017 Optional<ScalarEvolution::LoopInvariantPredicate> 10018 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10019 const SCEV *LHS, const SCEV *RHS, 10020 const Loop *L) { 10021 10022 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10023 if (!isLoopInvariant(RHS, L)) { 10024 if (!isLoopInvariant(LHS, L)) 10025 return None; 10026 10027 std::swap(LHS, RHS); 10028 Pred = ICmpInst::getSwappedPredicate(Pred); 10029 } 10030 10031 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10032 if (!ArLHS || ArLHS->getLoop() != L) 10033 return None; 10034 10035 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10036 if (!MonotonicType) 10037 return None; 10038 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10039 // true as the loop iterates, and the backedge is control dependent on 10040 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10041 // 10042 // * if the predicate was false in the first iteration then the predicate 10043 // is never evaluated again, since the loop exits without taking the 10044 // backedge. 10045 // * if the predicate was true in the first iteration then it will 10046 // continue to be true for all future iterations since it is 10047 // monotonically increasing. 10048 // 10049 // For both the above possibilities, we can replace the loop varying 10050 // predicate with its value on the first iteration of the loop (which is 10051 // loop invariant). 10052 // 10053 // A similar reasoning applies for a monotonically decreasing predicate, by 10054 // replacing true with false and false with true in the above two bullets. 10055 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10056 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10057 10058 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10059 return None; 10060 10061 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10062 } 10063 10064 Optional<ScalarEvolution::LoopInvariantPredicate> 10065 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10066 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10067 const Instruction *Context, const SCEV *MaxIter) { 10068 // Try to prove the following set of facts: 10069 // - The predicate is monotonic in the iteration space. 10070 // - If the check does not fail on the 1st iteration: 10071 // - No overflow will happen during first MaxIter iterations; 10072 // - It will not fail on the MaxIter'th iteration. 10073 // If the check does fail on the 1st iteration, we leave the loop and no 10074 // other checks matter. 10075 10076 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10077 if (!isLoopInvariant(RHS, L)) { 10078 if (!isLoopInvariant(LHS, L)) 10079 return None; 10080 10081 std::swap(LHS, RHS); 10082 Pred = ICmpInst::getSwappedPredicate(Pred); 10083 } 10084 10085 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10086 if (!AR || AR->getLoop() != L) 10087 return None; 10088 10089 // The predicate must be relational (i.e. <, <=, >=, >). 10090 if (!ICmpInst::isRelational(Pred)) 10091 return None; 10092 10093 // TODO: Support steps other than +/- 1. 10094 const SCEV *Step = AR->getStepRecurrence(*this); 10095 auto *One = getOne(Step->getType()); 10096 auto *MinusOne = getNegativeSCEV(One); 10097 if (Step != One && Step != MinusOne) 10098 return None; 10099 10100 // Type mismatch here means that MaxIter is potentially larger than max 10101 // unsigned value in start type, which mean we cannot prove no wrap for the 10102 // indvar. 10103 if (AR->getType() != MaxIter->getType()) 10104 return None; 10105 10106 // Value of IV on suggested last iteration. 10107 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10108 // Does it still meet the requirement? 10109 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10110 return None; 10111 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10112 // not exceed max unsigned value of this type), this effectively proves 10113 // that there is no wrap during the iteration. To prove that there is no 10114 // signed/unsigned wrap, we need to check that 10115 // Start <= Last for step = 1 or Start >= Last for step = -1. 10116 ICmpInst::Predicate NoOverflowPred = 10117 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10118 if (Step == MinusOne) 10119 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10120 const SCEV *Start = AR->getStart(); 10121 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 10122 return None; 10123 10124 // Everything is fine. 10125 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10126 } 10127 10128 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10129 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10130 if (HasSameValue(LHS, RHS)) 10131 return ICmpInst::isTrueWhenEqual(Pred); 10132 10133 // This code is split out from isKnownPredicate because it is called from 10134 // within isLoopEntryGuardedByCond. 10135 10136 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10137 const ConstantRange &RangeRHS) { 10138 return RangeLHS.icmp(Pred, RangeRHS); 10139 }; 10140 10141 // The check at the top of the function catches the case where the values are 10142 // known to be equal. 10143 if (Pred == CmpInst::ICMP_EQ) 10144 return false; 10145 10146 if (Pred == CmpInst::ICMP_NE) { 10147 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10148 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10149 return true; 10150 auto *Diff = getMinusSCEV(LHS, RHS); 10151 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10152 } 10153 10154 if (CmpInst::isSigned(Pred)) 10155 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10156 10157 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10158 } 10159 10160 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10161 const SCEV *LHS, 10162 const SCEV *RHS) { 10163 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10164 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10165 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10166 // OutC1 and OutC2. 10167 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10168 APInt &OutC1, APInt &OutC2, 10169 SCEV::NoWrapFlags ExpectedFlags) { 10170 const SCEV *XNonConstOp, *XConstOp; 10171 const SCEV *YNonConstOp, *YConstOp; 10172 SCEV::NoWrapFlags XFlagsPresent; 10173 SCEV::NoWrapFlags YFlagsPresent; 10174 10175 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10176 XConstOp = getZero(X->getType()); 10177 XNonConstOp = X; 10178 XFlagsPresent = ExpectedFlags; 10179 } 10180 if (!isa<SCEVConstant>(XConstOp) || 10181 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10182 return false; 10183 10184 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10185 YConstOp = getZero(Y->getType()); 10186 YNonConstOp = Y; 10187 YFlagsPresent = ExpectedFlags; 10188 } 10189 10190 if (!isa<SCEVConstant>(YConstOp) || 10191 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10192 return false; 10193 10194 if (YNonConstOp != XNonConstOp) 10195 return false; 10196 10197 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10198 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10199 10200 return true; 10201 }; 10202 10203 APInt C1; 10204 APInt C2; 10205 10206 switch (Pred) { 10207 default: 10208 break; 10209 10210 case ICmpInst::ICMP_SGE: 10211 std::swap(LHS, RHS); 10212 LLVM_FALLTHROUGH; 10213 case ICmpInst::ICMP_SLE: 10214 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10215 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10216 return true; 10217 10218 break; 10219 10220 case ICmpInst::ICMP_SGT: 10221 std::swap(LHS, RHS); 10222 LLVM_FALLTHROUGH; 10223 case ICmpInst::ICMP_SLT: 10224 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10225 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10226 return true; 10227 10228 break; 10229 10230 case ICmpInst::ICMP_UGE: 10231 std::swap(LHS, RHS); 10232 LLVM_FALLTHROUGH; 10233 case ICmpInst::ICMP_ULE: 10234 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10235 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10236 return true; 10237 10238 break; 10239 10240 case ICmpInst::ICMP_UGT: 10241 std::swap(LHS, RHS); 10242 LLVM_FALLTHROUGH; 10243 case ICmpInst::ICMP_ULT: 10244 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10245 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10246 return true; 10247 break; 10248 } 10249 10250 return false; 10251 } 10252 10253 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10254 const SCEV *LHS, 10255 const SCEV *RHS) { 10256 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10257 return false; 10258 10259 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10260 // the stack can result in exponential time complexity. 10261 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10262 10263 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10264 // 10265 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10266 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10267 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10268 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10269 // use isKnownPredicate later if needed. 10270 return isKnownNonNegative(RHS) && 10271 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10272 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10273 } 10274 10275 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10276 ICmpInst::Predicate Pred, 10277 const SCEV *LHS, const SCEV *RHS) { 10278 // No need to even try if we know the module has no guards. 10279 if (!HasGuards) 10280 return false; 10281 10282 return any_of(*BB, [&](const Instruction &I) { 10283 using namespace llvm::PatternMatch; 10284 10285 Value *Condition; 10286 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10287 m_Value(Condition))) && 10288 isImpliedCond(Pred, LHS, RHS, Condition, false); 10289 }); 10290 } 10291 10292 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10293 /// protected by a conditional between LHS and RHS. This is used to 10294 /// to eliminate casts. 10295 bool 10296 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10297 ICmpInst::Predicate Pred, 10298 const SCEV *LHS, const SCEV *RHS) { 10299 // Interpret a null as meaning no loop, where there is obviously no guard 10300 // (interprocedural conditions notwithstanding). 10301 if (!L) return true; 10302 10303 if (VerifyIR) 10304 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10305 "This cannot be done on broken IR!"); 10306 10307 10308 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10309 return true; 10310 10311 BasicBlock *Latch = L->getLoopLatch(); 10312 if (!Latch) 10313 return false; 10314 10315 BranchInst *LoopContinuePredicate = 10316 dyn_cast<BranchInst>(Latch->getTerminator()); 10317 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10318 isImpliedCond(Pred, LHS, RHS, 10319 LoopContinuePredicate->getCondition(), 10320 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10321 return true; 10322 10323 // We don't want more than one activation of the following loops on the stack 10324 // -- that can lead to O(n!) time complexity. 10325 if (WalkingBEDominatingConds) 10326 return false; 10327 10328 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10329 10330 // See if we can exploit a trip count to prove the predicate. 10331 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10332 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10333 if (LatchBECount != getCouldNotCompute()) { 10334 // We know that Latch branches back to the loop header exactly 10335 // LatchBECount times. This means the backdege condition at Latch is 10336 // equivalent to "{0,+,1} u< LatchBECount". 10337 Type *Ty = LatchBECount->getType(); 10338 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10339 const SCEV *LoopCounter = 10340 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10341 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10342 LatchBECount)) 10343 return true; 10344 } 10345 10346 // Check conditions due to any @llvm.assume intrinsics. 10347 for (auto &AssumeVH : AC.assumptions()) { 10348 if (!AssumeVH) 10349 continue; 10350 auto *CI = cast<CallInst>(AssumeVH); 10351 if (!DT.dominates(CI, Latch->getTerminator())) 10352 continue; 10353 10354 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10355 return true; 10356 } 10357 10358 // If the loop is not reachable from the entry block, we risk running into an 10359 // infinite loop as we walk up into the dom tree. These loops do not matter 10360 // anyway, so we just return a conservative answer when we see them. 10361 if (!DT.isReachableFromEntry(L->getHeader())) 10362 return false; 10363 10364 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10365 return true; 10366 10367 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10368 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10369 assert(DTN && "should reach the loop header before reaching the root!"); 10370 10371 BasicBlock *BB = DTN->getBlock(); 10372 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10373 return true; 10374 10375 BasicBlock *PBB = BB->getSinglePredecessor(); 10376 if (!PBB) 10377 continue; 10378 10379 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10380 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10381 continue; 10382 10383 Value *Condition = ContinuePredicate->getCondition(); 10384 10385 // If we have an edge `E` within the loop body that dominates the only 10386 // latch, the condition guarding `E` also guards the backedge. This 10387 // reasoning works only for loops with a single latch. 10388 10389 BasicBlockEdge DominatingEdge(PBB, BB); 10390 if (DominatingEdge.isSingleEdge()) { 10391 // We're constructively (and conservatively) enumerating edges within the 10392 // loop body that dominate the latch. The dominator tree better agree 10393 // with us on this: 10394 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10395 10396 if (isImpliedCond(Pred, LHS, RHS, Condition, 10397 BB != ContinuePredicate->getSuccessor(0))) 10398 return true; 10399 } 10400 } 10401 10402 return false; 10403 } 10404 10405 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10406 ICmpInst::Predicate Pred, 10407 const SCEV *LHS, 10408 const SCEV *RHS) { 10409 if (VerifyIR) 10410 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10411 "This cannot be done on broken IR!"); 10412 10413 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10414 // the facts (a >= b && a != b) separately. A typical situation is when the 10415 // non-strict comparison is known from ranges and non-equality is known from 10416 // dominating predicates. If we are proving strict comparison, we always try 10417 // to prove non-equality and non-strict comparison separately. 10418 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10419 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10420 bool ProvedNonStrictComparison = false; 10421 bool ProvedNonEquality = false; 10422 10423 auto SplitAndProve = 10424 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10425 if (!ProvedNonStrictComparison) 10426 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10427 if (!ProvedNonEquality) 10428 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10429 if (ProvedNonStrictComparison && ProvedNonEquality) 10430 return true; 10431 return false; 10432 }; 10433 10434 if (ProvingStrictComparison) { 10435 auto ProofFn = [&](ICmpInst::Predicate P) { 10436 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10437 }; 10438 if (SplitAndProve(ProofFn)) 10439 return true; 10440 } 10441 10442 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10443 auto ProveViaGuard = [&](const BasicBlock *Block) { 10444 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10445 return true; 10446 if (ProvingStrictComparison) { 10447 auto ProofFn = [&](ICmpInst::Predicate P) { 10448 return isImpliedViaGuard(Block, P, LHS, RHS); 10449 }; 10450 if (SplitAndProve(ProofFn)) 10451 return true; 10452 } 10453 return false; 10454 }; 10455 10456 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10457 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10458 const Instruction *Context = &BB->front(); 10459 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10460 return true; 10461 if (ProvingStrictComparison) { 10462 auto ProofFn = [&](ICmpInst::Predicate P) { 10463 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10464 }; 10465 if (SplitAndProve(ProofFn)) 10466 return true; 10467 } 10468 return false; 10469 }; 10470 10471 // Starting at the block's predecessor, climb up the predecessor chain, as long 10472 // as there are predecessors that can be found that have unique successors 10473 // leading to the original block. 10474 const Loop *ContainingLoop = LI.getLoopFor(BB); 10475 const BasicBlock *PredBB; 10476 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10477 PredBB = ContainingLoop->getLoopPredecessor(); 10478 else 10479 PredBB = BB->getSinglePredecessor(); 10480 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10481 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10482 if (ProveViaGuard(Pair.first)) 10483 return true; 10484 10485 const BranchInst *LoopEntryPredicate = 10486 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10487 if (!LoopEntryPredicate || 10488 LoopEntryPredicate->isUnconditional()) 10489 continue; 10490 10491 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10492 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10493 return true; 10494 } 10495 10496 // Check conditions due to any @llvm.assume intrinsics. 10497 for (auto &AssumeVH : AC.assumptions()) { 10498 if (!AssumeVH) 10499 continue; 10500 auto *CI = cast<CallInst>(AssumeVH); 10501 if (!DT.dominates(CI, BB)) 10502 continue; 10503 10504 if (ProveViaCond(CI->getArgOperand(0), false)) 10505 return true; 10506 } 10507 10508 return false; 10509 } 10510 10511 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10512 ICmpInst::Predicate Pred, 10513 const SCEV *LHS, 10514 const SCEV *RHS) { 10515 // Interpret a null as meaning no loop, where there is obviously no guard 10516 // (interprocedural conditions notwithstanding). 10517 if (!L) 10518 return false; 10519 10520 // Both LHS and RHS must be available at loop entry. 10521 assert(isAvailableAtLoopEntry(LHS, L) && 10522 "LHS is not available at Loop Entry"); 10523 assert(isAvailableAtLoopEntry(RHS, L) && 10524 "RHS is not available at Loop Entry"); 10525 10526 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10527 return true; 10528 10529 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10530 } 10531 10532 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10533 const SCEV *RHS, 10534 const Value *FoundCondValue, bool Inverse, 10535 const Instruction *Context) { 10536 // False conditions implies anything. Do not bother analyzing it further. 10537 if (FoundCondValue == 10538 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10539 return true; 10540 10541 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10542 return false; 10543 10544 auto ClearOnExit = 10545 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10546 10547 // Recursively handle And and Or conditions. 10548 const Value *Op0, *Op1; 10549 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10550 if (!Inverse) 10551 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10552 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10553 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10554 if (Inverse) 10555 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10556 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10557 } 10558 10559 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10560 if (!ICI) return false; 10561 10562 // Now that we found a conditional branch that dominates the loop or controls 10563 // the loop latch. Check to see if it is the comparison we are looking for. 10564 ICmpInst::Predicate FoundPred; 10565 if (Inverse) 10566 FoundPred = ICI->getInversePredicate(); 10567 else 10568 FoundPred = ICI->getPredicate(); 10569 10570 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10571 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10572 10573 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10574 } 10575 10576 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10577 const SCEV *RHS, 10578 ICmpInst::Predicate FoundPred, 10579 const SCEV *FoundLHS, const SCEV *FoundRHS, 10580 const Instruction *Context) { 10581 // Balance the types. 10582 if (getTypeSizeInBits(LHS->getType()) < 10583 getTypeSizeInBits(FoundLHS->getType())) { 10584 // For unsigned and equality predicates, try to prove that both found 10585 // operands fit into narrow unsigned range. If so, try to prove facts in 10586 // narrow types. 10587 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10588 auto *NarrowType = LHS->getType(); 10589 auto *WideType = FoundLHS->getType(); 10590 auto BitWidth = getTypeSizeInBits(NarrowType); 10591 const SCEV *MaxValue = getZeroExtendExpr( 10592 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10593 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10594 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10595 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10596 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10597 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10598 TruncFoundRHS, Context)) 10599 return true; 10600 } 10601 } 10602 10603 if (LHS->getType()->isPointerTy()) 10604 return false; 10605 if (CmpInst::isSigned(Pred)) { 10606 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10607 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10608 } else { 10609 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10610 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10611 } 10612 } else if (getTypeSizeInBits(LHS->getType()) > 10613 getTypeSizeInBits(FoundLHS->getType())) { 10614 if (FoundLHS->getType()->isPointerTy()) 10615 return false; 10616 if (CmpInst::isSigned(FoundPred)) { 10617 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10618 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10619 } else { 10620 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10621 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10622 } 10623 } 10624 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10625 FoundRHS, Context); 10626 } 10627 10628 bool ScalarEvolution::isImpliedCondBalancedTypes( 10629 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10630 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10631 const Instruction *Context) { 10632 assert(getTypeSizeInBits(LHS->getType()) == 10633 getTypeSizeInBits(FoundLHS->getType()) && 10634 "Types should be balanced!"); 10635 // Canonicalize the query to match the way instcombine will have 10636 // canonicalized the comparison. 10637 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10638 if (LHS == RHS) 10639 return CmpInst::isTrueWhenEqual(Pred); 10640 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10641 if (FoundLHS == FoundRHS) 10642 return CmpInst::isFalseWhenEqual(FoundPred); 10643 10644 // Check to see if we can make the LHS or RHS match. 10645 if (LHS == FoundRHS || RHS == FoundLHS) { 10646 if (isa<SCEVConstant>(RHS)) { 10647 std::swap(FoundLHS, FoundRHS); 10648 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10649 } else { 10650 std::swap(LHS, RHS); 10651 Pred = ICmpInst::getSwappedPredicate(Pred); 10652 } 10653 } 10654 10655 // Check whether the found predicate is the same as the desired predicate. 10656 if (FoundPred == Pred) 10657 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10658 10659 // Check whether swapping the found predicate makes it the same as the 10660 // desired predicate. 10661 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10662 // We can write the implication 10663 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10664 // using one of the following ways: 10665 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10666 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10667 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10668 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10669 // Forms 1. and 2. require swapping the operands of one condition. Don't 10670 // do this if it would break canonical constant/addrec ordering. 10671 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10672 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10673 Context); 10674 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10675 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10676 10677 // There's no clear preference between forms 3. and 4., try both. Avoid 10678 // forming getNotSCEV of pointer values as the resulting subtract is 10679 // not legal. 10680 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10681 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10682 FoundLHS, FoundRHS, Context)) 10683 return true; 10684 10685 if (!FoundLHS->getType()->isPointerTy() && 10686 !FoundRHS->getType()->isPointerTy() && 10687 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10688 getNotSCEV(FoundRHS), Context)) 10689 return true; 10690 10691 return false; 10692 } 10693 10694 // Unsigned comparison is the same as signed comparison when both the operands 10695 // are non-negative. 10696 if (CmpInst::isUnsigned(FoundPred) && 10697 CmpInst::getSignedPredicate(FoundPred) == Pred && 10698 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10699 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10700 10701 // Check if we can make progress by sharpening ranges. 10702 if (FoundPred == ICmpInst::ICMP_NE && 10703 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10704 10705 const SCEVConstant *C = nullptr; 10706 const SCEV *V = nullptr; 10707 10708 if (isa<SCEVConstant>(FoundLHS)) { 10709 C = cast<SCEVConstant>(FoundLHS); 10710 V = FoundRHS; 10711 } else { 10712 C = cast<SCEVConstant>(FoundRHS); 10713 V = FoundLHS; 10714 } 10715 10716 // The guarding predicate tells us that C != V. If the known range 10717 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10718 // range we consider has to correspond to same signedness as the 10719 // predicate we're interested in folding. 10720 10721 APInt Min = ICmpInst::isSigned(Pred) ? 10722 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10723 10724 if (Min == C->getAPInt()) { 10725 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10726 // This is true even if (Min + 1) wraps around -- in case of 10727 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10728 10729 APInt SharperMin = Min + 1; 10730 10731 switch (Pred) { 10732 case ICmpInst::ICMP_SGE: 10733 case ICmpInst::ICMP_UGE: 10734 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10735 // RHS, we're done. 10736 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10737 Context)) 10738 return true; 10739 LLVM_FALLTHROUGH; 10740 10741 case ICmpInst::ICMP_SGT: 10742 case ICmpInst::ICMP_UGT: 10743 // We know from the range information that (V `Pred` Min || 10744 // V == Min). We know from the guarding condition that !(V 10745 // == Min). This gives us 10746 // 10747 // V `Pred` Min || V == Min && !(V == Min) 10748 // => V `Pred` Min 10749 // 10750 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10751 10752 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10753 Context)) 10754 return true; 10755 break; 10756 10757 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10758 case ICmpInst::ICMP_SLE: 10759 case ICmpInst::ICMP_ULE: 10760 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10761 LHS, V, getConstant(SharperMin), Context)) 10762 return true; 10763 LLVM_FALLTHROUGH; 10764 10765 case ICmpInst::ICMP_SLT: 10766 case ICmpInst::ICMP_ULT: 10767 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10768 LHS, V, getConstant(Min), Context)) 10769 return true; 10770 break; 10771 10772 default: 10773 // No change 10774 break; 10775 } 10776 } 10777 } 10778 10779 // Check whether the actual condition is beyond sufficient. 10780 if (FoundPred == ICmpInst::ICMP_EQ) 10781 if (ICmpInst::isTrueWhenEqual(Pred)) 10782 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10783 return true; 10784 if (Pred == ICmpInst::ICMP_NE) 10785 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10786 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10787 Context)) 10788 return true; 10789 10790 // Otherwise assume the worst. 10791 return false; 10792 } 10793 10794 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10795 const SCEV *&L, const SCEV *&R, 10796 SCEV::NoWrapFlags &Flags) { 10797 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10798 if (!AE || AE->getNumOperands() != 2) 10799 return false; 10800 10801 L = AE->getOperand(0); 10802 R = AE->getOperand(1); 10803 Flags = AE->getNoWrapFlags(); 10804 return true; 10805 } 10806 10807 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10808 const SCEV *Less) { 10809 // We avoid subtracting expressions here because this function is usually 10810 // fairly deep in the call stack (i.e. is called many times). 10811 10812 // X - X = 0. 10813 if (More == Less) 10814 return APInt(getTypeSizeInBits(More->getType()), 0); 10815 10816 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10817 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10818 const auto *MAR = cast<SCEVAddRecExpr>(More); 10819 10820 if (LAR->getLoop() != MAR->getLoop()) 10821 return None; 10822 10823 // We look at affine expressions only; not for correctness but to keep 10824 // getStepRecurrence cheap. 10825 if (!LAR->isAffine() || !MAR->isAffine()) 10826 return None; 10827 10828 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10829 return None; 10830 10831 Less = LAR->getStart(); 10832 More = MAR->getStart(); 10833 10834 // fall through 10835 } 10836 10837 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10838 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10839 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10840 return M - L; 10841 } 10842 10843 SCEV::NoWrapFlags Flags; 10844 const SCEV *LLess = nullptr, *RLess = nullptr; 10845 const SCEV *LMore = nullptr, *RMore = nullptr; 10846 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10847 // Compare (X + C1) vs X. 10848 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10849 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10850 if (RLess == More) 10851 return -(C1->getAPInt()); 10852 10853 // Compare X vs (X + C2). 10854 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10855 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10856 if (RMore == Less) 10857 return C2->getAPInt(); 10858 10859 // Compare (X + C1) vs (X + C2). 10860 if (C1 && C2 && RLess == RMore) 10861 return C2->getAPInt() - C1->getAPInt(); 10862 10863 return None; 10864 } 10865 10866 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10867 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10868 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10869 // Try to recognize the following pattern: 10870 // 10871 // FoundRHS = ... 10872 // ... 10873 // loop: 10874 // FoundLHS = {Start,+,W} 10875 // context_bb: // Basic block from the same loop 10876 // known(Pred, FoundLHS, FoundRHS) 10877 // 10878 // If some predicate is known in the context of a loop, it is also known on 10879 // each iteration of this loop, including the first iteration. Therefore, in 10880 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10881 // prove the original pred using this fact. 10882 if (!Context) 10883 return false; 10884 const BasicBlock *ContextBB = Context->getParent(); 10885 // Make sure AR varies in the context block. 10886 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10887 const Loop *L = AR->getLoop(); 10888 // Make sure that context belongs to the loop and executes on 1st iteration 10889 // (if it ever executes at all). 10890 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10891 return false; 10892 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10893 return false; 10894 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10895 } 10896 10897 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10898 const Loop *L = AR->getLoop(); 10899 // Make sure that context belongs to the loop and executes on 1st iteration 10900 // (if it ever executes at all). 10901 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10902 return false; 10903 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10904 return false; 10905 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10906 } 10907 10908 return false; 10909 } 10910 10911 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10912 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10913 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10914 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10915 return false; 10916 10917 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10918 if (!AddRecLHS) 10919 return false; 10920 10921 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10922 if (!AddRecFoundLHS) 10923 return false; 10924 10925 // We'd like to let SCEV reason about control dependencies, so we constrain 10926 // both the inequalities to be about add recurrences on the same loop. This 10927 // way we can use isLoopEntryGuardedByCond later. 10928 10929 const Loop *L = AddRecFoundLHS->getLoop(); 10930 if (L != AddRecLHS->getLoop()) 10931 return false; 10932 10933 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10934 // 10935 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10936 // ... (2) 10937 // 10938 // Informal proof for (2), assuming (1) [*]: 10939 // 10940 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10941 // 10942 // Then 10943 // 10944 // FoundLHS s< FoundRHS s< INT_MIN - C 10945 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10946 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10947 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10948 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10949 // <=> FoundLHS + C s< FoundRHS + C 10950 // 10951 // [*]: (1) can be proved by ruling out overflow. 10952 // 10953 // [**]: This can be proved by analyzing all the four possibilities: 10954 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10955 // (A s>= 0, B s>= 0). 10956 // 10957 // Note: 10958 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10959 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10960 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10961 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10962 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10963 // C)". 10964 10965 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10966 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10967 if (!LDiff || !RDiff || *LDiff != *RDiff) 10968 return false; 10969 10970 if (LDiff->isMinValue()) 10971 return true; 10972 10973 APInt FoundRHSLimit; 10974 10975 if (Pred == CmpInst::ICMP_ULT) { 10976 FoundRHSLimit = -(*RDiff); 10977 } else { 10978 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10979 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10980 } 10981 10982 // Try to prove (1) or (2), as needed. 10983 return isAvailableAtLoopEntry(FoundRHS, L) && 10984 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10985 getConstant(FoundRHSLimit)); 10986 } 10987 10988 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10989 const SCEV *LHS, const SCEV *RHS, 10990 const SCEV *FoundLHS, 10991 const SCEV *FoundRHS, unsigned Depth) { 10992 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10993 10994 auto ClearOnExit = make_scope_exit([&]() { 10995 if (LPhi) { 10996 bool Erased = PendingMerges.erase(LPhi); 10997 assert(Erased && "Failed to erase LPhi!"); 10998 (void)Erased; 10999 } 11000 if (RPhi) { 11001 bool Erased = PendingMerges.erase(RPhi); 11002 assert(Erased && "Failed to erase RPhi!"); 11003 (void)Erased; 11004 } 11005 }); 11006 11007 // Find respective Phis and check that they are not being pending. 11008 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11009 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11010 if (!PendingMerges.insert(Phi).second) 11011 return false; 11012 LPhi = Phi; 11013 } 11014 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11015 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11016 // If we detect a loop of Phi nodes being processed by this method, for 11017 // example: 11018 // 11019 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11020 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11021 // 11022 // we don't want to deal with a case that complex, so return conservative 11023 // answer false. 11024 if (!PendingMerges.insert(Phi).second) 11025 return false; 11026 RPhi = Phi; 11027 } 11028 11029 // If none of LHS, RHS is a Phi, nothing to do here. 11030 if (!LPhi && !RPhi) 11031 return false; 11032 11033 // If there is a SCEVUnknown Phi we are interested in, make it left. 11034 if (!LPhi) { 11035 std::swap(LHS, RHS); 11036 std::swap(FoundLHS, FoundRHS); 11037 std::swap(LPhi, RPhi); 11038 Pred = ICmpInst::getSwappedPredicate(Pred); 11039 } 11040 11041 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11042 const BasicBlock *LBB = LPhi->getParent(); 11043 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11044 11045 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11046 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11047 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11048 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11049 }; 11050 11051 if (RPhi && RPhi->getParent() == LBB) { 11052 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11053 // If we compare two Phis from the same block, and for each entry block 11054 // the predicate is true for incoming values from this block, then the 11055 // predicate is also true for the Phis. 11056 for (const BasicBlock *IncBB : predecessors(LBB)) { 11057 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11058 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11059 if (!ProvedEasily(L, R)) 11060 return false; 11061 } 11062 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11063 // Case two: RHS is also a Phi from the same basic block, and it is an 11064 // AddRec. It means that there is a loop which has both AddRec and Unknown 11065 // PHIs, for it we can compare incoming values of AddRec from above the loop 11066 // and latch with their respective incoming values of LPhi. 11067 // TODO: Generalize to handle loops with many inputs in a header. 11068 if (LPhi->getNumIncomingValues() != 2) return false; 11069 11070 auto *RLoop = RAR->getLoop(); 11071 auto *Predecessor = RLoop->getLoopPredecessor(); 11072 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11073 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11074 if (!ProvedEasily(L1, RAR->getStart())) 11075 return false; 11076 auto *Latch = RLoop->getLoopLatch(); 11077 assert(Latch && "Loop with AddRec with no latch?"); 11078 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11079 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11080 return false; 11081 } else { 11082 // In all other cases go over inputs of LHS and compare each of them to RHS, 11083 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11084 // At this point RHS is either a non-Phi, or it is a Phi from some block 11085 // different from LBB. 11086 for (const BasicBlock *IncBB : predecessors(LBB)) { 11087 // Check that RHS is available in this block. 11088 if (!dominates(RHS, IncBB)) 11089 return false; 11090 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11091 // Make sure L does not refer to a value from a potentially previous 11092 // iteration of a loop. 11093 if (!properlyDominates(L, IncBB)) 11094 return false; 11095 if (!ProvedEasily(L, RHS)) 11096 return false; 11097 } 11098 } 11099 return true; 11100 } 11101 11102 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11103 const SCEV *LHS, const SCEV *RHS, 11104 const SCEV *FoundLHS, 11105 const SCEV *FoundRHS, 11106 const Instruction *Context) { 11107 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11108 return true; 11109 11110 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11111 return true; 11112 11113 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11114 Context)) 11115 return true; 11116 11117 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11118 FoundLHS, FoundRHS); 11119 } 11120 11121 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11122 template <typename MinMaxExprType> 11123 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11124 const SCEV *Candidate) { 11125 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11126 if (!MinMaxExpr) 11127 return false; 11128 11129 return is_contained(MinMaxExpr->operands(), Candidate); 11130 } 11131 11132 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11133 ICmpInst::Predicate Pred, 11134 const SCEV *LHS, const SCEV *RHS) { 11135 // If both sides are affine addrecs for the same loop, with equal 11136 // steps, and we know the recurrences don't wrap, then we only 11137 // need to check the predicate on the starting values. 11138 11139 if (!ICmpInst::isRelational(Pred)) 11140 return false; 11141 11142 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11143 if (!LAR) 11144 return false; 11145 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11146 if (!RAR) 11147 return false; 11148 if (LAR->getLoop() != RAR->getLoop()) 11149 return false; 11150 if (!LAR->isAffine() || !RAR->isAffine()) 11151 return false; 11152 11153 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11154 return false; 11155 11156 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11157 SCEV::FlagNSW : SCEV::FlagNUW; 11158 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11159 return false; 11160 11161 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11162 } 11163 11164 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11165 /// expression? 11166 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11167 ICmpInst::Predicate Pred, 11168 const SCEV *LHS, const SCEV *RHS) { 11169 switch (Pred) { 11170 default: 11171 return false; 11172 11173 case ICmpInst::ICMP_SGE: 11174 std::swap(LHS, RHS); 11175 LLVM_FALLTHROUGH; 11176 case ICmpInst::ICMP_SLE: 11177 return 11178 // min(A, ...) <= A 11179 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11180 // A <= max(A, ...) 11181 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11182 11183 case ICmpInst::ICMP_UGE: 11184 std::swap(LHS, RHS); 11185 LLVM_FALLTHROUGH; 11186 case ICmpInst::ICMP_ULE: 11187 return 11188 // min(A, ...) <= A 11189 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11190 // A <= max(A, ...) 11191 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11192 } 11193 11194 llvm_unreachable("covered switch fell through?!"); 11195 } 11196 11197 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11198 const SCEV *LHS, const SCEV *RHS, 11199 const SCEV *FoundLHS, 11200 const SCEV *FoundRHS, 11201 unsigned Depth) { 11202 assert(getTypeSizeInBits(LHS->getType()) == 11203 getTypeSizeInBits(RHS->getType()) && 11204 "LHS and RHS have different sizes?"); 11205 assert(getTypeSizeInBits(FoundLHS->getType()) == 11206 getTypeSizeInBits(FoundRHS->getType()) && 11207 "FoundLHS and FoundRHS have different sizes?"); 11208 // We want to avoid hurting the compile time with analysis of too big trees. 11209 if (Depth > MaxSCEVOperationsImplicationDepth) 11210 return false; 11211 11212 // We only want to work with GT comparison so far. 11213 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11214 Pred = CmpInst::getSwappedPredicate(Pred); 11215 std::swap(LHS, RHS); 11216 std::swap(FoundLHS, FoundRHS); 11217 } 11218 11219 // For unsigned, try to reduce it to corresponding signed comparison. 11220 if (Pred == ICmpInst::ICMP_UGT) 11221 // We can replace unsigned predicate with its signed counterpart if all 11222 // involved values are non-negative. 11223 // TODO: We could have better support for unsigned. 11224 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11225 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11226 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11227 // use this fact to prove that LHS and RHS are non-negative. 11228 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11229 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11230 FoundRHS) && 11231 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11232 FoundRHS)) 11233 Pred = ICmpInst::ICMP_SGT; 11234 } 11235 11236 if (Pred != ICmpInst::ICMP_SGT) 11237 return false; 11238 11239 auto GetOpFromSExt = [&](const SCEV *S) { 11240 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11241 return Ext->getOperand(); 11242 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11243 // the constant in some cases. 11244 return S; 11245 }; 11246 11247 // Acquire values from extensions. 11248 auto *OrigLHS = LHS; 11249 auto *OrigFoundLHS = FoundLHS; 11250 LHS = GetOpFromSExt(LHS); 11251 FoundLHS = GetOpFromSExt(FoundLHS); 11252 11253 // Is the SGT predicate can be proved trivially or using the found context. 11254 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11255 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11256 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11257 FoundRHS, Depth + 1); 11258 }; 11259 11260 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11261 // We want to avoid creation of any new non-constant SCEV. Since we are 11262 // going to compare the operands to RHS, we should be certain that we don't 11263 // need any size extensions for this. So let's decline all cases when the 11264 // sizes of types of LHS and RHS do not match. 11265 // TODO: Maybe try to get RHS from sext to catch more cases? 11266 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11267 return false; 11268 11269 // Should not overflow. 11270 if (!LHSAddExpr->hasNoSignedWrap()) 11271 return false; 11272 11273 auto *LL = LHSAddExpr->getOperand(0); 11274 auto *LR = LHSAddExpr->getOperand(1); 11275 auto *MinusOne = getMinusOne(RHS->getType()); 11276 11277 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11278 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11279 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11280 }; 11281 // Try to prove the following rule: 11282 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11283 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11284 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11285 return true; 11286 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11287 Value *LL, *LR; 11288 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11289 11290 using namespace llvm::PatternMatch; 11291 11292 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11293 // Rules for division. 11294 // We are going to perform some comparisons with Denominator and its 11295 // derivative expressions. In general case, creating a SCEV for it may 11296 // lead to a complex analysis of the entire graph, and in particular it 11297 // can request trip count recalculation for the same loop. This would 11298 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11299 // this, we only want to create SCEVs that are constants in this section. 11300 // So we bail if Denominator is not a constant. 11301 if (!isa<ConstantInt>(LR)) 11302 return false; 11303 11304 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11305 11306 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11307 // then a SCEV for the numerator already exists and matches with FoundLHS. 11308 auto *Numerator = getExistingSCEV(LL); 11309 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11310 return false; 11311 11312 // Make sure that the numerator matches with FoundLHS and the denominator 11313 // is positive. 11314 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11315 return false; 11316 11317 auto *DTy = Denominator->getType(); 11318 auto *FRHSTy = FoundRHS->getType(); 11319 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11320 // One of types is a pointer and another one is not. We cannot extend 11321 // them properly to a wider type, so let us just reject this case. 11322 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11323 // to avoid this check. 11324 return false; 11325 11326 // Given that: 11327 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11328 auto *WTy = getWiderType(DTy, FRHSTy); 11329 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11330 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11331 11332 // Try to prove the following rule: 11333 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11334 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11335 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11336 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11337 if (isKnownNonPositive(RHS) && 11338 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11339 return true; 11340 11341 // Try to prove the following rule: 11342 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11343 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11344 // If we divide it by Denominator > 2, then: 11345 // 1. If FoundLHS is negative, then the result is 0. 11346 // 2. If FoundLHS is non-negative, then the result is non-negative. 11347 // Anyways, the result is non-negative. 11348 auto *MinusOne = getMinusOne(WTy); 11349 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11350 if (isKnownNegative(RHS) && 11351 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11352 return true; 11353 } 11354 } 11355 11356 // If our expression contained SCEVUnknown Phis, and we split it down and now 11357 // need to prove something for them, try to prove the predicate for every 11358 // possible incoming values of those Phis. 11359 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11360 return true; 11361 11362 return false; 11363 } 11364 11365 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11366 const SCEV *LHS, const SCEV *RHS) { 11367 // zext x u<= sext x, sext x s<= zext x 11368 switch (Pred) { 11369 case ICmpInst::ICMP_SGE: 11370 std::swap(LHS, RHS); 11371 LLVM_FALLTHROUGH; 11372 case ICmpInst::ICMP_SLE: { 11373 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11374 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11375 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11376 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11377 return true; 11378 break; 11379 } 11380 case ICmpInst::ICMP_UGE: 11381 std::swap(LHS, RHS); 11382 LLVM_FALLTHROUGH; 11383 case ICmpInst::ICMP_ULE: { 11384 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11385 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11386 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11387 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11388 return true; 11389 break; 11390 } 11391 default: 11392 break; 11393 }; 11394 return false; 11395 } 11396 11397 bool 11398 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11399 const SCEV *LHS, const SCEV *RHS) { 11400 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11401 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11402 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11403 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11404 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11405 } 11406 11407 bool 11408 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11409 const SCEV *LHS, const SCEV *RHS, 11410 const SCEV *FoundLHS, 11411 const SCEV *FoundRHS) { 11412 switch (Pred) { 11413 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11414 case ICmpInst::ICMP_EQ: 11415 case ICmpInst::ICMP_NE: 11416 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11417 return true; 11418 break; 11419 case ICmpInst::ICMP_SLT: 11420 case ICmpInst::ICMP_SLE: 11421 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11422 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11423 return true; 11424 break; 11425 case ICmpInst::ICMP_SGT: 11426 case ICmpInst::ICMP_SGE: 11427 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11428 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11429 return true; 11430 break; 11431 case ICmpInst::ICMP_ULT: 11432 case ICmpInst::ICMP_ULE: 11433 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11434 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11435 return true; 11436 break; 11437 case ICmpInst::ICMP_UGT: 11438 case ICmpInst::ICMP_UGE: 11439 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11440 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11441 return true; 11442 break; 11443 } 11444 11445 // Maybe it can be proved via operations? 11446 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11447 return true; 11448 11449 return false; 11450 } 11451 11452 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11453 const SCEV *LHS, 11454 const SCEV *RHS, 11455 const SCEV *FoundLHS, 11456 const SCEV *FoundRHS) { 11457 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11458 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11459 // reduce the compile time impact of this optimization. 11460 return false; 11461 11462 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11463 if (!Addend) 11464 return false; 11465 11466 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11467 11468 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11469 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11470 ConstantRange FoundLHSRange = 11471 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11472 11473 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11474 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11475 11476 // We can also compute the range of values for `LHS` that satisfy the 11477 // consequent, "`LHS` `Pred` `RHS`": 11478 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11479 // The antecedent implies the consequent if every value of `LHS` that 11480 // satisfies the antecedent also satisfies the consequent. 11481 return LHSRange.icmp(Pred, ConstRHS); 11482 } 11483 11484 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11485 bool IsSigned) { 11486 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11487 11488 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11489 const SCEV *One = getOne(Stride->getType()); 11490 11491 if (IsSigned) { 11492 APInt MaxRHS = getSignedRangeMax(RHS); 11493 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11494 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11495 11496 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11497 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11498 } 11499 11500 APInt MaxRHS = getUnsignedRangeMax(RHS); 11501 APInt MaxValue = APInt::getMaxValue(BitWidth); 11502 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11503 11504 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11505 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11506 } 11507 11508 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11509 bool IsSigned) { 11510 11511 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11512 const SCEV *One = getOne(Stride->getType()); 11513 11514 if (IsSigned) { 11515 APInt MinRHS = getSignedRangeMin(RHS); 11516 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11517 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11518 11519 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11520 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11521 } 11522 11523 APInt MinRHS = getUnsignedRangeMin(RHS); 11524 APInt MinValue = APInt::getMinValue(BitWidth); 11525 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11526 11527 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11528 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11529 } 11530 11531 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11532 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11533 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11534 // expression fixes the case of N=0. 11535 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11536 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11537 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11538 } 11539 11540 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11541 const SCEV *Stride, 11542 const SCEV *End, 11543 unsigned BitWidth, 11544 bool IsSigned) { 11545 // The logic in this function assumes we can represent a positive stride. 11546 // If we can't, the backedge-taken count must be zero. 11547 if (IsSigned && BitWidth == 1) 11548 return getZero(Stride->getType()); 11549 11550 // This code has only been closely audited for negative strides in the 11551 // unsigned comparison case, it may be correct for signed comparison, but 11552 // that needs to be established. 11553 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11554 "Stride is expected strictly positive for signed case!"); 11555 11556 // Calculate the maximum backedge count based on the range of values 11557 // permitted by Start, End, and Stride. 11558 APInt MinStart = 11559 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11560 11561 APInt MinStride = 11562 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11563 11564 // We assume either the stride is positive, or the backedge-taken count 11565 // is zero. So force StrideForMaxBECount to be at least one. 11566 APInt One(BitWidth, 1); 11567 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11568 : APIntOps::umax(One, MinStride); 11569 11570 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11571 : APInt::getMaxValue(BitWidth); 11572 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11573 11574 // Although End can be a MAX expression we estimate MaxEnd considering only 11575 // the case End = RHS of the loop termination condition. This is safe because 11576 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11577 // taken count. 11578 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11579 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11580 11581 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11582 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11583 : APIntOps::umax(MaxEnd, MinStart); 11584 11585 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11586 getConstant(StrideForMaxBECount) /* Step */); 11587 } 11588 11589 ScalarEvolution::ExitLimit 11590 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11591 const Loop *L, bool IsSigned, 11592 bool ControlsExit, bool AllowPredicates) { 11593 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11594 11595 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11596 bool PredicatedIV = false; 11597 11598 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11599 // Can we prove this loop *must* be UB if overflow of IV occurs? 11600 // Reasoning goes as follows: 11601 // * Suppose the IV did self wrap. 11602 // * If Stride evenly divides the iteration space, then once wrap 11603 // occurs, the loop must revisit the same values. 11604 // * We know that RHS is invariant, and that none of those values 11605 // caused this exit to be taken previously. Thus, this exit is 11606 // dynamically dead. 11607 // * If this is the sole exit, then a dead exit implies the loop 11608 // must be infinite if there are no abnormal exits. 11609 // * If the loop were infinite, then it must either not be mustprogress 11610 // or have side effects. Otherwise, it must be UB. 11611 // * It can't (by assumption), be UB so we have contradicted our 11612 // premise and can conclude the IV did not in fact self-wrap. 11613 if (!isLoopInvariant(RHS, L)) 11614 return false; 11615 11616 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11617 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11618 return false; 11619 11620 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11621 return false; 11622 11623 return loopIsFiniteByAssumption(L); 11624 }; 11625 11626 if (!IV) { 11627 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11628 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11629 if (AR && AR->getLoop() == L && AR->isAffine()) { 11630 auto Flags = AR->getNoWrapFlags(); 11631 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11632 Flags = setFlags(Flags, SCEV::FlagNW); 11633 11634 SmallVector<const SCEV*> Operands{AR->operands()}; 11635 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11636 11637 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11638 } 11639 if (AR->hasNoUnsignedWrap()) { 11640 // Emulate what getZeroExtendExpr would have done during construction 11641 // if we'd been able to infer the fact just above at that time. 11642 const SCEV *Step = AR->getStepRecurrence(*this); 11643 Type *Ty = ZExt->getType(); 11644 auto *S = getAddRecExpr( 11645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11646 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11647 IV = dyn_cast<SCEVAddRecExpr>(S); 11648 } 11649 } 11650 } 11651 } 11652 11653 11654 if (!IV && AllowPredicates) { 11655 // Try to make this an AddRec using runtime tests, in the first X 11656 // iterations of this loop, where X is the SCEV expression found by the 11657 // algorithm below. 11658 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11659 PredicatedIV = true; 11660 } 11661 11662 // Avoid weird loops 11663 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11664 return getCouldNotCompute(); 11665 11666 // A precondition of this method is that the condition being analyzed 11667 // reaches an exiting branch which dominates the latch. Given that, we can 11668 // assume that an increment which violates the nowrap specification and 11669 // produces poison must cause undefined behavior when the resulting poison 11670 // value is branched upon and thus we can conclude that the backedge is 11671 // taken no more often than would be required to produce that poison value. 11672 // Note that a well defined loop can exit on the iteration which violates 11673 // the nowrap specification if there is another exit (either explicit or 11674 // implicit/exceptional) which causes the loop to execute before the 11675 // exiting instruction we're analyzing would trigger UB. 11676 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11677 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11678 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11679 11680 const SCEV *Stride = IV->getStepRecurrence(*this); 11681 11682 bool PositiveStride = isKnownPositive(Stride); 11683 11684 // Avoid negative or zero stride values. 11685 if (!PositiveStride) { 11686 // We can compute the correct backedge taken count for loops with unknown 11687 // strides if we can prove that the loop is not an infinite loop with side 11688 // effects. Here's the loop structure we are trying to handle - 11689 // 11690 // i = start 11691 // do { 11692 // A[i] = i; 11693 // i += s; 11694 // } while (i < end); 11695 // 11696 // The backedge taken count for such loops is evaluated as - 11697 // (max(end, start + stride) - start - 1) /u stride 11698 // 11699 // The additional preconditions that we need to check to prove correctness 11700 // of the above formula is as follows - 11701 // 11702 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11703 // NoWrap flag). 11704 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11705 // no side effects within the loop) 11706 // c) loop has a single static exit (with no abnormal exits) 11707 // 11708 // Precondition a) implies that if the stride is negative, this is a single 11709 // trip loop. The backedge taken count formula reduces to zero in this case. 11710 // 11711 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11712 // then a zero stride means the backedge can't be taken without executing 11713 // undefined behavior. 11714 // 11715 // The positive stride case is the same as isKnownPositive(Stride) returning 11716 // true (original behavior of the function). 11717 // 11718 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11719 !loopHasNoAbnormalExits(L)) 11720 return getCouldNotCompute(); 11721 11722 // This bailout is protecting the logic in computeMaxBECountForLT which 11723 // has not yet been sufficiently auditted or tested with negative strides. 11724 // We used to filter out all known-non-positive cases here, we're in the 11725 // process of being less restrictive bit by bit. 11726 if (IsSigned && isKnownNonPositive(Stride)) 11727 return getCouldNotCompute(); 11728 11729 if (!isKnownNonZero(Stride)) { 11730 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11731 // if it might eventually be greater than start and if so, on which 11732 // iteration. We can't even produce a useful upper bound. 11733 if (!isLoopInvariant(RHS, L)) 11734 return getCouldNotCompute(); 11735 11736 // We allow a potentially zero stride, but we need to divide by stride 11737 // below. Since the loop can't be infinite and this check must control 11738 // the sole exit, we can infer the exit must be taken on the first 11739 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11740 // we know the numerator in the divides below must be zero, so we can 11741 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11742 // and produce the right result. 11743 // FIXME: Handle the case where Stride is poison? 11744 auto wouldZeroStrideBeUB = [&]() { 11745 // Proof by contradiction. Suppose the stride were zero. If we can 11746 // prove that the backedge *is* taken on the first iteration, then since 11747 // we know this condition controls the sole exit, we must have an 11748 // infinite loop. We can't have a (well defined) infinite loop per 11749 // check just above. 11750 // Note: The (Start - Stride) term is used to get the start' term from 11751 // (start' + stride,+,stride). Remember that we only care about the 11752 // result of this expression when stride == 0 at runtime. 11753 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11754 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11755 }; 11756 if (!wouldZeroStrideBeUB()) { 11757 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11758 } 11759 } 11760 } else if (!Stride->isOne() && !NoWrap) { 11761 auto isUBOnWrap = [&]() { 11762 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11763 // follows trivially from the fact that every (un)signed-wrapped, but 11764 // not self-wrapped value must be LT than the last value before 11765 // (un)signed wrap. Since we know that last value didn't exit, nor 11766 // will any smaller one. 11767 return canAssumeNoSelfWrap(IV); 11768 }; 11769 11770 // Avoid proven overflow cases: this will ensure that the backedge taken 11771 // count will not generate any unsigned overflow. Relaxed no-overflow 11772 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11773 // undefined behaviors like the case of C language. 11774 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11775 return getCouldNotCompute(); 11776 } 11777 11778 // On all paths just preceeding, we established the following invariant: 11779 // IV can be assumed not to overflow up to and including the exiting 11780 // iteration. We proved this in one of two ways: 11781 // 1) We can show overflow doesn't occur before the exiting iteration 11782 // 1a) canIVOverflowOnLT, and b) step of one 11783 // 2) We can show that if overflow occurs, the loop must execute UB 11784 // before any possible exit. 11785 // Note that we have not yet proved RHS invariant (in general). 11786 11787 const SCEV *Start = IV->getStart(); 11788 11789 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11790 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11791 // Use integer-typed versions for actual computation; we can't subtract 11792 // pointers in general. 11793 const SCEV *OrigStart = Start; 11794 const SCEV *OrigRHS = RHS; 11795 if (Start->getType()->isPointerTy()) { 11796 Start = getLosslessPtrToIntExpr(Start); 11797 if (isa<SCEVCouldNotCompute>(Start)) 11798 return Start; 11799 } 11800 if (RHS->getType()->isPointerTy()) { 11801 RHS = getLosslessPtrToIntExpr(RHS); 11802 if (isa<SCEVCouldNotCompute>(RHS)) 11803 return RHS; 11804 } 11805 11806 // When the RHS is not invariant, we do not know the end bound of the loop and 11807 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11808 // calculate the MaxBECount, given the start, stride and max value for the end 11809 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11810 // checked above). 11811 if (!isLoopInvariant(RHS, L)) { 11812 const SCEV *MaxBECount = computeMaxBECountForLT( 11813 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11814 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11815 false /*MaxOrZero*/, Predicates); 11816 } 11817 11818 // We use the expression (max(End,Start)-Start)/Stride to describe the 11819 // backedge count, as if the backedge is taken at least once max(End,Start) 11820 // is End and so the result is as above, and if not max(End,Start) is Start 11821 // so we get a backedge count of zero. 11822 const SCEV *BECount = nullptr; 11823 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11824 // Can we prove (max(RHS,Start) > Start - Stride? 11825 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11826 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11827 // In this case, we can use a refined formula for computing backedge taken 11828 // count. The general formula remains: 11829 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11830 // We want to use the alternate formula: 11831 // "((End - 1) - (Start - Stride)) /u Stride" 11832 // Let's do a quick case analysis to show these are equivalent under 11833 // our precondition that max(RHS,Start) > Start - Stride. 11834 // * For RHS <= Start, the backedge-taken count must be zero. 11835 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11836 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11837 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11838 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11839 // this to the stride of 1 case. 11840 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11841 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11842 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11843 // "((RHS - (Start - Stride) - 1) /u Stride". 11844 // Our preconditions trivially imply no overflow in that form. 11845 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11846 const SCEV *Numerator = 11847 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11848 BECount = getUDivExpr(Numerator, Stride); 11849 } 11850 11851 const SCEV *BECountIfBackedgeTaken = nullptr; 11852 if (!BECount) { 11853 auto canProveRHSGreaterThanEqualStart = [&]() { 11854 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11855 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11856 return true; 11857 11858 // (RHS > Start - 1) implies RHS >= Start. 11859 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11860 // "Start - 1" doesn't overflow. 11861 // * For signed comparison, if Start - 1 does overflow, it's equal 11862 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11863 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11864 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11865 // 11866 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11867 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11868 auto *StartMinusOne = getAddExpr(OrigStart, 11869 getMinusOne(OrigStart->getType())); 11870 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11871 }; 11872 11873 // If we know that RHS >= Start in the context of loop, then we know that 11874 // max(RHS, Start) = RHS at this point. 11875 const SCEV *End; 11876 if (canProveRHSGreaterThanEqualStart()) { 11877 End = RHS; 11878 } else { 11879 // If RHS < Start, the backedge will be taken zero times. So in 11880 // general, we can write the backedge-taken count as: 11881 // 11882 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11883 // 11884 // We convert it to the following to make it more convenient for SCEV: 11885 // 11886 // ceil(max(RHS, Start) - Start) / Stride 11887 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11888 11889 // See what would happen if we assume the backedge is taken. This is 11890 // used to compute MaxBECount. 11891 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11892 } 11893 11894 // At this point, we know: 11895 // 11896 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11897 // 2. The index variable doesn't overflow. 11898 // 11899 // Therefore, we know N exists such that 11900 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11901 // doesn't overflow. 11902 // 11903 // Using this information, try to prove whether the addition in 11904 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11905 const SCEV *One = getOne(Stride->getType()); 11906 bool MayAddOverflow = [&] { 11907 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11908 if (StrideC->getAPInt().isPowerOf2()) { 11909 // Suppose Stride is a power of two, and Start/End are unsigned 11910 // integers. Let UMAX be the largest representable unsigned 11911 // integer. 11912 // 11913 // By the preconditions of this function, we know 11914 // "(Start + Stride * N) >= End", and this doesn't overflow. 11915 // As a formula: 11916 // 11917 // End <= (Start + Stride * N) <= UMAX 11918 // 11919 // Subtracting Start from all the terms: 11920 // 11921 // End - Start <= Stride * N <= UMAX - Start 11922 // 11923 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11924 // 11925 // End - Start <= Stride * N <= UMAX 11926 // 11927 // Stride * N is a multiple of Stride. Therefore, 11928 // 11929 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11930 // 11931 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11932 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11933 // 11934 // End - Start <= Stride * N <= UMAX - Stride - 1 11935 // 11936 // Dropping the middle term: 11937 // 11938 // End - Start <= UMAX - Stride - 1 11939 // 11940 // Adding Stride - 1 to both sides: 11941 // 11942 // (End - Start) + (Stride - 1) <= UMAX 11943 // 11944 // In other words, the addition doesn't have unsigned overflow. 11945 // 11946 // A similar proof works if we treat Start/End as signed values. 11947 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11948 // use signed max instead of unsigned max. Note that we're trying 11949 // to prove a lack of unsigned overflow in either case. 11950 return false; 11951 } 11952 } 11953 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11954 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11955 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11956 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11957 // 11958 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11959 return false; 11960 } 11961 return true; 11962 }(); 11963 11964 const SCEV *Delta = getMinusSCEV(End, Start); 11965 if (!MayAddOverflow) { 11966 // floor((D + (S - 1)) / S) 11967 // We prefer this formulation if it's legal because it's fewer operations. 11968 BECount = 11969 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 11970 } else { 11971 BECount = getUDivCeilSCEV(Delta, Stride); 11972 } 11973 } 11974 11975 const SCEV *MaxBECount; 11976 bool MaxOrZero = false; 11977 if (isa<SCEVConstant>(BECount)) { 11978 MaxBECount = BECount; 11979 } else if (BECountIfBackedgeTaken && 11980 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11981 // If we know exactly how many times the backedge will be taken if it's 11982 // taken at least once, then the backedge count will either be that or 11983 // zero. 11984 MaxBECount = BECountIfBackedgeTaken; 11985 MaxOrZero = true; 11986 } else { 11987 MaxBECount = computeMaxBECountForLT( 11988 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11989 } 11990 11991 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11992 !isa<SCEVCouldNotCompute>(BECount)) 11993 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11994 11995 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11996 } 11997 11998 ScalarEvolution::ExitLimit 11999 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12000 const Loop *L, bool IsSigned, 12001 bool ControlsExit, bool AllowPredicates) { 12002 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12003 // We handle only IV > Invariant 12004 if (!isLoopInvariant(RHS, L)) 12005 return getCouldNotCompute(); 12006 12007 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12008 if (!IV && AllowPredicates) 12009 // Try to make this an AddRec using runtime tests, in the first X 12010 // iterations of this loop, where X is the SCEV expression found by the 12011 // algorithm below. 12012 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12013 12014 // Avoid weird loops 12015 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12016 return getCouldNotCompute(); 12017 12018 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12019 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12020 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12021 12022 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12023 12024 // Avoid negative or zero stride values 12025 if (!isKnownPositive(Stride)) 12026 return getCouldNotCompute(); 12027 12028 // Avoid proven overflow cases: this will ensure that the backedge taken count 12029 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12030 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12031 // behaviors like the case of C language. 12032 if (!Stride->isOne() && !NoWrap) 12033 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12034 return getCouldNotCompute(); 12035 12036 const SCEV *Start = IV->getStart(); 12037 const SCEV *End = RHS; 12038 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12039 // If we know that Start >= RHS in the context of loop, then we know that 12040 // min(RHS, Start) = RHS at this point. 12041 if (isLoopEntryGuardedByCond( 12042 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12043 End = RHS; 12044 else 12045 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12046 } 12047 12048 if (Start->getType()->isPointerTy()) { 12049 Start = getLosslessPtrToIntExpr(Start); 12050 if (isa<SCEVCouldNotCompute>(Start)) 12051 return Start; 12052 } 12053 if (End->getType()->isPointerTy()) { 12054 End = getLosslessPtrToIntExpr(End); 12055 if (isa<SCEVCouldNotCompute>(End)) 12056 return End; 12057 } 12058 12059 // Compute ((Start - End) + (Stride - 1)) / Stride. 12060 // FIXME: This can overflow. Holding off on fixing this for now; 12061 // howManyGreaterThans will hopefully be gone soon. 12062 const SCEV *One = getOne(Stride->getType()); 12063 const SCEV *BECount = getUDivExpr( 12064 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12065 12066 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12067 : getUnsignedRangeMax(Start); 12068 12069 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12070 : getUnsignedRangeMin(Stride); 12071 12072 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12073 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12074 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12075 12076 // Although End can be a MIN expression we estimate MinEnd considering only 12077 // the case End = RHS. This is safe because in the other case (Start - End) 12078 // is zero, leading to a zero maximum backedge taken count. 12079 APInt MinEnd = 12080 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12081 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12082 12083 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12084 ? BECount 12085 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12086 getConstant(MinStride)); 12087 12088 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12089 MaxBECount = BECount; 12090 12091 return ExitLimit(BECount, MaxBECount, false, Predicates); 12092 } 12093 12094 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12095 ScalarEvolution &SE) const { 12096 if (Range.isFullSet()) // Infinite loop. 12097 return SE.getCouldNotCompute(); 12098 12099 // If the start is a non-zero constant, shift the range to simplify things. 12100 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12101 if (!SC->getValue()->isZero()) { 12102 SmallVector<const SCEV *, 4> Operands(operands()); 12103 Operands[0] = SE.getZero(SC->getType()); 12104 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12105 getNoWrapFlags(FlagNW)); 12106 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12107 return ShiftedAddRec->getNumIterationsInRange( 12108 Range.subtract(SC->getAPInt()), SE); 12109 // This is strange and shouldn't happen. 12110 return SE.getCouldNotCompute(); 12111 } 12112 12113 // The only time we can solve this is when we have all constant indices. 12114 // Otherwise, we cannot determine the overflow conditions. 12115 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12116 return SE.getCouldNotCompute(); 12117 12118 // Okay at this point we know that all elements of the chrec are constants and 12119 // that the start element is zero. 12120 12121 // First check to see if the range contains zero. If not, the first 12122 // iteration exits. 12123 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12124 if (!Range.contains(APInt(BitWidth, 0))) 12125 return SE.getZero(getType()); 12126 12127 if (isAffine()) { 12128 // If this is an affine expression then we have this situation: 12129 // Solve {0,+,A} in Range === Ax in Range 12130 12131 // We know that zero is in the range. If A is positive then we know that 12132 // the upper value of the range must be the first possible exit value. 12133 // If A is negative then the lower of the range is the last possible loop 12134 // value. Also note that we already checked for a full range. 12135 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12136 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12137 12138 // The exit value should be (End+A)/A. 12139 APInt ExitVal = (End + A).udiv(A); 12140 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12141 12142 // Evaluate at the exit value. If we really did fall out of the valid 12143 // range, then we computed our trip count, otherwise wrap around or other 12144 // things must have happened. 12145 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12146 if (Range.contains(Val->getValue())) 12147 return SE.getCouldNotCompute(); // Something strange happened 12148 12149 // Ensure that the previous value is in the range. This is a sanity check. 12150 assert(Range.contains( 12151 EvaluateConstantChrecAtConstant(this, 12152 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12153 "Linear scev computation is off in a bad way!"); 12154 return SE.getConstant(ExitValue); 12155 } 12156 12157 if (isQuadratic()) { 12158 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12159 return SE.getConstant(S.getValue()); 12160 } 12161 12162 return SE.getCouldNotCompute(); 12163 } 12164 12165 const SCEVAddRecExpr * 12166 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12167 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12168 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12169 // but in this case we cannot guarantee that the value returned will be an 12170 // AddRec because SCEV does not have a fixed point where it stops 12171 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12172 // may happen if we reach arithmetic depth limit while simplifying. So we 12173 // construct the returned value explicitly. 12174 SmallVector<const SCEV *, 3> Ops; 12175 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12176 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12177 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12178 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12179 // We know that the last operand is not a constant zero (otherwise it would 12180 // have been popped out earlier). This guarantees us that if the result has 12181 // the same last operand, then it will also not be popped out, meaning that 12182 // the returned value will be an AddRec. 12183 const SCEV *Last = getOperand(getNumOperands() - 1); 12184 assert(!Last->isZero() && "Recurrency with zero step?"); 12185 Ops.push_back(Last); 12186 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12187 SCEV::FlagAnyWrap)); 12188 } 12189 12190 // Return true when S contains at least an undef value. 12191 static inline bool containsUndefs(const SCEV *S) { 12192 return SCEVExprContains(S, [](const SCEV *S) { 12193 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12194 return isa<UndefValue>(SU->getValue()); 12195 return false; 12196 }); 12197 } 12198 12199 /// Return the size of an element read or written by Inst. 12200 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12201 Type *Ty; 12202 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12203 Ty = Store->getValueOperand()->getType(); 12204 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12205 Ty = Load->getType(); 12206 else 12207 return nullptr; 12208 12209 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12210 return getSizeOfExpr(ETy, Ty); 12211 } 12212 12213 //===----------------------------------------------------------------------===// 12214 // SCEVCallbackVH Class Implementation 12215 //===----------------------------------------------------------------------===// 12216 12217 void ScalarEvolution::SCEVCallbackVH::deleted() { 12218 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12219 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12220 SE->ConstantEvolutionLoopExitValue.erase(PN); 12221 SE->eraseValueFromMap(getValPtr()); 12222 // this now dangles! 12223 } 12224 12225 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12226 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12227 12228 // Forget all the expressions associated with users of the old value, 12229 // so that future queries will recompute the expressions using the new 12230 // value. 12231 Value *Old = getValPtr(); 12232 SmallVector<User *, 16> Worklist(Old->users()); 12233 SmallPtrSet<User *, 8> Visited; 12234 while (!Worklist.empty()) { 12235 User *U = Worklist.pop_back_val(); 12236 // Deleting the Old value will cause this to dangle. Postpone 12237 // that until everything else is done. 12238 if (U == Old) 12239 continue; 12240 if (!Visited.insert(U).second) 12241 continue; 12242 if (PHINode *PN = dyn_cast<PHINode>(U)) 12243 SE->ConstantEvolutionLoopExitValue.erase(PN); 12244 SE->eraseValueFromMap(U); 12245 llvm::append_range(Worklist, U->users()); 12246 } 12247 // Delete the Old value. 12248 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12249 SE->ConstantEvolutionLoopExitValue.erase(PN); 12250 SE->eraseValueFromMap(Old); 12251 // this now dangles! 12252 } 12253 12254 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12255 : CallbackVH(V), SE(se) {} 12256 12257 //===----------------------------------------------------------------------===// 12258 // ScalarEvolution Class Implementation 12259 //===----------------------------------------------------------------------===// 12260 12261 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12262 AssumptionCache &AC, DominatorTree &DT, 12263 LoopInfo &LI) 12264 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12265 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12266 LoopDispositions(64), BlockDispositions(64) { 12267 // To use guards for proving predicates, we need to scan every instruction in 12268 // relevant basic blocks, and not just terminators. Doing this is a waste of 12269 // time if the IR does not actually contain any calls to 12270 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12271 // 12272 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12273 // to _add_ guards to the module when there weren't any before, and wants 12274 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12275 // efficient in lieu of being smart in that rather obscure case. 12276 12277 auto *GuardDecl = F.getParent()->getFunction( 12278 Intrinsic::getName(Intrinsic::experimental_guard)); 12279 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12280 } 12281 12282 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12283 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12284 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12285 ValueExprMap(std::move(Arg.ValueExprMap)), 12286 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12287 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12288 PendingMerges(std::move(Arg.PendingMerges)), 12289 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12290 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12291 PredicatedBackedgeTakenCounts( 12292 std::move(Arg.PredicatedBackedgeTakenCounts)), 12293 ConstantEvolutionLoopExitValue( 12294 std::move(Arg.ConstantEvolutionLoopExitValue)), 12295 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12296 LoopDispositions(std::move(Arg.LoopDispositions)), 12297 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12298 BlockDispositions(std::move(Arg.BlockDispositions)), 12299 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12300 SignedRanges(std::move(Arg.SignedRanges)), 12301 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12302 UniquePreds(std::move(Arg.UniquePreds)), 12303 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12304 LoopUsers(std::move(Arg.LoopUsers)), 12305 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12306 FirstUnknown(Arg.FirstUnknown) { 12307 Arg.FirstUnknown = nullptr; 12308 } 12309 12310 ScalarEvolution::~ScalarEvolution() { 12311 // Iterate through all the SCEVUnknown instances and call their 12312 // destructors, so that they release their references to their values. 12313 for (SCEVUnknown *U = FirstUnknown; U;) { 12314 SCEVUnknown *Tmp = U; 12315 U = U->Next; 12316 Tmp->~SCEVUnknown(); 12317 } 12318 FirstUnknown = nullptr; 12319 12320 ExprValueMap.clear(); 12321 ValueExprMap.clear(); 12322 HasRecMap.clear(); 12323 BackedgeTakenCounts.clear(); 12324 PredicatedBackedgeTakenCounts.clear(); 12325 12326 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12327 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12328 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12329 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12330 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12331 } 12332 12333 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12334 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12335 } 12336 12337 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12338 const Loop *L) { 12339 // Print all inner loops first 12340 for (Loop *I : *L) 12341 PrintLoopInfo(OS, SE, I); 12342 12343 OS << "Loop "; 12344 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12345 OS << ": "; 12346 12347 SmallVector<BasicBlock *, 8> ExitingBlocks; 12348 L->getExitingBlocks(ExitingBlocks); 12349 if (ExitingBlocks.size() != 1) 12350 OS << "<multiple exits> "; 12351 12352 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12353 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12354 else 12355 OS << "Unpredictable backedge-taken count.\n"; 12356 12357 if (ExitingBlocks.size() > 1) 12358 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12359 OS << " exit count for " << ExitingBlock->getName() << ": " 12360 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12361 } 12362 12363 OS << "Loop "; 12364 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12365 OS << ": "; 12366 12367 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12368 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12369 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12370 OS << ", actual taken count either this or zero."; 12371 } else { 12372 OS << "Unpredictable max backedge-taken count. "; 12373 } 12374 12375 OS << "\n" 12376 "Loop "; 12377 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12378 OS << ": "; 12379 12380 SCEVUnionPredicate Pred; 12381 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12382 if (!isa<SCEVCouldNotCompute>(PBT)) { 12383 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12384 OS << " Predicates:\n"; 12385 Pred.print(OS, 4); 12386 } else { 12387 OS << "Unpredictable predicated backedge-taken count. "; 12388 } 12389 OS << "\n"; 12390 12391 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12392 OS << "Loop "; 12393 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12394 OS << ": "; 12395 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12396 } 12397 } 12398 12399 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12400 switch (LD) { 12401 case ScalarEvolution::LoopVariant: 12402 return "Variant"; 12403 case ScalarEvolution::LoopInvariant: 12404 return "Invariant"; 12405 case ScalarEvolution::LoopComputable: 12406 return "Computable"; 12407 } 12408 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12409 } 12410 12411 void ScalarEvolution::print(raw_ostream &OS) const { 12412 // ScalarEvolution's implementation of the print method is to print 12413 // out SCEV values of all instructions that are interesting. Doing 12414 // this potentially causes it to create new SCEV objects though, 12415 // which technically conflicts with the const qualifier. This isn't 12416 // observable from outside the class though, so casting away the 12417 // const isn't dangerous. 12418 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12419 12420 if (ClassifyExpressions) { 12421 OS << "Classifying expressions for: "; 12422 F.printAsOperand(OS, /*PrintType=*/false); 12423 OS << "\n"; 12424 for (Instruction &I : instructions(F)) 12425 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12426 OS << I << '\n'; 12427 OS << " --> "; 12428 const SCEV *SV = SE.getSCEV(&I); 12429 SV->print(OS); 12430 if (!isa<SCEVCouldNotCompute>(SV)) { 12431 OS << " U: "; 12432 SE.getUnsignedRange(SV).print(OS); 12433 OS << " S: "; 12434 SE.getSignedRange(SV).print(OS); 12435 } 12436 12437 const Loop *L = LI.getLoopFor(I.getParent()); 12438 12439 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12440 if (AtUse != SV) { 12441 OS << " --> "; 12442 AtUse->print(OS); 12443 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12444 OS << " U: "; 12445 SE.getUnsignedRange(AtUse).print(OS); 12446 OS << " S: "; 12447 SE.getSignedRange(AtUse).print(OS); 12448 } 12449 } 12450 12451 if (L) { 12452 OS << "\t\t" "Exits: "; 12453 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12454 if (!SE.isLoopInvariant(ExitValue, L)) { 12455 OS << "<<Unknown>>"; 12456 } else { 12457 OS << *ExitValue; 12458 } 12459 12460 bool First = true; 12461 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12462 if (First) { 12463 OS << "\t\t" "LoopDispositions: { "; 12464 First = false; 12465 } else { 12466 OS << ", "; 12467 } 12468 12469 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12470 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12471 } 12472 12473 for (auto *InnerL : depth_first(L)) { 12474 if (InnerL == L) 12475 continue; 12476 if (First) { 12477 OS << "\t\t" "LoopDispositions: { "; 12478 First = false; 12479 } else { 12480 OS << ", "; 12481 } 12482 12483 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12484 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12485 } 12486 12487 OS << " }"; 12488 } 12489 12490 OS << "\n"; 12491 } 12492 } 12493 12494 OS << "Determining loop execution counts for: "; 12495 F.printAsOperand(OS, /*PrintType=*/false); 12496 OS << "\n"; 12497 for (Loop *I : LI) 12498 PrintLoopInfo(OS, &SE, I); 12499 } 12500 12501 ScalarEvolution::LoopDisposition 12502 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12503 auto &Values = LoopDispositions[S]; 12504 for (auto &V : Values) { 12505 if (V.getPointer() == L) 12506 return V.getInt(); 12507 } 12508 Values.emplace_back(L, LoopVariant); 12509 LoopDisposition D = computeLoopDisposition(S, L); 12510 auto &Values2 = LoopDispositions[S]; 12511 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12512 if (V.getPointer() == L) { 12513 V.setInt(D); 12514 break; 12515 } 12516 } 12517 return D; 12518 } 12519 12520 ScalarEvolution::LoopDisposition 12521 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12522 switch (S->getSCEVType()) { 12523 case scConstant: 12524 return LoopInvariant; 12525 case scPtrToInt: 12526 case scTruncate: 12527 case scZeroExtend: 12528 case scSignExtend: 12529 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12530 case scAddRecExpr: { 12531 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12532 12533 // If L is the addrec's loop, it's computable. 12534 if (AR->getLoop() == L) 12535 return LoopComputable; 12536 12537 // Add recurrences are never invariant in the function-body (null loop). 12538 if (!L) 12539 return LoopVariant; 12540 12541 // Everything that is not defined at loop entry is variant. 12542 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12543 return LoopVariant; 12544 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12545 " dominate the contained loop's header?"); 12546 12547 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12548 if (AR->getLoop()->contains(L)) 12549 return LoopInvariant; 12550 12551 // This recurrence is variant w.r.t. L if any of its operands 12552 // are variant. 12553 for (auto *Op : AR->operands()) 12554 if (!isLoopInvariant(Op, L)) 12555 return LoopVariant; 12556 12557 // Otherwise it's loop-invariant. 12558 return LoopInvariant; 12559 } 12560 case scAddExpr: 12561 case scMulExpr: 12562 case scUMaxExpr: 12563 case scSMaxExpr: 12564 case scUMinExpr: 12565 case scSMinExpr: { 12566 bool HasVarying = false; 12567 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12568 LoopDisposition D = getLoopDisposition(Op, L); 12569 if (D == LoopVariant) 12570 return LoopVariant; 12571 if (D == LoopComputable) 12572 HasVarying = true; 12573 } 12574 return HasVarying ? LoopComputable : LoopInvariant; 12575 } 12576 case scUDivExpr: { 12577 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12578 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12579 if (LD == LoopVariant) 12580 return LoopVariant; 12581 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12582 if (RD == LoopVariant) 12583 return LoopVariant; 12584 return (LD == LoopInvariant && RD == LoopInvariant) ? 12585 LoopInvariant : LoopComputable; 12586 } 12587 case scUnknown: 12588 // All non-instruction values are loop invariant. All instructions are loop 12589 // invariant if they are not contained in the specified loop. 12590 // Instructions are never considered invariant in the function body 12591 // (null loop) because they are defined within the "loop". 12592 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12593 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12594 return LoopInvariant; 12595 case scCouldNotCompute: 12596 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12597 } 12598 llvm_unreachable("Unknown SCEV kind!"); 12599 } 12600 12601 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12602 return getLoopDisposition(S, L) == LoopInvariant; 12603 } 12604 12605 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12606 return getLoopDisposition(S, L) == LoopComputable; 12607 } 12608 12609 ScalarEvolution::BlockDisposition 12610 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12611 auto &Values = BlockDispositions[S]; 12612 for (auto &V : Values) { 12613 if (V.getPointer() == BB) 12614 return V.getInt(); 12615 } 12616 Values.emplace_back(BB, DoesNotDominateBlock); 12617 BlockDisposition D = computeBlockDisposition(S, BB); 12618 auto &Values2 = BlockDispositions[S]; 12619 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12620 if (V.getPointer() == BB) { 12621 V.setInt(D); 12622 break; 12623 } 12624 } 12625 return D; 12626 } 12627 12628 ScalarEvolution::BlockDisposition 12629 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12630 switch (S->getSCEVType()) { 12631 case scConstant: 12632 return ProperlyDominatesBlock; 12633 case scPtrToInt: 12634 case scTruncate: 12635 case scZeroExtend: 12636 case scSignExtend: 12637 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12638 case scAddRecExpr: { 12639 // This uses a "dominates" query instead of "properly dominates" query 12640 // to test for proper dominance too, because the instruction which 12641 // produces the addrec's value is a PHI, and a PHI effectively properly 12642 // dominates its entire containing block. 12643 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12644 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12645 return DoesNotDominateBlock; 12646 12647 // Fall through into SCEVNAryExpr handling. 12648 LLVM_FALLTHROUGH; 12649 } 12650 case scAddExpr: 12651 case scMulExpr: 12652 case scUMaxExpr: 12653 case scSMaxExpr: 12654 case scUMinExpr: 12655 case scSMinExpr: { 12656 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12657 bool Proper = true; 12658 for (const SCEV *NAryOp : NAry->operands()) { 12659 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12660 if (D == DoesNotDominateBlock) 12661 return DoesNotDominateBlock; 12662 if (D == DominatesBlock) 12663 Proper = false; 12664 } 12665 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12666 } 12667 case scUDivExpr: { 12668 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12669 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12670 BlockDisposition LD = getBlockDisposition(LHS, BB); 12671 if (LD == DoesNotDominateBlock) 12672 return DoesNotDominateBlock; 12673 BlockDisposition RD = getBlockDisposition(RHS, BB); 12674 if (RD == DoesNotDominateBlock) 12675 return DoesNotDominateBlock; 12676 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12677 ProperlyDominatesBlock : DominatesBlock; 12678 } 12679 case scUnknown: 12680 if (Instruction *I = 12681 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12682 if (I->getParent() == BB) 12683 return DominatesBlock; 12684 if (DT.properlyDominates(I->getParent(), BB)) 12685 return ProperlyDominatesBlock; 12686 return DoesNotDominateBlock; 12687 } 12688 return ProperlyDominatesBlock; 12689 case scCouldNotCompute: 12690 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12691 } 12692 llvm_unreachable("Unknown SCEV kind!"); 12693 } 12694 12695 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12696 return getBlockDisposition(S, BB) >= DominatesBlock; 12697 } 12698 12699 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12700 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12701 } 12702 12703 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12704 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12705 } 12706 12707 void 12708 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12709 ValuesAtScopes.erase(S); 12710 LoopDispositions.erase(S); 12711 BlockDispositions.erase(S); 12712 UnsignedRanges.erase(S); 12713 SignedRanges.erase(S); 12714 ExprValueMap.erase(S); 12715 HasRecMap.erase(S); 12716 MinTrailingZerosCache.erase(S); 12717 12718 for (auto I = PredicatedSCEVRewrites.begin(); 12719 I != PredicatedSCEVRewrites.end();) { 12720 std::pair<const SCEV *, const Loop *> Entry = I->first; 12721 if (Entry.first == S) 12722 PredicatedSCEVRewrites.erase(I++); 12723 else 12724 ++I; 12725 } 12726 12727 auto RemoveSCEVFromBackedgeMap = 12728 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12729 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12730 BackedgeTakenInfo &BEInfo = I->second; 12731 if (BEInfo.hasOperand(S)) 12732 Map.erase(I++); 12733 else 12734 ++I; 12735 } 12736 }; 12737 12738 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12739 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12740 } 12741 12742 void 12743 ScalarEvolution::getUsedLoops(const SCEV *S, 12744 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12745 struct FindUsedLoops { 12746 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12747 : LoopsUsed(LoopsUsed) {} 12748 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12749 bool follow(const SCEV *S) { 12750 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12751 LoopsUsed.insert(AR->getLoop()); 12752 return true; 12753 } 12754 12755 bool isDone() const { return false; } 12756 }; 12757 12758 FindUsedLoops F(LoopsUsed); 12759 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12760 } 12761 12762 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12763 SmallPtrSet<const Loop *, 8> LoopsUsed; 12764 getUsedLoops(S, LoopsUsed); 12765 for (auto *L : LoopsUsed) 12766 LoopUsers[L].push_back(S); 12767 } 12768 12769 void ScalarEvolution::verify() const { 12770 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12771 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12772 12773 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12774 12775 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12776 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12777 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12778 12779 const SCEV *visitConstant(const SCEVConstant *Constant) { 12780 return SE.getConstant(Constant->getAPInt()); 12781 } 12782 12783 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12784 return SE.getUnknown(Expr->getValue()); 12785 } 12786 12787 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12788 return SE.getCouldNotCompute(); 12789 } 12790 }; 12791 12792 SCEVMapper SCM(SE2); 12793 12794 while (!LoopStack.empty()) { 12795 auto *L = LoopStack.pop_back_val(); 12796 llvm::append_range(LoopStack, *L); 12797 12798 auto *CurBECount = SCM.visit( 12799 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12800 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12801 12802 if (CurBECount == SE2.getCouldNotCompute() || 12803 NewBECount == SE2.getCouldNotCompute()) { 12804 // NB! This situation is legal, but is very suspicious -- whatever pass 12805 // change the loop to make a trip count go from could not compute to 12806 // computable or vice-versa *should have* invalidated SCEV. However, we 12807 // choose not to assert here (for now) since we don't want false 12808 // positives. 12809 continue; 12810 } 12811 12812 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12813 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12814 // not propagate undef aggressively). This means we can (and do) fail 12815 // verification in cases where a transform makes the trip count of a loop 12816 // go from "undef" to "undef+1" (say). The transform is fine, since in 12817 // both cases the loop iterates "undef" times, but SCEV thinks we 12818 // increased the trip count of the loop by 1 incorrectly. 12819 continue; 12820 } 12821 12822 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12823 SE.getTypeSizeInBits(NewBECount->getType())) 12824 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12825 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12826 SE.getTypeSizeInBits(NewBECount->getType())) 12827 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12828 12829 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12830 12831 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12832 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12833 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12834 dbgs() << "Old: " << *CurBECount << "\n"; 12835 dbgs() << "New: " << *NewBECount << "\n"; 12836 dbgs() << "Delta: " << *Delta << "\n"; 12837 std::abort(); 12838 } 12839 } 12840 12841 // Collect all valid loops currently in LoopInfo. 12842 SmallPtrSet<Loop *, 32> ValidLoops; 12843 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12844 while (!Worklist.empty()) { 12845 Loop *L = Worklist.pop_back_val(); 12846 if (ValidLoops.contains(L)) 12847 continue; 12848 ValidLoops.insert(L); 12849 Worklist.append(L->begin(), L->end()); 12850 } 12851 // Check for SCEV expressions referencing invalid/deleted loops. 12852 for (auto &KV : ValueExprMap) { 12853 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12854 if (!AR) 12855 continue; 12856 assert(ValidLoops.contains(AR->getLoop()) && 12857 "AddRec references invalid loop"); 12858 } 12859 } 12860 12861 bool ScalarEvolution::invalidate( 12862 Function &F, const PreservedAnalyses &PA, 12863 FunctionAnalysisManager::Invalidator &Inv) { 12864 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12865 // of its dependencies is invalidated. 12866 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12867 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12868 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12869 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12870 Inv.invalidate<LoopAnalysis>(F, PA); 12871 } 12872 12873 AnalysisKey ScalarEvolutionAnalysis::Key; 12874 12875 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12876 FunctionAnalysisManager &AM) { 12877 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12878 AM.getResult<AssumptionAnalysis>(F), 12879 AM.getResult<DominatorTreeAnalysis>(F), 12880 AM.getResult<LoopAnalysis>(F)); 12881 } 12882 12883 PreservedAnalyses 12884 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12885 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12886 return PreservedAnalyses::all(); 12887 } 12888 12889 PreservedAnalyses 12890 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12891 // For compatibility with opt's -analyze feature under legacy pass manager 12892 // which was not ported to NPM. This keeps tests using 12893 // update_analyze_test_checks.py working. 12894 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12895 << F.getName() << "':\n"; 12896 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12897 return PreservedAnalyses::all(); 12898 } 12899 12900 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12901 "Scalar Evolution Analysis", false, true) 12902 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12903 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12904 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12905 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12906 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12907 "Scalar Evolution Analysis", false, true) 12908 12909 char ScalarEvolutionWrapperPass::ID = 0; 12910 12911 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12912 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12913 } 12914 12915 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12916 SE.reset(new ScalarEvolution( 12917 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12918 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12919 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12920 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12921 return false; 12922 } 12923 12924 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12925 12926 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12927 SE->print(OS); 12928 } 12929 12930 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12931 if (!VerifySCEV) 12932 return; 12933 12934 SE->verify(); 12935 } 12936 12937 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12938 AU.setPreservesAll(); 12939 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12940 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12941 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12942 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12943 } 12944 12945 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12946 const SCEV *RHS) { 12947 FoldingSetNodeID ID; 12948 assert(LHS->getType() == RHS->getType() && 12949 "Type mismatch between LHS and RHS"); 12950 // Unique this node based on the arguments 12951 ID.AddInteger(SCEVPredicate::P_Equal); 12952 ID.AddPointer(LHS); 12953 ID.AddPointer(RHS); 12954 void *IP = nullptr; 12955 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12956 return S; 12957 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12958 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12959 UniquePreds.InsertNode(Eq, IP); 12960 return Eq; 12961 } 12962 12963 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12964 const SCEVAddRecExpr *AR, 12965 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12966 FoldingSetNodeID ID; 12967 // Unique this node based on the arguments 12968 ID.AddInteger(SCEVPredicate::P_Wrap); 12969 ID.AddPointer(AR); 12970 ID.AddInteger(AddedFlags); 12971 void *IP = nullptr; 12972 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12973 return S; 12974 auto *OF = new (SCEVAllocator) 12975 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12976 UniquePreds.InsertNode(OF, IP); 12977 return OF; 12978 } 12979 12980 namespace { 12981 12982 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12983 public: 12984 12985 /// Rewrites \p S in the context of a loop L and the SCEV predication 12986 /// infrastructure. 12987 /// 12988 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12989 /// equivalences present in \p Pred. 12990 /// 12991 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12992 /// \p NewPreds such that the result will be an AddRecExpr. 12993 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12994 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12995 SCEVUnionPredicate *Pred) { 12996 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12997 return Rewriter.visit(S); 12998 } 12999 13000 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13001 if (Pred) { 13002 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13003 for (auto *Pred : ExprPreds) 13004 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13005 if (IPred->getLHS() == Expr) 13006 return IPred->getRHS(); 13007 } 13008 return convertToAddRecWithPreds(Expr); 13009 } 13010 13011 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13012 const SCEV *Operand = visit(Expr->getOperand()); 13013 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13014 if (AR && AR->getLoop() == L && AR->isAffine()) { 13015 // This couldn't be folded because the operand didn't have the nuw 13016 // flag. Add the nusw flag as an assumption that we could make. 13017 const SCEV *Step = AR->getStepRecurrence(SE); 13018 Type *Ty = Expr->getType(); 13019 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13020 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13021 SE.getSignExtendExpr(Step, Ty), L, 13022 AR->getNoWrapFlags()); 13023 } 13024 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13025 } 13026 13027 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13028 const SCEV *Operand = visit(Expr->getOperand()); 13029 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13030 if (AR && AR->getLoop() == L && AR->isAffine()) { 13031 // This couldn't be folded because the operand didn't have the nsw 13032 // flag. Add the nssw flag as an assumption that we could make. 13033 const SCEV *Step = AR->getStepRecurrence(SE); 13034 Type *Ty = Expr->getType(); 13035 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13036 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13037 SE.getSignExtendExpr(Step, Ty), L, 13038 AR->getNoWrapFlags()); 13039 } 13040 return SE.getSignExtendExpr(Operand, Expr->getType()); 13041 } 13042 13043 private: 13044 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13045 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13046 SCEVUnionPredicate *Pred) 13047 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13048 13049 bool addOverflowAssumption(const SCEVPredicate *P) { 13050 if (!NewPreds) { 13051 // Check if we've already made this assumption. 13052 return Pred && Pred->implies(P); 13053 } 13054 NewPreds->insert(P); 13055 return true; 13056 } 13057 13058 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13059 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13060 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13061 return addOverflowAssumption(A); 13062 } 13063 13064 // If \p Expr represents a PHINode, we try to see if it can be represented 13065 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13066 // to add this predicate as a runtime overflow check, we return the AddRec. 13067 // If \p Expr does not meet these conditions (is not a PHI node, or we 13068 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13069 // return \p Expr. 13070 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13071 if (!isa<PHINode>(Expr->getValue())) 13072 return Expr; 13073 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13074 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13075 if (!PredicatedRewrite) 13076 return Expr; 13077 for (auto *P : PredicatedRewrite->second){ 13078 // Wrap predicates from outer loops are not supported. 13079 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13080 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13081 if (L != AR->getLoop()) 13082 return Expr; 13083 } 13084 if (!addOverflowAssumption(P)) 13085 return Expr; 13086 } 13087 return PredicatedRewrite->first; 13088 } 13089 13090 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13091 SCEVUnionPredicate *Pred; 13092 const Loop *L; 13093 }; 13094 13095 } // end anonymous namespace 13096 13097 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13098 SCEVUnionPredicate &Preds) { 13099 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13100 } 13101 13102 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13103 const SCEV *S, const Loop *L, 13104 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13105 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13106 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13107 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13108 13109 if (!AddRec) 13110 return nullptr; 13111 13112 // Since the transformation was successful, we can now transfer the SCEV 13113 // predicates. 13114 for (auto *P : TransformPreds) 13115 Preds.insert(P); 13116 13117 return AddRec; 13118 } 13119 13120 /// SCEV predicates 13121 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13122 SCEVPredicateKind Kind) 13123 : FastID(ID), Kind(Kind) {} 13124 13125 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13126 const SCEV *LHS, const SCEV *RHS) 13127 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13128 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13129 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13130 } 13131 13132 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13133 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13134 13135 if (!Op) 13136 return false; 13137 13138 return Op->LHS == LHS && Op->RHS == RHS; 13139 } 13140 13141 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13142 13143 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13144 13145 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13146 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13147 } 13148 13149 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13150 const SCEVAddRecExpr *AR, 13151 IncrementWrapFlags Flags) 13152 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13153 13154 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13155 13156 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13157 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13158 13159 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13160 } 13161 13162 bool SCEVWrapPredicate::isAlwaysTrue() const { 13163 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13164 IncrementWrapFlags IFlags = Flags; 13165 13166 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13167 IFlags = clearFlags(IFlags, IncrementNSSW); 13168 13169 return IFlags == IncrementAnyWrap; 13170 } 13171 13172 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13173 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13174 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13175 OS << "<nusw>"; 13176 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13177 OS << "<nssw>"; 13178 OS << "\n"; 13179 } 13180 13181 SCEVWrapPredicate::IncrementWrapFlags 13182 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13183 ScalarEvolution &SE) { 13184 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13185 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13186 13187 // We can safely transfer the NSW flag as NSSW. 13188 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13189 ImpliedFlags = IncrementNSSW; 13190 13191 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13192 // If the increment is positive, the SCEV NUW flag will also imply the 13193 // WrapPredicate NUSW flag. 13194 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13195 if (Step->getValue()->getValue().isNonNegative()) 13196 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13197 } 13198 13199 return ImpliedFlags; 13200 } 13201 13202 /// Union predicates don't get cached so create a dummy set ID for it. 13203 SCEVUnionPredicate::SCEVUnionPredicate() 13204 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13205 13206 bool SCEVUnionPredicate::isAlwaysTrue() const { 13207 return all_of(Preds, 13208 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13209 } 13210 13211 ArrayRef<const SCEVPredicate *> 13212 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13213 auto I = SCEVToPreds.find(Expr); 13214 if (I == SCEVToPreds.end()) 13215 return ArrayRef<const SCEVPredicate *>(); 13216 return I->second; 13217 } 13218 13219 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13220 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13221 return all_of(Set->Preds, 13222 [this](const SCEVPredicate *I) { return this->implies(I); }); 13223 13224 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13225 if (ScevPredsIt == SCEVToPreds.end()) 13226 return false; 13227 auto &SCEVPreds = ScevPredsIt->second; 13228 13229 return any_of(SCEVPreds, 13230 [N](const SCEVPredicate *I) { return I->implies(N); }); 13231 } 13232 13233 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13234 13235 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13236 for (auto Pred : Preds) 13237 Pred->print(OS, Depth); 13238 } 13239 13240 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13241 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13242 for (auto Pred : Set->Preds) 13243 add(Pred); 13244 return; 13245 } 13246 13247 if (implies(N)) 13248 return; 13249 13250 const SCEV *Key = N->getExpr(); 13251 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13252 " associated expression!"); 13253 13254 SCEVToPreds[Key].push_back(N); 13255 Preds.push_back(N); 13256 } 13257 13258 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13259 Loop &L) 13260 : SE(SE), L(L) {} 13261 13262 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13263 const SCEV *Expr = SE.getSCEV(V); 13264 RewriteEntry &Entry = RewriteMap[Expr]; 13265 13266 // If we already have an entry and the version matches, return it. 13267 if (Entry.second && Generation == Entry.first) 13268 return Entry.second; 13269 13270 // We found an entry but it's stale. Rewrite the stale entry 13271 // according to the current predicate. 13272 if (Entry.second) 13273 Expr = Entry.second; 13274 13275 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13276 Entry = {Generation, NewSCEV}; 13277 13278 return NewSCEV; 13279 } 13280 13281 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13282 if (!BackedgeCount) { 13283 SCEVUnionPredicate BackedgePred; 13284 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13285 addPredicate(BackedgePred); 13286 } 13287 return BackedgeCount; 13288 } 13289 13290 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13291 if (Preds.implies(&Pred)) 13292 return; 13293 Preds.add(&Pred); 13294 updateGeneration(); 13295 } 13296 13297 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13298 return Preds; 13299 } 13300 13301 void PredicatedScalarEvolution::updateGeneration() { 13302 // If the generation number wrapped recompute everything. 13303 if (++Generation == 0) { 13304 for (auto &II : RewriteMap) { 13305 const SCEV *Rewritten = II.second.second; 13306 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13307 } 13308 } 13309 } 13310 13311 void PredicatedScalarEvolution::setNoOverflow( 13312 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13313 const SCEV *Expr = getSCEV(V); 13314 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13315 13316 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13317 13318 // Clear the statically implied flags. 13319 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13320 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13321 13322 auto II = FlagsMap.insert({V, Flags}); 13323 if (!II.second) 13324 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13325 } 13326 13327 bool PredicatedScalarEvolution::hasNoOverflow( 13328 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13329 const SCEV *Expr = getSCEV(V); 13330 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13331 13332 Flags = SCEVWrapPredicate::clearFlags( 13333 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13334 13335 auto II = FlagsMap.find(V); 13336 13337 if (II != FlagsMap.end()) 13338 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13339 13340 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13341 } 13342 13343 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13344 const SCEV *Expr = this->getSCEV(V); 13345 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13346 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13347 13348 if (!New) 13349 return nullptr; 13350 13351 for (auto *P : NewPreds) 13352 Preds.add(P); 13353 13354 updateGeneration(); 13355 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13356 return New; 13357 } 13358 13359 PredicatedScalarEvolution::PredicatedScalarEvolution( 13360 const PredicatedScalarEvolution &Init) 13361 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13362 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13363 for (auto I : Init.FlagsMap) 13364 FlagsMap.insert(I); 13365 } 13366 13367 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13368 // For each block. 13369 for (auto *BB : L.getBlocks()) 13370 for (auto &I : *BB) { 13371 if (!SE.isSCEVable(I.getType())) 13372 continue; 13373 13374 auto *Expr = SE.getSCEV(&I); 13375 auto II = RewriteMap.find(Expr); 13376 13377 if (II == RewriteMap.end()) 13378 continue; 13379 13380 // Don't print things that are not interesting. 13381 if (II->second.second == Expr) 13382 continue; 13383 13384 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13385 OS.indent(Depth + 2) << *Expr << "\n"; 13386 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13387 } 13388 } 13389 13390 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13391 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13392 // for URem with constant power-of-2 second operands. 13393 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13394 // 4, A / B becomes X / 8). 13395 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13396 const SCEV *&RHS) { 13397 // Try to match 'zext (trunc A to iB) to iY', which is used 13398 // for URem with constant power-of-2 second operands. Make sure the size of 13399 // the operand A matches the size of the whole expressions. 13400 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13401 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13402 LHS = Trunc->getOperand(); 13403 // Bail out if the type of the LHS is larger than the type of the 13404 // expression for now. 13405 if (getTypeSizeInBits(LHS->getType()) > 13406 getTypeSizeInBits(Expr->getType())) 13407 return false; 13408 if (LHS->getType() != Expr->getType()) 13409 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13410 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13411 << getTypeSizeInBits(Trunc->getType())); 13412 return true; 13413 } 13414 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13415 if (Add == nullptr || Add->getNumOperands() != 2) 13416 return false; 13417 13418 const SCEV *A = Add->getOperand(1); 13419 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13420 13421 if (Mul == nullptr) 13422 return false; 13423 13424 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13425 // (SomeExpr + (-(SomeExpr / B) * B)). 13426 if (Expr == getURemExpr(A, B)) { 13427 LHS = A; 13428 RHS = B; 13429 return true; 13430 } 13431 return false; 13432 }; 13433 13434 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13435 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13436 return MatchURemWithDivisor(Mul->getOperand(1)) || 13437 MatchURemWithDivisor(Mul->getOperand(2)); 13438 13439 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13440 if (Mul->getNumOperands() == 2) 13441 return MatchURemWithDivisor(Mul->getOperand(1)) || 13442 MatchURemWithDivisor(Mul->getOperand(0)) || 13443 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13444 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13445 return false; 13446 } 13447 13448 const SCEV * 13449 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13450 SmallVector<BasicBlock*, 16> ExitingBlocks; 13451 L->getExitingBlocks(ExitingBlocks); 13452 13453 // Form an expression for the maximum exit count possible for this loop. We 13454 // merge the max and exact information to approximate a version of 13455 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13456 SmallVector<const SCEV*, 4> ExitCounts; 13457 for (BasicBlock *ExitingBB : ExitingBlocks) { 13458 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13459 if (isa<SCEVCouldNotCompute>(ExitCount)) 13460 ExitCount = getExitCount(L, ExitingBB, 13461 ScalarEvolution::ConstantMaximum); 13462 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13463 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13464 "We should only have known counts for exiting blocks that " 13465 "dominate latch!"); 13466 ExitCounts.push_back(ExitCount); 13467 } 13468 } 13469 if (ExitCounts.empty()) 13470 return getCouldNotCompute(); 13471 return getUMinFromMismatchedTypes(ExitCounts); 13472 } 13473 13474 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13475 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13476 /// we cannot guarantee that the replacement is loop invariant in the loop of 13477 /// the AddRec. 13478 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13479 ValueToSCEVMapTy ⤅ 13480 13481 public: 13482 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13483 : SCEVRewriteVisitor(SE), Map(M) {} 13484 13485 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13486 13487 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13488 auto I = Map.find(Expr->getValue()); 13489 if (I == Map.end()) 13490 return Expr; 13491 return I->second; 13492 } 13493 }; 13494 13495 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13496 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13497 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13498 // If we have LHS == 0, check if LHS is computing a property of some unknown 13499 // SCEV %v which we can rewrite %v to express explicitly. 13500 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13501 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13502 RHSC->getValue()->isNullValue()) { 13503 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13504 // explicitly express that. 13505 const SCEV *URemLHS = nullptr; 13506 const SCEV *URemRHS = nullptr; 13507 if (matchURem(LHS, URemLHS, URemRHS)) { 13508 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13509 Value *V = LHSUnknown->getValue(); 13510 auto Multiple = 13511 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13512 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13513 RewriteMap[V] = Multiple; 13514 return; 13515 } 13516 } 13517 } 13518 13519 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13520 std::swap(LHS, RHS); 13521 Predicate = CmpInst::getSwappedPredicate(Predicate); 13522 } 13523 13524 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13525 // create this form when combining two checks of the form (X u< C2 + C1) and 13526 // (X >=u C1). 13527 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13528 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13529 if (!AddExpr || AddExpr->getNumOperands() != 2) 13530 return false; 13531 13532 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13533 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13534 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13535 if (!C1 || !C2 || !LHSUnknown) 13536 return false; 13537 13538 auto ExactRegion = 13539 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13540 .sub(C1->getAPInt()); 13541 13542 // Bail out, unless we have a non-wrapping, monotonic range. 13543 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13544 return false; 13545 auto I = RewriteMap.find(LHSUnknown->getValue()); 13546 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13547 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13548 getConstant(ExactRegion.getUnsignedMin()), 13549 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13550 return true; 13551 }; 13552 if (MatchRangeCheckIdiom()) 13553 return; 13554 13555 // For now, limit to conditions that provide information about unknown 13556 // expressions. RHS also cannot contain add recurrences. 13557 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13558 if (!LHSUnknown || containsAddRecurrence(RHS)) 13559 return; 13560 13561 // Check whether LHS has already been rewritten. In that case we want to 13562 // chain further rewrites onto the already rewritten value. 13563 auto I = RewriteMap.find(LHSUnknown->getValue()); 13564 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13565 const SCEV *RewrittenRHS = nullptr; 13566 switch (Predicate) { 13567 case CmpInst::ICMP_ULT: 13568 RewrittenRHS = 13569 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13570 break; 13571 case CmpInst::ICMP_SLT: 13572 RewrittenRHS = 13573 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13574 break; 13575 case CmpInst::ICMP_ULE: 13576 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13577 break; 13578 case CmpInst::ICMP_SLE: 13579 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13580 break; 13581 case CmpInst::ICMP_UGT: 13582 RewrittenRHS = 13583 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13584 break; 13585 case CmpInst::ICMP_SGT: 13586 RewrittenRHS = 13587 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13588 break; 13589 case CmpInst::ICMP_UGE: 13590 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13591 break; 13592 case CmpInst::ICMP_SGE: 13593 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13594 break; 13595 case CmpInst::ICMP_EQ: 13596 if (isa<SCEVConstant>(RHS)) 13597 RewrittenRHS = RHS; 13598 break; 13599 case CmpInst::ICMP_NE: 13600 if (isa<SCEVConstant>(RHS) && 13601 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13602 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13603 break; 13604 default: 13605 break; 13606 } 13607 13608 if (RewrittenRHS) 13609 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13610 }; 13611 // Starting at the loop predecessor, climb up the predecessor chain, as long 13612 // as there are predecessors that can be found that have unique successors 13613 // leading to the original header. 13614 // TODO: share this logic with isLoopEntryGuardedByCond. 13615 ValueToSCEVMapTy RewriteMap; 13616 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13617 L->getLoopPredecessor(), L->getHeader()); 13618 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13619 13620 const BranchInst *LoopEntryPredicate = 13621 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13622 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13623 continue; 13624 13625 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13626 SmallVector<Value *, 8> Worklist; 13627 SmallPtrSet<Value *, 8> Visited; 13628 Worklist.push_back(LoopEntryPredicate->getCondition()); 13629 while (!Worklist.empty()) { 13630 Value *Cond = Worklist.pop_back_val(); 13631 if (!Visited.insert(Cond).second) 13632 continue; 13633 13634 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13635 auto Predicate = 13636 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13637 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13638 getSCEV(Cmp->getOperand(1)), RewriteMap); 13639 continue; 13640 } 13641 13642 Value *L, *R; 13643 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13644 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13645 Worklist.push_back(L); 13646 Worklist.push_back(R); 13647 } 13648 } 13649 } 13650 13651 // Also collect information from assumptions dominating the loop. 13652 for (auto &AssumeVH : AC.assumptions()) { 13653 if (!AssumeVH) 13654 continue; 13655 auto *AssumeI = cast<CallInst>(AssumeVH); 13656 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13657 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13658 continue; 13659 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13660 getSCEV(Cmp->getOperand(1)), RewriteMap); 13661 } 13662 13663 if (RewriteMap.empty()) 13664 return Expr; 13665 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13666 return Rewriter.visit(Expr); 13667 } 13668