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 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2401 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2402 Ops.size() == 2) { 2403 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2404 if (UDiv->getOperand(1) == Ops[1]) 2405 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2406 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2407 if (UDiv->getOperand(1) == Ops[0]) 2408 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2409 } 2410 2411 return Flags; 2412 } 2413 2414 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2415 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2416 } 2417 2418 /// Get a canonical add expression, or something simpler if possible. 2419 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2420 SCEV::NoWrapFlags OrigFlags, 2421 unsigned Depth) { 2422 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2423 "only nuw or nsw allowed"); 2424 assert(!Ops.empty() && "Cannot get empty add!"); 2425 if (Ops.size() == 1) return Ops[0]; 2426 #ifndef NDEBUG 2427 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2428 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2429 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2430 "SCEVAddExpr operand types don't match!"); 2431 unsigned NumPtrs = count_if( 2432 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2433 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2434 #endif 2435 2436 // Sort by complexity, this groups all similar expression types together. 2437 GroupByComplexity(Ops, &LI, DT); 2438 2439 // If there are any constants, fold them together. 2440 unsigned Idx = 0; 2441 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2442 ++Idx; 2443 assert(Idx < Ops.size()); 2444 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2445 // We found two constants, fold them together! 2446 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2447 if (Ops.size() == 2) return Ops[0]; 2448 Ops.erase(Ops.begin()+1); // Erase the folded element 2449 LHSC = cast<SCEVConstant>(Ops[0]); 2450 } 2451 2452 // If we are left with a constant zero being added, strip it off. 2453 if (LHSC->getValue()->isZero()) { 2454 Ops.erase(Ops.begin()); 2455 --Idx; 2456 } 2457 2458 if (Ops.size() == 1) return Ops[0]; 2459 } 2460 2461 // Delay expensive flag strengthening until necessary. 2462 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2463 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2464 }; 2465 2466 // Limit recursion calls depth. 2467 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2468 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2469 2470 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2471 // Don't strengthen flags if we have no new information. 2472 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2473 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2474 Add->setNoWrapFlags(ComputeFlags(Ops)); 2475 return S; 2476 } 2477 2478 // Okay, check to see if the same value occurs in the operand list more than 2479 // once. If so, merge them together into an multiply expression. Since we 2480 // sorted the list, these values are required to be adjacent. 2481 Type *Ty = Ops[0]->getType(); 2482 bool FoundMatch = false; 2483 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2484 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2485 // Scan ahead to count how many equal operands there are. 2486 unsigned Count = 2; 2487 while (i+Count != e && Ops[i+Count] == Ops[i]) 2488 ++Count; 2489 // Merge the values into a multiply. 2490 const SCEV *Scale = getConstant(Ty, Count); 2491 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2492 if (Ops.size() == Count) 2493 return Mul; 2494 Ops[i] = Mul; 2495 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2496 --i; e -= Count - 1; 2497 FoundMatch = true; 2498 } 2499 if (FoundMatch) 2500 return getAddExpr(Ops, OrigFlags, Depth + 1); 2501 2502 // Check for truncates. If all the operands are truncated from the same 2503 // type, see if factoring out the truncate would permit the result to be 2504 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2505 // if the contents of the resulting outer trunc fold to something simple. 2506 auto FindTruncSrcType = [&]() -> Type * { 2507 // We're ultimately looking to fold an addrec of truncs and muls of only 2508 // constants and truncs, so if we find any other types of SCEV 2509 // as operands of the addrec then we bail and return nullptr here. 2510 // Otherwise, we return the type of the operand of a trunc that we find. 2511 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2512 return T->getOperand()->getType(); 2513 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2514 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2515 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2516 return T->getOperand()->getType(); 2517 } 2518 return nullptr; 2519 }; 2520 if (auto *SrcType = FindTruncSrcType()) { 2521 SmallVector<const SCEV *, 8> LargeOps; 2522 bool Ok = true; 2523 // Check all the operands to see if they can be represented in the 2524 // source type of the truncate. 2525 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2526 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2527 if (T->getOperand()->getType() != SrcType) { 2528 Ok = false; 2529 break; 2530 } 2531 LargeOps.push_back(T->getOperand()); 2532 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2533 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2534 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2535 SmallVector<const SCEV *, 8> LargeMulOps; 2536 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2537 if (const SCEVTruncateExpr *T = 2538 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2539 if (T->getOperand()->getType() != SrcType) { 2540 Ok = false; 2541 break; 2542 } 2543 LargeMulOps.push_back(T->getOperand()); 2544 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2545 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2546 } else { 2547 Ok = false; 2548 break; 2549 } 2550 } 2551 if (Ok) 2552 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2553 } else { 2554 Ok = false; 2555 break; 2556 } 2557 } 2558 if (Ok) { 2559 // Evaluate the expression in the larger type. 2560 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2561 // If it folds to something simple, use it. Otherwise, don't. 2562 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2563 return getTruncateExpr(Fold, Ty); 2564 } 2565 } 2566 2567 if (Ops.size() == 2) { 2568 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2569 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2570 // C1). 2571 const SCEV *A = Ops[0]; 2572 const SCEV *B = Ops[1]; 2573 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2574 auto *C = dyn_cast<SCEVConstant>(A); 2575 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2576 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2577 auto C2 = C->getAPInt(); 2578 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2579 2580 APInt ConstAdd = C1 + C2; 2581 auto AddFlags = AddExpr->getNoWrapFlags(); 2582 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2583 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2584 ConstAdd.ule(C1)) { 2585 PreservedFlags = 2586 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2587 } 2588 2589 // Adding a constant with the same sign and small magnitude is NSW, if the 2590 // original AddExpr was NSW. 2591 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2592 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2593 ConstAdd.abs().ule(C1.abs())) { 2594 PreservedFlags = 2595 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2596 } 2597 2598 if (PreservedFlags != SCEV::FlagAnyWrap) { 2599 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2600 NewOps[0] = getConstant(ConstAdd); 2601 return getAddExpr(NewOps, PreservedFlags); 2602 } 2603 } 2604 } 2605 2606 // Skip past any other cast SCEVs. 2607 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2608 ++Idx; 2609 2610 // If there are add operands they would be next. 2611 if (Idx < Ops.size()) { 2612 bool DeletedAdd = false; 2613 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2614 // common NUW flag for expression after inlining. Other flags cannot be 2615 // preserved, because they may depend on the original order of operations. 2616 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2617 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2618 if (Ops.size() > AddOpsInlineThreshold || 2619 Add->getNumOperands() > AddOpsInlineThreshold) 2620 break; 2621 // If we have an add, expand the add operands onto the end of the operands 2622 // list. 2623 Ops.erase(Ops.begin()+Idx); 2624 Ops.append(Add->op_begin(), Add->op_end()); 2625 DeletedAdd = true; 2626 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2627 } 2628 2629 // If we deleted at least one add, we added operands to the end of the list, 2630 // and they are not necessarily sorted. Recurse to resort and resimplify 2631 // any operands we just acquired. 2632 if (DeletedAdd) 2633 return getAddExpr(Ops, CommonFlags, Depth + 1); 2634 } 2635 2636 // Skip over the add expression until we get to a multiply. 2637 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2638 ++Idx; 2639 2640 // Check to see if there are any folding opportunities present with 2641 // operands multiplied by constant values. 2642 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2643 uint64_t BitWidth = getTypeSizeInBits(Ty); 2644 DenseMap<const SCEV *, APInt> M; 2645 SmallVector<const SCEV *, 8> NewOps; 2646 APInt AccumulatedConstant(BitWidth, 0); 2647 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2648 Ops.data(), Ops.size(), 2649 APInt(BitWidth, 1), *this)) { 2650 struct APIntCompare { 2651 bool operator()(const APInt &LHS, const APInt &RHS) const { 2652 return LHS.ult(RHS); 2653 } 2654 }; 2655 2656 // Some interesting folding opportunity is present, so its worthwhile to 2657 // re-generate the operands list. Group the operands by constant scale, 2658 // to avoid multiplying by the same constant scale multiple times. 2659 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2660 for (const SCEV *NewOp : NewOps) 2661 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2662 // Re-generate the operands list. 2663 Ops.clear(); 2664 if (AccumulatedConstant != 0) 2665 Ops.push_back(getConstant(AccumulatedConstant)); 2666 for (auto &MulOp : MulOpLists) { 2667 if (MulOp.first == 1) { 2668 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2669 } else if (MulOp.first != 0) { 2670 Ops.push_back(getMulExpr( 2671 getConstant(MulOp.first), 2672 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2673 SCEV::FlagAnyWrap, Depth + 1)); 2674 } 2675 } 2676 if (Ops.empty()) 2677 return getZero(Ty); 2678 if (Ops.size() == 1) 2679 return Ops[0]; 2680 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2681 } 2682 } 2683 2684 // If we are adding something to a multiply expression, make sure the 2685 // something is not already an operand of the multiply. If so, merge it into 2686 // the multiply. 2687 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2688 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2689 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2690 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2691 if (isa<SCEVConstant>(MulOpSCEV)) 2692 continue; 2693 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2694 if (MulOpSCEV == Ops[AddOp]) { 2695 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2696 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2697 if (Mul->getNumOperands() != 2) { 2698 // If the multiply has more than two operands, we must get the 2699 // Y*Z term. 2700 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2701 Mul->op_begin()+MulOp); 2702 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2703 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2704 } 2705 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2706 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2707 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2708 SCEV::FlagAnyWrap, Depth + 1); 2709 if (Ops.size() == 2) return OuterMul; 2710 if (AddOp < Idx) { 2711 Ops.erase(Ops.begin()+AddOp); 2712 Ops.erase(Ops.begin()+Idx-1); 2713 } else { 2714 Ops.erase(Ops.begin()+Idx); 2715 Ops.erase(Ops.begin()+AddOp-1); 2716 } 2717 Ops.push_back(OuterMul); 2718 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2719 } 2720 2721 // Check this multiply against other multiplies being added together. 2722 for (unsigned OtherMulIdx = Idx+1; 2723 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2724 ++OtherMulIdx) { 2725 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2726 // If MulOp occurs in OtherMul, we can fold the two multiplies 2727 // together. 2728 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2729 OMulOp != e; ++OMulOp) 2730 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2731 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2732 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2733 if (Mul->getNumOperands() != 2) { 2734 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2735 Mul->op_begin()+MulOp); 2736 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2737 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2738 } 2739 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2740 if (OtherMul->getNumOperands() != 2) { 2741 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2742 OtherMul->op_begin()+OMulOp); 2743 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2744 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2745 } 2746 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2747 const SCEV *InnerMulSum = 2748 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2749 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2750 SCEV::FlagAnyWrap, Depth + 1); 2751 if (Ops.size() == 2) return OuterMul; 2752 Ops.erase(Ops.begin()+Idx); 2753 Ops.erase(Ops.begin()+OtherMulIdx-1); 2754 Ops.push_back(OuterMul); 2755 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2756 } 2757 } 2758 } 2759 } 2760 2761 // If there are any add recurrences in the operands list, see if any other 2762 // added values are loop invariant. If so, we can fold them into the 2763 // recurrence. 2764 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2765 ++Idx; 2766 2767 // Scan over all recurrences, trying to fold loop invariants into them. 2768 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2769 // Scan all of the other operands to this add and add them to the vector if 2770 // they are loop invariant w.r.t. the recurrence. 2771 SmallVector<const SCEV *, 8> LIOps; 2772 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2773 const Loop *AddRecLoop = AddRec->getLoop(); 2774 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2775 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2776 LIOps.push_back(Ops[i]); 2777 Ops.erase(Ops.begin()+i); 2778 --i; --e; 2779 } 2780 2781 // If we found some loop invariants, fold them into the recurrence. 2782 if (!LIOps.empty()) { 2783 // Compute nowrap flags for the addition of the loop-invariant ops and 2784 // the addrec. Temporarily push it as an operand for that purpose. 2785 LIOps.push_back(AddRec); 2786 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2787 LIOps.pop_back(); 2788 2789 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2790 LIOps.push_back(AddRec->getStart()); 2791 2792 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2793 // This follows from the fact that the no-wrap flags on the outer add 2794 // expression are applicable on the 0th iteration, when the add recurrence 2795 // will be equal to its start value. 2796 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2797 2798 // Build the new addrec. Propagate the NUW and NSW flags if both the 2799 // outer add and the inner addrec are guaranteed to have no overflow. 2800 // Always propagate NW. 2801 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2802 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2803 2804 // If all of the other operands were loop invariant, we are done. 2805 if (Ops.size() == 1) return NewRec; 2806 2807 // Otherwise, add the folded AddRec by the non-invariant parts. 2808 for (unsigned i = 0;; ++i) 2809 if (Ops[i] == AddRec) { 2810 Ops[i] = NewRec; 2811 break; 2812 } 2813 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2814 } 2815 2816 // Okay, if there weren't any loop invariants to be folded, check to see if 2817 // there are multiple AddRec's with the same loop induction variable being 2818 // added together. If so, we can fold them. 2819 for (unsigned OtherIdx = Idx+1; 2820 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2821 ++OtherIdx) { 2822 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2823 // so that the 1st found AddRecExpr is dominated by all others. 2824 assert(DT.dominates( 2825 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2826 AddRec->getLoop()->getHeader()) && 2827 "AddRecExprs are not sorted in reverse dominance order?"); 2828 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2829 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2830 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2831 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2832 ++OtherIdx) { 2833 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2834 if (OtherAddRec->getLoop() == AddRecLoop) { 2835 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2836 i != e; ++i) { 2837 if (i >= AddRecOps.size()) { 2838 AddRecOps.append(OtherAddRec->op_begin()+i, 2839 OtherAddRec->op_end()); 2840 break; 2841 } 2842 SmallVector<const SCEV *, 2> TwoOps = { 2843 AddRecOps[i], OtherAddRec->getOperand(i)}; 2844 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2845 } 2846 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2847 } 2848 } 2849 // Step size has changed, so we cannot guarantee no self-wraparound. 2850 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2851 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2852 } 2853 } 2854 2855 // Otherwise couldn't fold anything into this recurrence. Move onto the 2856 // next one. 2857 } 2858 2859 // Okay, it looks like we really DO need an add expr. Check to see if we 2860 // already have one, otherwise create a new one. 2861 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2862 } 2863 2864 const SCEV * 2865 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2866 SCEV::NoWrapFlags Flags) { 2867 FoldingSetNodeID ID; 2868 ID.AddInteger(scAddExpr); 2869 for (const SCEV *Op : Ops) 2870 ID.AddPointer(Op); 2871 void *IP = nullptr; 2872 SCEVAddExpr *S = 2873 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2874 if (!S) { 2875 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2876 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2877 S = new (SCEVAllocator) 2878 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2879 UniqueSCEVs.InsertNode(S, IP); 2880 addToLoopUseLists(S); 2881 } 2882 S->setNoWrapFlags(Flags); 2883 return S; 2884 } 2885 2886 const SCEV * 2887 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2888 const Loop *L, SCEV::NoWrapFlags Flags) { 2889 FoldingSetNodeID ID; 2890 ID.AddInteger(scAddRecExpr); 2891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2892 ID.AddPointer(Ops[i]); 2893 ID.AddPointer(L); 2894 void *IP = nullptr; 2895 SCEVAddRecExpr *S = 2896 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2897 if (!S) { 2898 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2899 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2900 S = new (SCEVAllocator) 2901 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2902 UniqueSCEVs.InsertNode(S, IP); 2903 addToLoopUseLists(S); 2904 } 2905 setNoWrapFlags(S, Flags); 2906 return S; 2907 } 2908 2909 const SCEV * 2910 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2911 SCEV::NoWrapFlags Flags) { 2912 FoldingSetNodeID ID; 2913 ID.AddInteger(scMulExpr); 2914 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2915 ID.AddPointer(Ops[i]); 2916 void *IP = nullptr; 2917 SCEVMulExpr *S = 2918 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2919 if (!S) { 2920 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2921 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2922 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2923 O, Ops.size()); 2924 UniqueSCEVs.InsertNode(S, IP); 2925 addToLoopUseLists(S); 2926 } 2927 S->setNoWrapFlags(Flags); 2928 return S; 2929 } 2930 2931 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2932 uint64_t k = i*j; 2933 if (j > 1 && k / j != i) Overflow = true; 2934 return k; 2935 } 2936 2937 /// Compute the result of "n choose k", the binomial coefficient. If an 2938 /// intermediate computation overflows, Overflow will be set and the return will 2939 /// be garbage. Overflow is not cleared on absence of overflow. 2940 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2941 // We use the multiplicative formula: 2942 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2943 // At each iteration, we take the n-th term of the numeral and divide by the 2944 // (k-n)th term of the denominator. This division will always produce an 2945 // integral result, and helps reduce the chance of overflow in the 2946 // intermediate computations. However, we can still overflow even when the 2947 // final result would fit. 2948 2949 if (n == 0 || n == k) return 1; 2950 if (k > n) return 0; 2951 2952 if (k > n/2) 2953 k = n-k; 2954 2955 uint64_t r = 1; 2956 for (uint64_t i = 1; i <= k; ++i) { 2957 r = umul_ov(r, n-(i-1), Overflow); 2958 r /= i; 2959 } 2960 return r; 2961 } 2962 2963 /// Determine if any of the operands in this SCEV are a constant or if 2964 /// any of the add or multiply expressions in this SCEV contain a constant. 2965 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2966 struct FindConstantInAddMulChain { 2967 bool FoundConstant = false; 2968 2969 bool follow(const SCEV *S) { 2970 FoundConstant |= isa<SCEVConstant>(S); 2971 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2972 } 2973 2974 bool isDone() const { 2975 return FoundConstant; 2976 } 2977 }; 2978 2979 FindConstantInAddMulChain F; 2980 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2981 ST.visitAll(StartExpr); 2982 return F.FoundConstant; 2983 } 2984 2985 /// Get a canonical multiply expression, or something simpler if possible. 2986 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2987 SCEV::NoWrapFlags OrigFlags, 2988 unsigned Depth) { 2989 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2990 "only nuw or nsw allowed"); 2991 assert(!Ops.empty() && "Cannot get empty mul!"); 2992 if (Ops.size() == 1) return Ops[0]; 2993 #ifndef NDEBUG 2994 Type *ETy = Ops[0]->getType(); 2995 assert(!ETy->isPointerTy()); 2996 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2997 assert(Ops[i]->getType() == ETy && 2998 "SCEVMulExpr operand types don't match!"); 2999 #endif 3000 3001 // Sort by complexity, this groups all similar expression types together. 3002 GroupByComplexity(Ops, &LI, DT); 3003 3004 // If there are any constants, fold them together. 3005 unsigned Idx = 0; 3006 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3007 ++Idx; 3008 assert(Idx < Ops.size()); 3009 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3010 // We found two constants, fold them together! 3011 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3012 if (Ops.size() == 2) return Ops[0]; 3013 Ops.erase(Ops.begin()+1); // Erase the folded element 3014 LHSC = cast<SCEVConstant>(Ops[0]); 3015 } 3016 3017 // If we have a multiply of zero, it will always be zero. 3018 if (LHSC->getValue()->isZero()) 3019 return LHSC; 3020 3021 // If we are left with a constant one being multiplied, strip it off. 3022 if (LHSC->getValue()->isOne()) { 3023 Ops.erase(Ops.begin()); 3024 --Idx; 3025 } 3026 3027 if (Ops.size() == 1) 3028 return Ops[0]; 3029 } 3030 3031 // Delay expensive flag strengthening until necessary. 3032 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3033 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3034 }; 3035 3036 // Limit recursion calls depth. 3037 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3038 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3039 3040 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3041 // Don't strengthen flags if we have no new information. 3042 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3043 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3044 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3045 return S; 3046 } 3047 3048 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3049 if (Ops.size() == 2) { 3050 // C1*(C2+V) -> C1*C2 + C1*V 3051 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3052 // If any of Add's ops are Adds or Muls with a constant, apply this 3053 // transformation as well. 3054 // 3055 // TODO: There are some cases where this transformation is not 3056 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3057 // this transformation should be narrowed down. 3058 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3059 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3060 SCEV::FlagAnyWrap, Depth + 1), 3061 getMulExpr(LHSC, Add->getOperand(1), 3062 SCEV::FlagAnyWrap, Depth + 1), 3063 SCEV::FlagAnyWrap, Depth + 1); 3064 3065 if (Ops[0]->isAllOnesValue()) { 3066 // If we have a mul by -1 of an add, try distributing the -1 among the 3067 // add operands. 3068 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3069 SmallVector<const SCEV *, 4> NewOps; 3070 bool AnyFolded = false; 3071 for (const SCEV *AddOp : Add->operands()) { 3072 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3073 Depth + 1); 3074 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3075 NewOps.push_back(Mul); 3076 } 3077 if (AnyFolded) 3078 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3079 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3080 // Negation preserves a recurrence's no self-wrap property. 3081 SmallVector<const SCEV *, 4> Operands; 3082 for (const SCEV *AddRecOp : AddRec->operands()) 3083 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3084 Depth + 1)); 3085 3086 return getAddRecExpr(Operands, AddRec->getLoop(), 3087 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3088 } 3089 } 3090 } 3091 } 3092 3093 // Skip over the add expression until we get to a multiply. 3094 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3095 ++Idx; 3096 3097 // If there are mul operands inline them all into this expression. 3098 if (Idx < Ops.size()) { 3099 bool DeletedMul = false; 3100 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3101 if (Ops.size() > MulOpsInlineThreshold) 3102 break; 3103 // If we have an mul, expand the mul operands onto the end of the 3104 // operands list. 3105 Ops.erase(Ops.begin()+Idx); 3106 Ops.append(Mul->op_begin(), Mul->op_end()); 3107 DeletedMul = true; 3108 } 3109 3110 // If we deleted at least one mul, we added operands to the end of the 3111 // list, and they are not necessarily sorted. Recurse to resort and 3112 // resimplify any operands we just acquired. 3113 if (DeletedMul) 3114 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3115 } 3116 3117 // If there are any add recurrences in the operands list, see if any other 3118 // added values are loop invariant. If so, we can fold them into the 3119 // recurrence. 3120 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3121 ++Idx; 3122 3123 // Scan over all recurrences, trying to fold loop invariants into them. 3124 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3125 // Scan all of the other operands to this mul and add them to the vector 3126 // if they are loop invariant w.r.t. the recurrence. 3127 SmallVector<const SCEV *, 8> LIOps; 3128 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3129 const Loop *AddRecLoop = AddRec->getLoop(); 3130 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3131 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3132 LIOps.push_back(Ops[i]); 3133 Ops.erase(Ops.begin()+i); 3134 --i; --e; 3135 } 3136 3137 // If we found some loop invariants, fold them into the recurrence. 3138 if (!LIOps.empty()) { 3139 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3140 SmallVector<const SCEV *, 4> NewOps; 3141 NewOps.reserve(AddRec->getNumOperands()); 3142 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3143 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3144 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3145 SCEV::FlagAnyWrap, Depth + 1)); 3146 3147 // Build the new addrec. Propagate the NUW and NSW flags if both the 3148 // outer mul and the inner addrec are guaranteed to have no overflow. 3149 // 3150 // No self-wrap cannot be guaranteed after changing the step size, but 3151 // will be inferred if either NUW or NSW is true. 3152 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3153 const SCEV *NewRec = getAddRecExpr( 3154 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3155 3156 // If all of the other operands were loop invariant, we are done. 3157 if (Ops.size() == 1) return NewRec; 3158 3159 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3160 for (unsigned i = 0;; ++i) 3161 if (Ops[i] == AddRec) { 3162 Ops[i] = NewRec; 3163 break; 3164 } 3165 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3166 } 3167 3168 // Okay, if there weren't any loop invariants to be folded, check to see 3169 // if there are multiple AddRec's with the same loop induction variable 3170 // being multiplied together. If so, we can fold them. 3171 3172 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3173 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3174 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3175 // ]]],+,...up to x=2n}. 3176 // Note that the arguments to choose() are always integers with values 3177 // known at compile time, never SCEV objects. 3178 // 3179 // The implementation avoids pointless extra computations when the two 3180 // addrec's are of different length (mathematically, it's equivalent to 3181 // an infinite stream of zeros on the right). 3182 bool OpsModified = false; 3183 for (unsigned OtherIdx = Idx+1; 3184 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3185 ++OtherIdx) { 3186 const SCEVAddRecExpr *OtherAddRec = 3187 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3188 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3189 continue; 3190 3191 // Limit max number of arguments to avoid creation of unreasonably big 3192 // SCEVAddRecs with very complex operands. 3193 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3194 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3195 continue; 3196 3197 bool Overflow = false; 3198 Type *Ty = AddRec->getType(); 3199 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3200 SmallVector<const SCEV*, 7> AddRecOps; 3201 for (int x = 0, xe = AddRec->getNumOperands() + 3202 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3203 SmallVector <const SCEV *, 7> SumOps; 3204 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3205 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3206 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3207 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3208 z < ze && !Overflow; ++z) { 3209 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3210 uint64_t Coeff; 3211 if (LargerThan64Bits) 3212 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3213 else 3214 Coeff = Coeff1*Coeff2; 3215 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3216 const SCEV *Term1 = AddRec->getOperand(y-z); 3217 const SCEV *Term2 = OtherAddRec->getOperand(z); 3218 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3219 SCEV::FlagAnyWrap, Depth + 1)); 3220 } 3221 } 3222 if (SumOps.empty()) 3223 SumOps.push_back(getZero(Ty)); 3224 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3225 } 3226 if (!Overflow) { 3227 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3228 SCEV::FlagAnyWrap); 3229 if (Ops.size() == 2) return NewAddRec; 3230 Ops[Idx] = NewAddRec; 3231 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3232 OpsModified = true; 3233 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3234 if (!AddRec) 3235 break; 3236 } 3237 } 3238 if (OpsModified) 3239 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3240 3241 // Otherwise couldn't fold anything into this recurrence. Move onto the 3242 // next one. 3243 } 3244 3245 // Okay, it looks like we really DO need an mul expr. Check to see if we 3246 // already have one, otherwise create a new one. 3247 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3248 } 3249 3250 /// Represents an unsigned remainder expression based on unsigned division. 3251 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3252 const SCEV *RHS) { 3253 assert(getEffectiveSCEVType(LHS->getType()) == 3254 getEffectiveSCEVType(RHS->getType()) && 3255 "SCEVURemExpr operand types don't match!"); 3256 3257 // Short-circuit easy cases 3258 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3259 // If constant is one, the result is trivial 3260 if (RHSC->getValue()->isOne()) 3261 return getZero(LHS->getType()); // X urem 1 --> 0 3262 3263 // If constant is a power of two, fold into a zext(trunc(LHS)). 3264 if (RHSC->getAPInt().isPowerOf2()) { 3265 Type *FullTy = LHS->getType(); 3266 Type *TruncTy = 3267 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3268 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3269 } 3270 } 3271 3272 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3273 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3274 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3275 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3276 } 3277 3278 /// Get a canonical unsigned division expression, or something simpler if 3279 /// possible. 3280 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3281 const SCEV *RHS) { 3282 assert(!LHS->getType()->isPointerTy() && 3283 "SCEVUDivExpr operand can't be pointer!"); 3284 assert(LHS->getType() == RHS->getType() && 3285 "SCEVUDivExpr operand types don't match!"); 3286 3287 FoldingSetNodeID ID; 3288 ID.AddInteger(scUDivExpr); 3289 ID.AddPointer(LHS); 3290 ID.AddPointer(RHS); 3291 void *IP = nullptr; 3292 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3293 return S; 3294 3295 // 0 udiv Y == 0 3296 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3297 if (LHSC->getValue()->isZero()) 3298 return LHS; 3299 3300 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3301 if (RHSC->getValue()->isOne()) 3302 return LHS; // X udiv 1 --> x 3303 // If the denominator is zero, the result of the udiv is undefined. Don't 3304 // try to analyze it, because the resolution chosen here may differ from 3305 // the resolution chosen in other parts of the compiler. 3306 if (!RHSC->getValue()->isZero()) { 3307 // Determine if the division can be folded into the operands of 3308 // its operands. 3309 // TODO: Generalize this to non-constants by using known-bits information. 3310 Type *Ty = LHS->getType(); 3311 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3312 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3313 // For non-power-of-two values, effectively round the value up to the 3314 // nearest power of two. 3315 if (!RHSC->getAPInt().isPowerOf2()) 3316 ++MaxShiftAmt; 3317 IntegerType *ExtTy = 3318 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3319 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3320 if (const SCEVConstant *Step = 3321 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3322 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3323 const APInt &StepInt = Step->getAPInt(); 3324 const APInt &DivInt = RHSC->getAPInt(); 3325 if (!StepInt.urem(DivInt) && 3326 getZeroExtendExpr(AR, ExtTy) == 3327 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3328 getZeroExtendExpr(Step, ExtTy), 3329 AR->getLoop(), SCEV::FlagAnyWrap)) { 3330 SmallVector<const SCEV *, 4> Operands; 3331 for (const SCEV *Op : AR->operands()) 3332 Operands.push_back(getUDivExpr(Op, RHS)); 3333 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3334 } 3335 /// Get a canonical UDivExpr for a recurrence. 3336 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3337 // We can currently only fold X%N if X is constant. 3338 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3339 if (StartC && !DivInt.urem(StepInt) && 3340 getZeroExtendExpr(AR, ExtTy) == 3341 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3342 getZeroExtendExpr(Step, ExtTy), 3343 AR->getLoop(), SCEV::FlagAnyWrap)) { 3344 const APInt &StartInt = StartC->getAPInt(); 3345 const APInt &StartRem = StartInt.urem(StepInt); 3346 if (StartRem != 0) { 3347 const SCEV *NewLHS = 3348 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3349 AR->getLoop(), SCEV::FlagNW); 3350 if (LHS != NewLHS) { 3351 LHS = NewLHS; 3352 3353 // Reset the ID to include the new LHS, and check if it is 3354 // already cached. 3355 ID.clear(); 3356 ID.AddInteger(scUDivExpr); 3357 ID.AddPointer(LHS); 3358 ID.AddPointer(RHS); 3359 IP = nullptr; 3360 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3361 return S; 3362 } 3363 } 3364 } 3365 } 3366 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3367 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3368 SmallVector<const SCEV *, 4> Operands; 3369 for (const SCEV *Op : M->operands()) 3370 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3371 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3372 // Find an operand that's safely divisible. 3373 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3374 const SCEV *Op = M->getOperand(i); 3375 const SCEV *Div = getUDivExpr(Op, RHSC); 3376 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3377 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3378 Operands[i] = Div; 3379 return getMulExpr(Operands); 3380 } 3381 } 3382 } 3383 3384 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3385 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3386 if (auto *DivisorConstant = 3387 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3388 bool Overflow = false; 3389 APInt NewRHS = 3390 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3391 if (Overflow) { 3392 return getConstant(RHSC->getType(), 0, false); 3393 } 3394 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3395 } 3396 } 3397 3398 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3399 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3400 SmallVector<const SCEV *, 4> Operands; 3401 for (const SCEV *Op : A->operands()) 3402 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3403 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3404 Operands.clear(); 3405 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3406 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3407 if (isa<SCEVUDivExpr>(Op) || 3408 getMulExpr(Op, RHS) != A->getOperand(i)) 3409 break; 3410 Operands.push_back(Op); 3411 } 3412 if (Operands.size() == A->getNumOperands()) 3413 return getAddExpr(Operands); 3414 } 3415 } 3416 3417 // Fold if both operands are constant. 3418 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3419 Constant *LHSCV = LHSC->getValue(); 3420 Constant *RHSCV = RHSC->getValue(); 3421 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3422 RHSCV))); 3423 } 3424 } 3425 } 3426 3427 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3428 // changes). Make sure we get a new one. 3429 IP = nullptr; 3430 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3431 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3432 LHS, RHS); 3433 UniqueSCEVs.InsertNode(S, IP); 3434 addToLoopUseLists(S); 3435 return S; 3436 } 3437 3438 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3439 APInt A = C1->getAPInt().abs(); 3440 APInt B = C2->getAPInt().abs(); 3441 uint32_t ABW = A.getBitWidth(); 3442 uint32_t BBW = B.getBitWidth(); 3443 3444 if (ABW > BBW) 3445 B = B.zext(ABW); 3446 else if (ABW < BBW) 3447 A = A.zext(BBW); 3448 3449 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3450 } 3451 3452 /// Get a canonical unsigned division expression, or something simpler if 3453 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3454 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3455 /// it's not exact because the udiv may be clearing bits. 3456 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3457 const SCEV *RHS) { 3458 // TODO: we could try to find factors in all sorts of things, but for now we 3459 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3460 // end of this file for inspiration. 3461 3462 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3463 if (!Mul || !Mul->hasNoUnsignedWrap()) 3464 return getUDivExpr(LHS, RHS); 3465 3466 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3467 // If the mulexpr multiplies by a constant, then that constant must be the 3468 // first element of the mulexpr. 3469 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3470 if (LHSCst == RHSCst) { 3471 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3472 return getMulExpr(Operands); 3473 } 3474 3475 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3476 // that there's a factor provided by one of the other terms. We need to 3477 // check. 3478 APInt Factor = gcd(LHSCst, RHSCst); 3479 if (!Factor.isIntN(1)) { 3480 LHSCst = 3481 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3482 RHSCst = 3483 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3484 SmallVector<const SCEV *, 2> Operands; 3485 Operands.push_back(LHSCst); 3486 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3487 LHS = getMulExpr(Operands); 3488 RHS = RHSCst; 3489 Mul = dyn_cast<SCEVMulExpr>(LHS); 3490 if (!Mul) 3491 return getUDivExactExpr(LHS, RHS); 3492 } 3493 } 3494 } 3495 3496 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3497 if (Mul->getOperand(i) == RHS) { 3498 SmallVector<const SCEV *, 2> Operands; 3499 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3500 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3501 return getMulExpr(Operands); 3502 } 3503 } 3504 3505 return getUDivExpr(LHS, RHS); 3506 } 3507 3508 /// Get an add recurrence expression for the specified loop. Simplify the 3509 /// expression as much as possible. 3510 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3511 const Loop *L, 3512 SCEV::NoWrapFlags Flags) { 3513 SmallVector<const SCEV *, 4> Operands; 3514 Operands.push_back(Start); 3515 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3516 if (StepChrec->getLoop() == L) { 3517 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3518 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3519 } 3520 3521 Operands.push_back(Step); 3522 return getAddRecExpr(Operands, L, Flags); 3523 } 3524 3525 /// Get an add recurrence expression for the specified loop. Simplify the 3526 /// expression as much as possible. 3527 const SCEV * 3528 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3529 const Loop *L, SCEV::NoWrapFlags Flags) { 3530 if (Operands.size() == 1) return Operands[0]; 3531 #ifndef NDEBUG 3532 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3533 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3534 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3535 "SCEVAddRecExpr operand types don't match!"); 3536 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3537 } 3538 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3539 assert(isLoopInvariant(Operands[i], L) && 3540 "SCEVAddRecExpr operand is not loop-invariant!"); 3541 #endif 3542 3543 if (Operands.back()->isZero()) { 3544 Operands.pop_back(); 3545 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3546 } 3547 3548 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3549 // use that information to infer NUW and NSW flags. However, computing a 3550 // BE count requires calling getAddRecExpr, so we may not yet have a 3551 // meaningful BE count at this point (and if we don't, we'd be stuck 3552 // with a SCEVCouldNotCompute as the cached BE count). 3553 3554 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3555 3556 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3557 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3558 const Loop *NestedLoop = NestedAR->getLoop(); 3559 if (L->contains(NestedLoop) 3560 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3561 : (!NestedLoop->contains(L) && 3562 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3563 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3564 Operands[0] = NestedAR->getStart(); 3565 // AddRecs require their operands be loop-invariant with respect to their 3566 // loops. Don't perform this transformation if it would break this 3567 // requirement. 3568 bool AllInvariant = all_of( 3569 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3570 3571 if (AllInvariant) { 3572 // Create a recurrence for the outer loop with the same step size. 3573 // 3574 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3575 // inner recurrence has the same property. 3576 SCEV::NoWrapFlags OuterFlags = 3577 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3578 3579 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3580 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3581 return isLoopInvariant(Op, NestedLoop); 3582 }); 3583 3584 if (AllInvariant) { 3585 // Ok, both add recurrences are valid after the transformation. 3586 // 3587 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3588 // the outer recurrence has the same property. 3589 SCEV::NoWrapFlags InnerFlags = 3590 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3591 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3592 } 3593 } 3594 // Reset Operands to its original state. 3595 Operands[0] = NestedAR; 3596 } 3597 } 3598 3599 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3600 // already have one, otherwise create a new one. 3601 return getOrCreateAddRecExpr(Operands, L, Flags); 3602 } 3603 3604 const SCEV * 3605 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3606 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3607 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3608 // getSCEV(Base)->getType() has the same address space as Base->getType() 3609 // because SCEV::getType() preserves the address space. 3610 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3611 const bool AssumeInBoundsFlags = [&]() { 3612 if (!GEP->isInBounds()) 3613 return false; 3614 3615 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3616 // but to do that, we have to ensure that said flag is valid in the entire 3617 // defined scope of the SCEV. 3618 auto *GEPI = dyn_cast<Instruction>(GEP); 3619 // TODO: non-instructions have global scope. We might be able to prove 3620 // some global scope cases 3621 return GEPI && isSCEVExprNeverPoison(GEPI); 3622 }(); 3623 3624 SCEV::NoWrapFlags OffsetWrap = 3625 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3626 3627 Type *CurTy = GEP->getType(); 3628 bool FirstIter = true; 3629 SmallVector<const SCEV *, 4> Offsets; 3630 for (const SCEV *IndexExpr : IndexExprs) { 3631 // Compute the (potentially symbolic) offset in bytes for this index. 3632 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3633 // For a struct, add the member offset. 3634 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3635 unsigned FieldNo = Index->getZExtValue(); 3636 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3637 Offsets.push_back(FieldOffset); 3638 3639 // Update CurTy to the type of the field at Index. 3640 CurTy = STy->getTypeAtIndex(Index); 3641 } else { 3642 // Update CurTy to its element type. 3643 if (FirstIter) { 3644 assert(isa<PointerType>(CurTy) && 3645 "The first index of a GEP indexes a pointer"); 3646 CurTy = GEP->getSourceElementType(); 3647 FirstIter = false; 3648 } else { 3649 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3650 } 3651 // For an array, add the element offset, explicitly scaled. 3652 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3653 // Getelementptr indices are signed. 3654 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3655 3656 // Multiply the index by the element size to compute the element offset. 3657 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3658 Offsets.push_back(LocalOffset); 3659 } 3660 } 3661 3662 // Handle degenerate case of GEP without offsets. 3663 if (Offsets.empty()) 3664 return BaseExpr; 3665 3666 // Add the offsets together, assuming nsw if inbounds. 3667 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3668 // Add the base address and the offset. We cannot use the nsw flag, as the 3669 // base address is unsigned. However, if we know that the offset is 3670 // non-negative, we can use nuw. 3671 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3672 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3673 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3674 assert(BaseExpr->getType() == GEPExpr->getType() && 3675 "GEP should not change type mid-flight."); 3676 return GEPExpr; 3677 } 3678 3679 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3680 ArrayRef<const SCEV *> Ops) { 3681 FoldingSetNodeID ID; 3682 ID.AddInteger(SCEVType); 3683 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3684 ID.AddPointer(Ops[i]); 3685 void *IP = nullptr; 3686 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3687 } 3688 3689 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3690 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3691 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3692 } 3693 3694 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3695 SmallVectorImpl<const SCEV *> &Ops) { 3696 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3697 if (Ops.size() == 1) return Ops[0]; 3698 #ifndef NDEBUG 3699 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3700 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3701 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3702 "Operand types don't match!"); 3703 assert(Ops[0]->getType()->isPointerTy() == 3704 Ops[i]->getType()->isPointerTy() && 3705 "min/max should be consistently pointerish"); 3706 } 3707 #endif 3708 3709 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3710 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3711 3712 // Sort by complexity, this groups all similar expression types together. 3713 GroupByComplexity(Ops, &LI, DT); 3714 3715 // Check if we have created the same expression before. 3716 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3717 return S; 3718 } 3719 3720 // If there are any constants, fold them together. 3721 unsigned Idx = 0; 3722 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3723 ++Idx; 3724 assert(Idx < Ops.size()); 3725 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3726 if (Kind == scSMaxExpr) 3727 return APIntOps::smax(LHS, RHS); 3728 else if (Kind == scSMinExpr) 3729 return APIntOps::smin(LHS, RHS); 3730 else if (Kind == scUMaxExpr) 3731 return APIntOps::umax(LHS, RHS); 3732 else if (Kind == scUMinExpr) 3733 return APIntOps::umin(LHS, RHS); 3734 llvm_unreachable("Unknown SCEV min/max opcode"); 3735 }; 3736 3737 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3738 // We found two constants, fold them together! 3739 ConstantInt *Fold = ConstantInt::get( 3740 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3741 Ops[0] = getConstant(Fold); 3742 Ops.erase(Ops.begin()+1); // Erase the folded element 3743 if (Ops.size() == 1) return Ops[0]; 3744 LHSC = cast<SCEVConstant>(Ops[0]); 3745 } 3746 3747 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3748 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3749 3750 if (IsMax ? IsMinV : IsMaxV) { 3751 // If we are left with a constant minimum(/maximum)-int, strip it off. 3752 Ops.erase(Ops.begin()); 3753 --Idx; 3754 } else if (IsMax ? IsMaxV : IsMinV) { 3755 // If we have a max(/min) with a constant maximum(/minimum)-int, 3756 // it will always be the extremum. 3757 return LHSC; 3758 } 3759 3760 if (Ops.size() == 1) return Ops[0]; 3761 } 3762 3763 // Find the first operation of the same kind 3764 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3765 ++Idx; 3766 3767 // Check to see if one of the operands is of the same kind. If so, expand its 3768 // operands onto our operand list, and recurse to simplify. 3769 if (Idx < Ops.size()) { 3770 bool DeletedAny = false; 3771 while (Ops[Idx]->getSCEVType() == Kind) { 3772 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3773 Ops.erase(Ops.begin()+Idx); 3774 Ops.append(SMME->op_begin(), SMME->op_end()); 3775 DeletedAny = true; 3776 } 3777 3778 if (DeletedAny) 3779 return getMinMaxExpr(Kind, Ops); 3780 } 3781 3782 // Okay, check to see if the same value occurs in the operand list twice. If 3783 // so, delete one. Since we sorted the list, these values are required to 3784 // be adjacent. 3785 llvm::CmpInst::Predicate GEPred = 3786 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3787 llvm::CmpInst::Predicate LEPred = 3788 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3789 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3790 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3791 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3792 if (Ops[i] == Ops[i + 1] || 3793 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3794 // X op Y op Y --> X op Y 3795 // X op Y --> X, if we know X, Y are ordered appropriately 3796 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3797 --i; 3798 --e; 3799 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3800 Ops[i + 1])) { 3801 // X op Y --> Y, if we know X, Y are ordered appropriately 3802 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3803 --i; 3804 --e; 3805 } 3806 } 3807 3808 if (Ops.size() == 1) return Ops[0]; 3809 3810 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3811 3812 // Okay, it looks like we really DO need an expr. Check to see if we 3813 // already have one, otherwise create a new one. 3814 FoldingSetNodeID ID; 3815 ID.AddInteger(Kind); 3816 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3817 ID.AddPointer(Ops[i]); 3818 void *IP = nullptr; 3819 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3820 if (ExistingSCEV) 3821 return ExistingSCEV; 3822 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3823 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3824 SCEV *S = new (SCEVAllocator) 3825 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3826 3827 UniqueSCEVs.InsertNode(S, IP); 3828 addToLoopUseLists(S); 3829 return S; 3830 } 3831 3832 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3833 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3834 return getSMaxExpr(Ops); 3835 } 3836 3837 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3838 return getMinMaxExpr(scSMaxExpr, Ops); 3839 } 3840 3841 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3842 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3843 return getUMaxExpr(Ops); 3844 } 3845 3846 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3847 return getMinMaxExpr(scUMaxExpr, Ops); 3848 } 3849 3850 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3851 const SCEV *RHS) { 3852 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3853 return getSMinExpr(Ops); 3854 } 3855 3856 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3857 return getMinMaxExpr(scSMinExpr, Ops); 3858 } 3859 3860 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3861 const SCEV *RHS) { 3862 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3863 return getUMinExpr(Ops); 3864 } 3865 3866 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3867 return getMinMaxExpr(scUMinExpr, Ops); 3868 } 3869 3870 const SCEV * 3871 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3872 ScalableVectorType *ScalableTy) { 3873 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3874 Constant *One = ConstantInt::get(IntTy, 1); 3875 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3876 // Note that the expression we created is the final expression, we don't 3877 // want to simplify it any further Also, if we call a normal getSCEV(), 3878 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3879 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3880 } 3881 3882 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3883 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3884 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3885 // We can bypass creating a target-independent constant expression and then 3886 // folding it back into a ConstantInt. This is just a compile-time 3887 // optimization. 3888 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3889 } 3890 3891 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3892 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3893 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3894 // We can bypass creating a target-independent constant expression and then 3895 // folding it back into a ConstantInt. This is just a compile-time 3896 // optimization. 3897 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3898 } 3899 3900 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3901 StructType *STy, 3902 unsigned FieldNo) { 3903 // We can bypass creating a target-independent constant expression and then 3904 // folding it back into a ConstantInt. This is just a compile-time 3905 // optimization. 3906 return getConstant( 3907 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3908 } 3909 3910 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3911 // Don't attempt to do anything other than create a SCEVUnknown object 3912 // here. createSCEV only calls getUnknown after checking for all other 3913 // interesting possibilities, and any other code that calls getUnknown 3914 // is doing so in order to hide a value from SCEV canonicalization. 3915 3916 FoldingSetNodeID ID; 3917 ID.AddInteger(scUnknown); 3918 ID.AddPointer(V); 3919 void *IP = nullptr; 3920 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3921 assert(cast<SCEVUnknown>(S)->getValue() == V && 3922 "Stale SCEVUnknown in uniquing map!"); 3923 return S; 3924 } 3925 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3926 FirstUnknown); 3927 FirstUnknown = cast<SCEVUnknown>(S); 3928 UniqueSCEVs.InsertNode(S, IP); 3929 return S; 3930 } 3931 3932 //===----------------------------------------------------------------------===// 3933 // Basic SCEV Analysis and PHI Idiom Recognition Code 3934 // 3935 3936 /// Test if values of the given type are analyzable within the SCEV 3937 /// framework. This primarily includes integer types, and it can optionally 3938 /// include pointer types if the ScalarEvolution class has access to 3939 /// target-specific information. 3940 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3941 // Integers and pointers are always SCEVable. 3942 return Ty->isIntOrPtrTy(); 3943 } 3944 3945 /// Return the size in bits of the specified type, for which isSCEVable must 3946 /// return true. 3947 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3948 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3949 if (Ty->isPointerTy()) 3950 return getDataLayout().getIndexTypeSizeInBits(Ty); 3951 return getDataLayout().getTypeSizeInBits(Ty); 3952 } 3953 3954 /// Return a type with the same bitwidth as the given type and which represents 3955 /// how SCEV will treat the given type, for which isSCEVable must return 3956 /// true. For pointer types, this is the pointer index sized integer type. 3957 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3958 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3959 3960 if (Ty->isIntegerTy()) 3961 return Ty; 3962 3963 // The only other support type is pointer. 3964 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3965 return getDataLayout().getIndexType(Ty); 3966 } 3967 3968 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3969 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3970 } 3971 3972 const SCEV *ScalarEvolution::getCouldNotCompute() { 3973 return CouldNotCompute.get(); 3974 } 3975 3976 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3977 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3978 auto *SU = dyn_cast<SCEVUnknown>(S); 3979 return SU && SU->getValue() == nullptr; 3980 }); 3981 3982 return !ContainsNulls; 3983 } 3984 3985 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3986 HasRecMapType::iterator I = HasRecMap.find(S); 3987 if (I != HasRecMap.end()) 3988 return I->second; 3989 3990 bool FoundAddRec = 3991 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3992 HasRecMap.insert({S, FoundAddRec}); 3993 return FoundAddRec; 3994 } 3995 3996 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3997 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3998 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3999 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4000 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4001 if (!Add) 4002 return {S, nullptr}; 4003 4004 if (Add->getNumOperands() != 2) 4005 return {S, nullptr}; 4006 4007 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4008 if (!ConstOp) 4009 return {S, nullptr}; 4010 4011 return {Add->getOperand(1), ConstOp->getValue()}; 4012 } 4013 4014 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4015 /// by the value and offset from any ValueOffsetPair in the set. 4016 ScalarEvolution::ValueOffsetPairSetVector * 4017 ScalarEvolution::getSCEVValues(const SCEV *S) { 4018 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4019 if (SI == ExprValueMap.end()) 4020 return nullptr; 4021 #ifndef NDEBUG 4022 if (VerifySCEVMap) { 4023 // Check there is no dangling Value in the set returned. 4024 for (const auto &VE : SI->second) 4025 assert(ValueExprMap.count(VE.first)); 4026 } 4027 #endif 4028 return &SI->second; 4029 } 4030 4031 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4032 /// cannot be used separately. eraseValueFromMap should be used to remove 4033 /// V from ValueExprMap and ExprValueMap at the same time. 4034 void ScalarEvolution::eraseValueFromMap(Value *V) { 4035 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4036 if (I != ValueExprMap.end()) { 4037 const SCEV *S = I->second; 4038 // Remove {V, 0} from the set of ExprValueMap[S] 4039 if (auto *SV = getSCEVValues(S)) 4040 SV->remove({V, nullptr}); 4041 4042 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4043 const SCEV *Stripped; 4044 ConstantInt *Offset; 4045 std::tie(Stripped, Offset) = splitAddExpr(S); 4046 if (Offset != nullptr) { 4047 if (auto *SV = getSCEVValues(Stripped)) 4048 SV->remove({V, Offset}); 4049 } 4050 ValueExprMap.erase(V); 4051 } 4052 } 4053 4054 /// Check whether value has nuw/nsw/exact set but SCEV does not. 4055 /// TODO: In reality it is better to check the poison recursively 4056 /// but this is better than nothing. 4057 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 4058 if (auto *I = dyn_cast<Instruction>(V)) { 4059 if (isa<OverflowingBinaryOperator>(I)) { 4060 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 4061 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 4062 return true; 4063 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 4064 return true; 4065 } 4066 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 4067 return true; 4068 } 4069 return false; 4070 } 4071 4072 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4073 /// create a new one. 4074 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4075 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4076 4077 const SCEV *S = getExistingSCEV(V); 4078 if (S == nullptr) { 4079 S = createSCEV(V); 4080 // During PHI resolution, it is possible to create two SCEVs for the same 4081 // V, so it is needed to double check whether V->S is inserted into 4082 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4083 std::pair<ValueExprMapType::iterator, bool> Pair = 4084 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4085 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 4086 ExprValueMap[S].insert({V, nullptr}); 4087 4088 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4089 // ExprValueMap. 4090 const SCEV *Stripped = S; 4091 ConstantInt *Offset = nullptr; 4092 std::tie(Stripped, Offset) = splitAddExpr(S); 4093 // If stripped is SCEVUnknown, don't bother to save 4094 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4095 // increase the complexity of the expansion code. 4096 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4097 // because it may generate add/sub instead of GEP in SCEV expansion. 4098 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4099 !isa<GetElementPtrInst>(V)) 4100 ExprValueMap[Stripped].insert({V, Offset}); 4101 } 4102 } 4103 return S; 4104 } 4105 4106 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4107 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4108 4109 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4110 if (I != ValueExprMap.end()) { 4111 const SCEV *S = I->second; 4112 if (checkValidity(S)) 4113 return S; 4114 eraseValueFromMap(V); 4115 forgetMemoizedResults(S); 4116 } 4117 return nullptr; 4118 } 4119 4120 /// Return a SCEV corresponding to -V = -1*V 4121 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4122 SCEV::NoWrapFlags Flags) { 4123 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4124 return getConstant( 4125 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4126 4127 Type *Ty = V->getType(); 4128 Ty = getEffectiveSCEVType(Ty); 4129 return getMulExpr(V, getMinusOne(Ty), Flags); 4130 } 4131 4132 /// If Expr computes ~A, return A else return nullptr 4133 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4134 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4135 if (!Add || Add->getNumOperands() != 2 || 4136 !Add->getOperand(0)->isAllOnesValue()) 4137 return nullptr; 4138 4139 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4140 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4141 !AddRHS->getOperand(0)->isAllOnesValue()) 4142 return nullptr; 4143 4144 return AddRHS->getOperand(1); 4145 } 4146 4147 /// Return a SCEV corresponding to ~V = -1-V 4148 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4149 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4150 4151 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4152 return getConstant( 4153 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4154 4155 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4156 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4157 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4158 SmallVector<const SCEV *, 2> MatchedOperands; 4159 for (const SCEV *Operand : MME->operands()) { 4160 const SCEV *Matched = MatchNotExpr(Operand); 4161 if (!Matched) 4162 return (const SCEV *)nullptr; 4163 MatchedOperands.push_back(Matched); 4164 } 4165 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4166 MatchedOperands); 4167 }; 4168 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4169 return Replaced; 4170 } 4171 4172 Type *Ty = V->getType(); 4173 Ty = getEffectiveSCEVType(Ty); 4174 return getMinusSCEV(getMinusOne(Ty), V); 4175 } 4176 4177 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4178 assert(P->getType()->isPointerTy()); 4179 4180 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4181 // The base of an AddRec is the first operand. 4182 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4183 Ops[0] = removePointerBase(Ops[0]); 4184 // Don't try to transfer nowrap flags for now. We could in some cases 4185 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4186 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4187 } 4188 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4189 // The base of an Add is the pointer operand. 4190 SmallVector<const SCEV *> Ops{Add->operands()}; 4191 const SCEV **PtrOp = nullptr; 4192 for (const SCEV *&AddOp : Ops) { 4193 if (AddOp->getType()->isPointerTy()) { 4194 assert(!PtrOp && "Cannot have multiple pointer ops"); 4195 PtrOp = &AddOp; 4196 } 4197 } 4198 *PtrOp = removePointerBase(*PtrOp); 4199 // Don't try to transfer nowrap flags for now. We could in some cases 4200 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4201 return getAddExpr(Ops); 4202 } 4203 // Any other expression must be a pointer base. 4204 return getZero(P->getType()); 4205 } 4206 4207 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4208 SCEV::NoWrapFlags Flags, 4209 unsigned Depth) { 4210 // Fast path: X - X --> 0. 4211 if (LHS == RHS) 4212 return getZero(LHS->getType()); 4213 4214 // If we subtract two pointers with different pointer bases, bail. 4215 // Eventually, we're going to add an assertion to getMulExpr that we 4216 // can't multiply by a pointer. 4217 if (RHS->getType()->isPointerTy()) { 4218 if (!LHS->getType()->isPointerTy() || 4219 getPointerBase(LHS) != getPointerBase(RHS)) 4220 return getCouldNotCompute(); 4221 LHS = removePointerBase(LHS); 4222 RHS = removePointerBase(RHS); 4223 } 4224 4225 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4226 // makes it so that we cannot make much use of NUW. 4227 auto AddFlags = SCEV::FlagAnyWrap; 4228 const bool RHSIsNotMinSigned = 4229 !getSignedRangeMin(RHS).isMinSignedValue(); 4230 if (hasFlags(Flags, SCEV::FlagNSW)) { 4231 // Let M be the minimum representable signed value. Then (-1)*RHS 4232 // signed-wraps if and only if RHS is M. That can happen even for 4233 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4234 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4235 // (-1)*RHS, we need to prove that RHS != M. 4236 // 4237 // If LHS is non-negative and we know that LHS - RHS does not 4238 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4239 // either by proving that RHS > M or that LHS >= 0. 4240 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4241 AddFlags = SCEV::FlagNSW; 4242 } 4243 } 4244 4245 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4246 // RHS is NSW and LHS >= 0. 4247 // 4248 // The difficulty here is that the NSW flag may have been proven 4249 // relative to a loop that is to be found in a recurrence in LHS and 4250 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4251 // larger scope than intended. 4252 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4253 4254 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4255 } 4256 4257 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4258 unsigned Depth) { 4259 Type *SrcTy = V->getType(); 4260 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4261 "Cannot truncate or zero extend with non-integer arguments!"); 4262 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4263 return V; // No conversion 4264 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4265 return getTruncateExpr(V, Ty, Depth); 4266 return getZeroExtendExpr(V, Ty, Depth); 4267 } 4268 4269 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4270 unsigned Depth) { 4271 Type *SrcTy = V->getType(); 4272 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4273 "Cannot truncate or zero extend with non-integer arguments!"); 4274 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4275 return V; // No conversion 4276 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4277 return getTruncateExpr(V, Ty, Depth); 4278 return getSignExtendExpr(V, Ty, Depth); 4279 } 4280 4281 const SCEV * 4282 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4283 Type *SrcTy = V->getType(); 4284 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4285 "Cannot noop or zero extend with non-integer arguments!"); 4286 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4287 "getNoopOrZeroExtend cannot truncate!"); 4288 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4289 return V; // No conversion 4290 return getZeroExtendExpr(V, Ty); 4291 } 4292 4293 const SCEV * 4294 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4295 Type *SrcTy = V->getType(); 4296 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4297 "Cannot noop or sign extend with non-integer arguments!"); 4298 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4299 "getNoopOrSignExtend cannot truncate!"); 4300 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4301 return V; // No conversion 4302 return getSignExtendExpr(V, Ty); 4303 } 4304 4305 const SCEV * 4306 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4307 Type *SrcTy = V->getType(); 4308 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4309 "Cannot noop or any extend with non-integer arguments!"); 4310 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4311 "getNoopOrAnyExtend cannot truncate!"); 4312 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4313 return V; // No conversion 4314 return getAnyExtendExpr(V, Ty); 4315 } 4316 4317 const SCEV * 4318 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4319 Type *SrcTy = V->getType(); 4320 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4321 "Cannot truncate or noop with non-integer arguments!"); 4322 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4323 "getTruncateOrNoop cannot extend!"); 4324 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4325 return V; // No conversion 4326 return getTruncateExpr(V, Ty); 4327 } 4328 4329 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4330 const SCEV *RHS) { 4331 const SCEV *PromotedLHS = LHS; 4332 const SCEV *PromotedRHS = RHS; 4333 4334 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4335 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4336 else 4337 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4338 4339 return getUMaxExpr(PromotedLHS, PromotedRHS); 4340 } 4341 4342 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4343 const SCEV *RHS) { 4344 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4345 return getUMinFromMismatchedTypes(Ops); 4346 } 4347 4348 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4349 SmallVectorImpl<const SCEV *> &Ops) { 4350 assert(!Ops.empty() && "At least one operand must be!"); 4351 // Trivial case. 4352 if (Ops.size() == 1) 4353 return Ops[0]; 4354 4355 // Find the max type first. 4356 Type *MaxType = nullptr; 4357 for (auto *S : Ops) 4358 if (MaxType) 4359 MaxType = getWiderType(MaxType, S->getType()); 4360 else 4361 MaxType = S->getType(); 4362 assert(MaxType && "Failed to find maximum type!"); 4363 4364 // Extend all ops to max type. 4365 SmallVector<const SCEV *, 2> PromotedOps; 4366 for (auto *S : Ops) 4367 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4368 4369 // Generate umin. 4370 return getUMinExpr(PromotedOps); 4371 } 4372 4373 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4374 // A pointer operand may evaluate to a nonpointer expression, such as null. 4375 if (!V->getType()->isPointerTy()) 4376 return V; 4377 4378 while (true) { 4379 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4380 V = AddRec->getStart(); 4381 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4382 const SCEV *PtrOp = nullptr; 4383 for (const SCEV *AddOp : Add->operands()) { 4384 if (AddOp->getType()->isPointerTy()) { 4385 assert(!PtrOp && "Cannot have multiple pointer ops"); 4386 PtrOp = AddOp; 4387 } 4388 } 4389 assert(PtrOp && "Must have pointer op"); 4390 V = PtrOp; 4391 } else // Not something we can look further into. 4392 return V; 4393 } 4394 } 4395 4396 /// Push users of the given Instruction onto the given Worklist. 4397 static void 4398 PushDefUseChildren(Instruction *I, 4399 SmallVectorImpl<Instruction *> &Worklist) { 4400 // Push the def-use children onto the Worklist stack. 4401 for (User *U : I->users()) 4402 Worklist.push_back(cast<Instruction>(U)); 4403 } 4404 4405 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4406 SmallVector<Instruction *, 16> Worklist; 4407 PushDefUseChildren(PN, Worklist); 4408 4409 SmallPtrSet<Instruction *, 8> Visited; 4410 Visited.insert(PN); 4411 while (!Worklist.empty()) { 4412 Instruction *I = Worklist.pop_back_val(); 4413 if (!Visited.insert(I).second) 4414 continue; 4415 4416 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4417 if (It != ValueExprMap.end()) { 4418 const SCEV *Old = It->second; 4419 4420 // Short-circuit the def-use traversal if the symbolic name 4421 // ceases to appear in expressions. 4422 if (Old != SymName && !hasOperand(Old, SymName)) 4423 continue; 4424 4425 // SCEVUnknown for a PHI either means that it has an unrecognized 4426 // structure, it's a PHI that's in the progress of being computed 4427 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4428 // additional loop trip count information isn't going to change anything. 4429 // In the second case, createNodeForPHI will perform the necessary 4430 // updates on its own when it gets to that point. In the third, we do 4431 // want to forget the SCEVUnknown. 4432 if (!isa<PHINode>(I) || 4433 !isa<SCEVUnknown>(Old) || 4434 (I != PN && Old == SymName)) { 4435 eraseValueFromMap(It->first); 4436 forgetMemoizedResults(Old); 4437 } 4438 } 4439 4440 PushDefUseChildren(I, Worklist); 4441 } 4442 } 4443 4444 namespace { 4445 4446 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4447 /// expression in case its Loop is L. If it is not L then 4448 /// if IgnoreOtherLoops is true then use AddRec itself 4449 /// otherwise rewrite cannot be done. 4450 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4451 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4452 public: 4453 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4454 bool IgnoreOtherLoops = true) { 4455 SCEVInitRewriter Rewriter(L, SE); 4456 const SCEV *Result = Rewriter.visit(S); 4457 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4458 return SE.getCouldNotCompute(); 4459 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4460 ? SE.getCouldNotCompute() 4461 : Result; 4462 } 4463 4464 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4465 if (!SE.isLoopInvariant(Expr, L)) 4466 SeenLoopVariantSCEVUnknown = true; 4467 return Expr; 4468 } 4469 4470 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4471 // Only re-write AddRecExprs for this loop. 4472 if (Expr->getLoop() == L) 4473 return Expr->getStart(); 4474 SeenOtherLoops = true; 4475 return Expr; 4476 } 4477 4478 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4479 4480 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4481 4482 private: 4483 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4484 : SCEVRewriteVisitor(SE), L(L) {} 4485 4486 const Loop *L; 4487 bool SeenLoopVariantSCEVUnknown = false; 4488 bool SeenOtherLoops = false; 4489 }; 4490 4491 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4492 /// increment expression in case its Loop is L. If it is not L then 4493 /// use AddRec itself. 4494 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4495 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4496 public: 4497 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4498 SCEVPostIncRewriter Rewriter(L, SE); 4499 const SCEV *Result = Rewriter.visit(S); 4500 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4501 ? SE.getCouldNotCompute() 4502 : Result; 4503 } 4504 4505 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4506 if (!SE.isLoopInvariant(Expr, L)) 4507 SeenLoopVariantSCEVUnknown = true; 4508 return Expr; 4509 } 4510 4511 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4512 // Only re-write AddRecExprs for this loop. 4513 if (Expr->getLoop() == L) 4514 return Expr->getPostIncExpr(SE); 4515 SeenOtherLoops = true; 4516 return Expr; 4517 } 4518 4519 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4520 4521 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4522 4523 private: 4524 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4525 : SCEVRewriteVisitor(SE), L(L) {} 4526 4527 const Loop *L; 4528 bool SeenLoopVariantSCEVUnknown = false; 4529 bool SeenOtherLoops = false; 4530 }; 4531 4532 /// This class evaluates the compare condition by matching it against the 4533 /// condition of loop latch. If there is a match we assume a true value 4534 /// for the condition while building SCEV nodes. 4535 class SCEVBackedgeConditionFolder 4536 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4537 public: 4538 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4539 ScalarEvolution &SE) { 4540 bool IsPosBECond = false; 4541 Value *BECond = nullptr; 4542 if (BasicBlock *Latch = L->getLoopLatch()) { 4543 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4544 if (BI && BI->isConditional()) { 4545 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4546 "Both outgoing branches should not target same header!"); 4547 BECond = BI->getCondition(); 4548 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4549 } else { 4550 return S; 4551 } 4552 } 4553 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4554 return Rewriter.visit(S); 4555 } 4556 4557 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4558 const SCEV *Result = Expr; 4559 bool InvariantF = SE.isLoopInvariant(Expr, L); 4560 4561 if (!InvariantF) { 4562 Instruction *I = cast<Instruction>(Expr->getValue()); 4563 switch (I->getOpcode()) { 4564 case Instruction::Select: { 4565 SelectInst *SI = cast<SelectInst>(I); 4566 Optional<const SCEV *> Res = 4567 compareWithBackedgeCondition(SI->getCondition()); 4568 if (Res.hasValue()) { 4569 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4570 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4571 } 4572 break; 4573 } 4574 default: { 4575 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4576 if (Res.hasValue()) 4577 Result = Res.getValue(); 4578 break; 4579 } 4580 } 4581 } 4582 return Result; 4583 } 4584 4585 private: 4586 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4587 bool IsPosBECond, ScalarEvolution &SE) 4588 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4589 IsPositiveBECond(IsPosBECond) {} 4590 4591 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4592 4593 const Loop *L; 4594 /// Loop back condition. 4595 Value *BackedgeCond = nullptr; 4596 /// Set to true if loop back is on positive branch condition. 4597 bool IsPositiveBECond; 4598 }; 4599 4600 Optional<const SCEV *> 4601 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4602 4603 // If value matches the backedge condition for loop latch, 4604 // then return a constant evolution node based on loopback 4605 // branch taken. 4606 if (BackedgeCond == IC) 4607 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4608 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4609 return None; 4610 } 4611 4612 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4613 public: 4614 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4615 ScalarEvolution &SE) { 4616 SCEVShiftRewriter Rewriter(L, SE); 4617 const SCEV *Result = Rewriter.visit(S); 4618 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4619 } 4620 4621 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4622 // Only allow AddRecExprs for this loop. 4623 if (!SE.isLoopInvariant(Expr, L)) 4624 Valid = false; 4625 return Expr; 4626 } 4627 4628 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4629 if (Expr->getLoop() == L && Expr->isAffine()) 4630 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4631 Valid = false; 4632 return Expr; 4633 } 4634 4635 bool isValid() { return Valid; } 4636 4637 private: 4638 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4639 : SCEVRewriteVisitor(SE), L(L) {} 4640 4641 const Loop *L; 4642 bool Valid = true; 4643 }; 4644 4645 } // end anonymous namespace 4646 4647 SCEV::NoWrapFlags 4648 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4649 if (!AR->isAffine()) 4650 return SCEV::FlagAnyWrap; 4651 4652 using OBO = OverflowingBinaryOperator; 4653 4654 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4655 4656 if (!AR->hasNoSignedWrap()) { 4657 ConstantRange AddRecRange = getSignedRange(AR); 4658 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4659 4660 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4661 Instruction::Add, IncRange, OBO::NoSignedWrap); 4662 if (NSWRegion.contains(AddRecRange)) 4663 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4664 } 4665 4666 if (!AR->hasNoUnsignedWrap()) { 4667 ConstantRange AddRecRange = getUnsignedRange(AR); 4668 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4669 4670 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4671 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4672 if (NUWRegion.contains(AddRecRange)) 4673 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4674 } 4675 4676 return Result; 4677 } 4678 4679 SCEV::NoWrapFlags 4680 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4681 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4682 4683 if (AR->hasNoSignedWrap()) 4684 return Result; 4685 4686 if (!AR->isAffine()) 4687 return Result; 4688 4689 const SCEV *Step = AR->getStepRecurrence(*this); 4690 const Loop *L = AR->getLoop(); 4691 4692 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4693 // Note that this serves two purposes: It filters out loops that are 4694 // simply not analyzable, and it covers the case where this code is 4695 // being called from within backedge-taken count analysis, such that 4696 // attempting to ask for the backedge-taken count would likely result 4697 // in infinite recursion. In the later case, the analysis code will 4698 // cope with a conservative value, and it will take care to purge 4699 // that value once it has finished. 4700 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4701 4702 // Normally, in the cases we can prove no-overflow via a 4703 // backedge guarding condition, we can also compute a backedge 4704 // taken count for the loop. The exceptions are assumptions and 4705 // guards present in the loop -- SCEV is not great at exploiting 4706 // these to compute max backedge taken counts, but can still use 4707 // these to prove lack of overflow. Use this fact to avoid 4708 // doing extra work that may not pay off. 4709 4710 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4711 AC.assumptions().empty()) 4712 return Result; 4713 4714 // If the backedge is guarded by a comparison with the pre-inc value the 4715 // addrec is safe. Also, if the entry is guarded by a comparison with the 4716 // start value and the backedge is guarded by a comparison with the post-inc 4717 // value, the addrec is safe. 4718 ICmpInst::Predicate Pred; 4719 const SCEV *OverflowLimit = 4720 getSignedOverflowLimitForStep(Step, &Pred, this); 4721 if (OverflowLimit && 4722 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4723 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4724 Result = setFlags(Result, SCEV::FlagNSW); 4725 } 4726 return Result; 4727 } 4728 SCEV::NoWrapFlags 4729 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4730 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4731 4732 if (AR->hasNoUnsignedWrap()) 4733 return Result; 4734 4735 if (!AR->isAffine()) 4736 return Result; 4737 4738 const SCEV *Step = AR->getStepRecurrence(*this); 4739 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4740 const Loop *L = AR->getLoop(); 4741 4742 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4743 // Note that this serves two purposes: It filters out loops that are 4744 // simply not analyzable, and it covers the case where this code is 4745 // being called from within backedge-taken count analysis, such that 4746 // attempting to ask for the backedge-taken count would likely result 4747 // in infinite recursion. In the later case, the analysis code will 4748 // cope with a conservative value, and it will take care to purge 4749 // that value once it has finished. 4750 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4751 4752 // Normally, in the cases we can prove no-overflow via a 4753 // backedge guarding condition, we can also compute a backedge 4754 // taken count for the loop. The exceptions are assumptions and 4755 // guards present in the loop -- SCEV is not great at exploiting 4756 // these to compute max backedge taken counts, but can still use 4757 // these to prove lack of overflow. Use this fact to avoid 4758 // doing extra work that may not pay off. 4759 4760 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4761 AC.assumptions().empty()) 4762 return Result; 4763 4764 // If the backedge is guarded by a comparison with the pre-inc value the 4765 // addrec is safe. Also, if the entry is guarded by a comparison with the 4766 // start value and the backedge is guarded by a comparison with the post-inc 4767 // value, the addrec is safe. 4768 if (isKnownPositive(Step)) { 4769 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4770 getUnsignedRangeMax(Step)); 4771 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4772 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4773 Result = setFlags(Result, SCEV::FlagNUW); 4774 } 4775 } 4776 4777 return Result; 4778 } 4779 4780 namespace { 4781 4782 /// Represents an abstract binary operation. This may exist as a 4783 /// normal instruction or constant expression, or may have been 4784 /// derived from an expression tree. 4785 struct BinaryOp { 4786 unsigned Opcode; 4787 Value *LHS; 4788 Value *RHS; 4789 bool IsNSW = false; 4790 bool IsNUW = false; 4791 4792 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4793 /// constant expression. 4794 Operator *Op = nullptr; 4795 4796 explicit BinaryOp(Operator *Op) 4797 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4798 Op(Op) { 4799 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4800 IsNSW = OBO->hasNoSignedWrap(); 4801 IsNUW = OBO->hasNoUnsignedWrap(); 4802 } 4803 } 4804 4805 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4806 bool IsNUW = false) 4807 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4808 }; 4809 4810 } // end anonymous namespace 4811 4812 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4813 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4814 auto *Op = dyn_cast<Operator>(V); 4815 if (!Op) 4816 return None; 4817 4818 // Implementation detail: all the cleverness here should happen without 4819 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4820 // SCEV expressions when possible, and we should not break that. 4821 4822 switch (Op->getOpcode()) { 4823 case Instruction::Add: 4824 case Instruction::Sub: 4825 case Instruction::Mul: 4826 case Instruction::UDiv: 4827 case Instruction::URem: 4828 case Instruction::And: 4829 case Instruction::Or: 4830 case Instruction::AShr: 4831 case Instruction::Shl: 4832 return BinaryOp(Op); 4833 4834 case Instruction::Xor: 4835 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4836 // If the RHS of the xor is a signmask, then this is just an add. 4837 // Instcombine turns add of signmask into xor as a strength reduction step. 4838 if (RHSC->getValue().isSignMask()) 4839 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4840 return BinaryOp(Op); 4841 4842 case Instruction::LShr: 4843 // Turn logical shift right of a constant into a unsigned divide. 4844 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4845 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4846 4847 // If the shift count is not less than the bitwidth, the result of 4848 // the shift is undefined. Don't try to analyze it, because the 4849 // resolution chosen here may differ from the resolution chosen in 4850 // other parts of the compiler. 4851 if (SA->getValue().ult(BitWidth)) { 4852 Constant *X = 4853 ConstantInt::get(SA->getContext(), 4854 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4855 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4856 } 4857 } 4858 return BinaryOp(Op); 4859 4860 case Instruction::ExtractValue: { 4861 auto *EVI = cast<ExtractValueInst>(Op); 4862 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4863 break; 4864 4865 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4866 if (!WO) 4867 break; 4868 4869 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4870 bool Signed = WO->isSigned(); 4871 // TODO: Should add nuw/nsw flags for mul as well. 4872 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4873 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4874 4875 // Now that we know that all uses of the arithmetic-result component of 4876 // CI are guarded by the overflow check, we can go ahead and pretend 4877 // that the arithmetic is non-overflowing. 4878 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4879 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4880 } 4881 4882 default: 4883 break; 4884 } 4885 4886 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4887 // semantics as a Sub, return a binary sub expression. 4888 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4889 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4890 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4891 4892 return None; 4893 } 4894 4895 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4896 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4897 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4898 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4899 /// follows one of the following patterns: 4900 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4901 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4902 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4903 /// we return the type of the truncation operation, and indicate whether the 4904 /// truncated type should be treated as signed/unsigned by setting 4905 /// \p Signed to true/false, respectively. 4906 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4907 bool &Signed, ScalarEvolution &SE) { 4908 // The case where Op == SymbolicPHI (that is, with no type conversions on 4909 // the way) is handled by the regular add recurrence creating logic and 4910 // would have already been triggered in createAddRecForPHI. Reaching it here 4911 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4912 // because one of the other operands of the SCEVAddExpr updating this PHI is 4913 // not invariant). 4914 // 4915 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4916 // this case predicates that allow us to prove that Op == SymbolicPHI will 4917 // be added. 4918 if (Op == SymbolicPHI) 4919 return nullptr; 4920 4921 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4922 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4923 if (SourceBits != NewBits) 4924 return nullptr; 4925 4926 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4927 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4928 if (!SExt && !ZExt) 4929 return nullptr; 4930 const SCEVTruncateExpr *Trunc = 4931 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4932 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4933 if (!Trunc) 4934 return nullptr; 4935 const SCEV *X = Trunc->getOperand(); 4936 if (X != SymbolicPHI) 4937 return nullptr; 4938 Signed = SExt != nullptr; 4939 return Trunc->getType(); 4940 } 4941 4942 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4943 if (!PN->getType()->isIntegerTy()) 4944 return nullptr; 4945 const Loop *L = LI.getLoopFor(PN->getParent()); 4946 if (!L || L->getHeader() != PN->getParent()) 4947 return nullptr; 4948 return L; 4949 } 4950 4951 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4952 // computation that updates the phi follows the following pattern: 4953 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4954 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4955 // If so, try to see if it can be rewritten as an AddRecExpr under some 4956 // Predicates. If successful, return them as a pair. Also cache the results 4957 // of the analysis. 4958 // 4959 // Example usage scenario: 4960 // Say the Rewriter is called for the following SCEV: 4961 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4962 // where: 4963 // %X = phi i64 (%Start, %BEValue) 4964 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4965 // and call this function with %SymbolicPHI = %X. 4966 // 4967 // The analysis will find that the value coming around the backedge has 4968 // the following SCEV: 4969 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4970 // Upon concluding that this matches the desired pattern, the function 4971 // will return the pair {NewAddRec, SmallPredsVec} where: 4972 // NewAddRec = {%Start,+,%Step} 4973 // SmallPredsVec = {P1, P2, P3} as follows: 4974 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4975 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4976 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4977 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4978 // under the predicates {P1,P2,P3}. 4979 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4980 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4981 // 4982 // TODO's: 4983 // 4984 // 1) Extend the Induction descriptor to also support inductions that involve 4985 // casts: When needed (namely, when we are called in the context of the 4986 // vectorizer induction analysis), a Set of cast instructions will be 4987 // populated by this method, and provided back to isInductionPHI. This is 4988 // needed to allow the vectorizer to properly record them to be ignored by 4989 // the cost model and to avoid vectorizing them (otherwise these casts, 4990 // which are redundant under the runtime overflow checks, will be 4991 // vectorized, which can be costly). 4992 // 4993 // 2) Support additional induction/PHISCEV patterns: We also want to support 4994 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4995 // after the induction update operation (the induction increment): 4996 // 4997 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4998 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4999 // 5000 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5001 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5002 // 5003 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5004 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5005 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5006 SmallVector<const SCEVPredicate *, 3> Predicates; 5007 5008 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5009 // return an AddRec expression under some predicate. 5010 5011 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5012 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5013 assert(L && "Expecting an integer loop header phi"); 5014 5015 // The loop may have multiple entrances or multiple exits; we can analyze 5016 // this phi as an addrec if it has a unique entry value and a unique 5017 // backedge value. 5018 Value *BEValueV = nullptr, *StartValueV = nullptr; 5019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5020 Value *V = PN->getIncomingValue(i); 5021 if (L->contains(PN->getIncomingBlock(i))) { 5022 if (!BEValueV) { 5023 BEValueV = V; 5024 } else if (BEValueV != V) { 5025 BEValueV = nullptr; 5026 break; 5027 } 5028 } else if (!StartValueV) { 5029 StartValueV = V; 5030 } else if (StartValueV != V) { 5031 StartValueV = nullptr; 5032 break; 5033 } 5034 } 5035 if (!BEValueV || !StartValueV) 5036 return None; 5037 5038 const SCEV *BEValue = getSCEV(BEValueV); 5039 5040 // If the value coming around the backedge is an add with the symbolic 5041 // value we just inserted, possibly with casts that we can ignore under 5042 // an appropriate runtime guard, then we found a simple induction variable! 5043 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5044 if (!Add) 5045 return None; 5046 5047 // If there is a single occurrence of the symbolic value, possibly 5048 // casted, replace it with a recurrence. 5049 unsigned FoundIndex = Add->getNumOperands(); 5050 Type *TruncTy = nullptr; 5051 bool Signed; 5052 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5053 if ((TruncTy = 5054 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5055 if (FoundIndex == e) { 5056 FoundIndex = i; 5057 break; 5058 } 5059 5060 if (FoundIndex == Add->getNumOperands()) 5061 return None; 5062 5063 // Create an add with everything but the specified operand. 5064 SmallVector<const SCEV *, 8> Ops; 5065 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5066 if (i != FoundIndex) 5067 Ops.push_back(Add->getOperand(i)); 5068 const SCEV *Accum = getAddExpr(Ops); 5069 5070 // The runtime checks will not be valid if the step amount is 5071 // varying inside the loop. 5072 if (!isLoopInvariant(Accum, L)) 5073 return None; 5074 5075 // *** Part2: Create the predicates 5076 5077 // Analysis was successful: we have a phi-with-cast pattern for which we 5078 // can return an AddRec expression under the following predicates: 5079 // 5080 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5081 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5082 // P2: An Equal predicate that guarantees that 5083 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5084 // P3: An Equal predicate that guarantees that 5085 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5086 // 5087 // As we next prove, the above predicates guarantee that: 5088 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5089 // 5090 // 5091 // More formally, we want to prove that: 5092 // Expr(i+1) = Start + (i+1) * Accum 5093 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5094 // 5095 // Given that: 5096 // 1) Expr(0) = Start 5097 // 2) Expr(1) = Start + Accum 5098 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5099 // 3) Induction hypothesis (step i): 5100 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5101 // 5102 // Proof: 5103 // Expr(i+1) = 5104 // = Start + (i+1)*Accum 5105 // = (Start + i*Accum) + Accum 5106 // = Expr(i) + Accum 5107 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5108 // :: from step i 5109 // 5110 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5111 // 5112 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5113 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5114 // + Accum :: from P3 5115 // 5116 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5117 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5118 // 5119 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5120 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5121 // 5122 // By induction, the same applies to all iterations 1<=i<n: 5123 // 5124 5125 // Create a truncated addrec for which we will add a no overflow check (P1). 5126 const SCEV *StartVal = getSCEV(StartValueV); 5127 const SCEV *PHISCEV = 5128 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5129 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5130 5131 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5132 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5133 // will be constant. 5134 // 5135 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5136 // add P1. 5137 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5138 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5139 Signed ? SCEVWrapPredicate::IncrementNSSW 5140 : SCEVWrapPredicate::IncrementNUSW; 5141 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5142 Predicates.push_back(AddRecPred); 5143 } 5144 5145 // Create the Equal Predicates P2,P3: 5146 5147 // It is possible that the predicates P2 and/or P3 are computable at 5148 // compile time due to StartVal and/or Accum being constants. 5149 // If either one is, then we can check that now and escape if either P2 5150 // or P3 is false. 5151 5152 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5153 // for each of StartVal and Accum 5154 auto getExtendedExpr = [&](const SCEV *Expr, 5155 bool CreateSignExtend) -> const SCEV * { 5156 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5157 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5158 const SCEV *ExtendedExpr = 5159 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5160 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5161 return ExtendedExpr; 5162 }; 5163 5164 // Given: 5165 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5166 // = getExtendedExpr(Expr) 5167 // Determine whether the predicate P: Expr == ExtendedExpr 5168 // is known to be false at compile time 5169 auto PredIsKnownFalse = [&](const SCEV *Expr, 5170 const SCEV *ExtendedExpr) -> bool { 5171 return Expr != ExtendedExpr && 5172 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5173 }; 5174 5175 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5176 if (PredIsKnownFalse(StartVal, StartExtended)) { 5177 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5178 return None; 5179 } 5180 5181 // The Step is always Signed (because the overflow checks are either 5182 // NSSW or NUSW) 5183 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5184 if (PredIsKnownFalse(Accum, AccumExtended)) { 5185 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5186 return None; 5187 } 5188 5189 auto AppendPredicate = [&](const SCEV *Expr, 5190 const SCEV *ExtendedExpr) -> void { 5191 if (Expr != ExtendedExpr && 5192 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5193 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5194 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5195 Predicates.push_back(Pred); 5196 } 5197 }; 5198 5199 AppendPredicate(StartVal, StartExtended); 5200 AppendPredicate(Accum, AccumExtended); 5201 5202 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5203 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5204 // into NewAR if it will also add the runtime overflow checks specified in 5205 // Predicates. 5206 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5207 5208 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5209 std::make_pair(NewAR, Predicates); 5210 // Remember the result of the analysis for this SCEV at this locayyytion. 5211 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5212 return PredRewrite; 5213 } 5214 5215 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5216 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5217 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5218 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5219 if (!L) 5220 return None; 5221 5222 // Check to see if we already analyzed this PHI. 5223 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5224 if (I != PredicatedSCEVRewrites.end()) { 5225 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5226 I->second; 5227 // Analysis was done before and failed to create an AddRec: 5228 if (Rewrite.first == SymbolicPHI) 5229 return None; 5230 // Analysis was done before and succeeded to create an AddRec under 5231 // a predicate: 5232 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5233 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5234 return Rewrite; 5235 } 5236 5237 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5238 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5239 5240 // Record in the cache that the analysis failed 5241 if (!Rewrite) { 5242 SmallVector<const SCEVPredicate *, 3> Predicates; 5243 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5244 return None; 5245 } 5246 5247 return Rewrite; 5248 } 5249 5250 // FIXME: This utility is currently required because the Rewriter currently 5251 // does not rewrite this expression: 5252 // {0, +, (sext ix (trunc iy to ix) to iy)} 5253 // into {0, +, %step}, 5254 // even when the following Equal predicate exists: 5255 // "%step == (sext ix (trunc iy to ix) to iy)". 5256 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5257 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5258 if (AR1 == AR2) 5259 return true; 5260 5261 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5262 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5263 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5264 return false; 5265 return true; 5266 }; 5267 5268 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5269 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5270 return false; 5271 return true; 5272 } 5273 5274 /// A helper function for createAddRecFromPHI to handle simple cases. 5275 /// 5276 /// This function tries to find an AddRec expression for the simplest (yet most 5277 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5278 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5279 /// technique for finding the AddRec expression. 5280 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5281 Value *BEValueV, 5282 Value *StartValueV) { 5283 const Loop *L = LI.getLoopFor(PN->getParent()); 5284 assert(L && L->getHeader() == PN->getParent()); 5285 assert(BEValueV && StartValueV); 5286 5287 auto BO = MatchBinaryOp(BEValueV, DT); 5288 if (!BO) 5289 return nullptr; 5290 5291 if (BO->Opcode != Instruction::Add) 5292 return nullptr; 5293 5294 const SCEV *Accum = nullptr; 5295 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5296 Accum = getSCEV(BO->RHS); 5297 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5298 Accum = getSCEV(BO->LHS); 5299 5300 if (!Accum) 5301 return nullptr; 5302 5303 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5304 if (BO->IsNUW) 5305 Flags = setFlags(Flags, SCEV::FlagNUW); 5306 if (BO->IsNSW) 5307 Flags = setFlags(Flags, SCEV::FlagNSW); 5308 5309 const SCEV *StartVal = getSCEV(StartValueV); 5310 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5311 5312 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5313 5314 // We can add Flags to the post-inc expression only if we 5315 // know that it is *undefined behavior* for BEValueV to 5316 // overflow. 5317 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5318 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5319 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5320 5321 return PHISCEV; 5322 } 5323 5324 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5325 const Loop *L = LI.getLoopFor(PN->getParent()); 5326 if (!L || L->getHeader() != PN->getParent()) 5327 return nullptr; 5328 5329 // The loop may have multiple entrances or multiple exits; we can analyze 5330 // this phi as an addrec if it has a unique entry value and a unique 5331 // backedge value. 5332 Value *BEValueV = nullptr, *StartValueV = nullptr; 5333 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5334 Value *V = PN->getIncomingValue(i); 5335 if (L->contains(PN->getIncomingBlock(i))) { 5336 if (!BEValueV) { 5337 BEValueV = V; 5338 } else if (BEValueV != V) { 5339 BEValueV = nullptr; 5340 break; 5341 } 5342 } else if (!StartValueV) { 5343 StartValueV = V; 5344 } else if (StartValueV != V) { 5345 StartValueV = nullptr; 5346 break; 5347 } 5348 } 5349 if (!BEValueV || !StartValueV) 5350 return nullptr; 5351 5352 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5353 "PHI node already processed?"); 5354 5355 // First, try to find AddRec expression without creating a fictituos symbolic 5356 // value for PN. 5357 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5358 return S; 5359 5360 // Handle PHI node value symbolically. 5361 const SCEV *SymbolicName = getUnknown(PN); 5362 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5363 5364 // Using this symbolic name for the PHI, analyze the value coming around 5365 // the back-edge. 5366 const SCEV *BEValue = getSCEV(BEValueV); 5367 5368 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5369 // has a special value for the first iteration of the loop. 5370 5371 // If the value coming around the backedge is an add with the symbolic 5372 // value we just inserted, then we found a simple induction variable! 5373 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5374 // If there is a single occurrence of the symbolic value, replace it 5375 // with a recurrence. 5376 unsigned FoundIndex = Add->getNumOperands(); 5377 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5378 if (Add->getOperand(i) == SymbolicName) 5379 if (FoundIndex == e) { 5380 FoundIndex = i; 5381 break; 5382 } 5383 5384 if (FoundIndex != Add->getNumOperands()) { 5385 // Create an add with everything but the specified operand. 5386 SmallVector<const SCEV *, 8> Ops; 5387 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5388 if (i != FoundIndex) 5389 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5390 L, *this)); 5391 const SCEV *Accum = getAddExpr(Ops); 5392 5393 // This is not a valid addrec if the step amount is varying each 5394 // loop iteration, but is not itself an addrec in this loop. 5395 if (isLoopInvariant(Accum, L) || 5396 (isa<SCEVAddRecExpr>(Accum) && 5397 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5398 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5399 5400 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5401 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5402 if (BO->IsNUW) 5403 Flags = setFlags(Flags, SCEV::FlagNUW); 5404 if (BO->IsNSW) 5405 Flags = setFlags(Flags, SCEV::FlagNSW); 5406 } 5407 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5408 // If the increment is an inbounds GEP, then we know the address 5409 // space cannot be wrapped around. We cannot make any guarantee 5410 // about signed or unsigned overflow because pointers are 5411 // unsigned but we may have a negative index from the base 5412 // pointer. We can guarantee that no unsigned wrap occurs if the 5413 // indices form a positive value. 5414 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5415 Flags = setFlags(Flags, SCEV::FlagNW); 5416 5417 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5418 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5419 Flags = setFlags(Flags, SCEV::FlagNUW); 5420 } 5421 5422 // We cannot transfer nuw and nsw flags from subtraction 5423 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5424 // for instance. 5425 } 5426 5427 const SCEV *StartVal = getSCEV(StartValueV); 5428 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5429 5430 // Okay, for the entire analysis of this edge we assumed the PHI 5431 // to be symbolic. We now need to go back and purge all of the 5432 // entries for the scalars that use the symbolic expression. 5433 forgetSymbolicName(PN, SymbolicName); 5434 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5435 5436 // We can add Flags to the post-inc expression only if we 5437 // know that it is *undefined behavior* for BEValueV to 5438 // overflow. 5439 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5440 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5441 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5442 5443 return PHISCEV; 5444 } 5445 } 5446 } else { 5447 // Otherwise, this could be a loop like this: 5448 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5449 // In this case, j = {1,+,1} and BEValue is j. 5450 // Because the other in-value of i (0) fits the evolution of BEValue 5451 // i really is an addrec evolution. 5452 // 5453 // We can generalize this saying that i is the shifted value of BEValue 5454 // by one iteration: 5455 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5456 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5457 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5458 if (Shifted != getCouldNotCompute() && 5459 Start != getCouldNotCompute()) { 5460 const SCEV *StartVal = getSCEV(StartValueV); 5461 if (Start == StartVal) { 5462 // Okay, for the entire analysis of this edge we assumed the PHI 5463 // to be symbolic. We now need to go back and purge all of the 5464 // entries for the scalars that use the symbolic expression. 5465 forgetSymbolicName(PN, SymbolicName); 5466 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5467 return Shifted; 5468 } 5469 } 5470 } 5471 5472 // Remove the temporary PHI node SCEV that has been inserted while intending 5473 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5474 // as it will prevent later (possibly simpler) SCEV expressions to be added 5475 // to the ValueExprMap. 5476 eraseValueFromMap(PN); 5477 5478 return nullptr; 5479 } 5480 5481 // Checks if the SCEV S is available at BB. S is considered available at BB 5482 // if S can be materialized at BB without introducing a fault. 5483 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5484 BasicBlock *BB) { 5485 struct CheckAvailable { 5486 bool TraversalDone = false; 5487 bool Available = true; 5488 5489 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5490 BasicBlock *BB = nullptr; 5491 DominatorTree &DT; 5492 5493 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5494 : L(L), BB(BB), DT(DT) {} 5495 5496 bool setUnavailable() { 5497 TraversalDone = true; 5498 Available = false; 5499 return false; 5500 } 5501 5502 bool follow(const SCEV *S) { 5503 switch (S->getSCEVType()) { 5504 case scConstant: 5505 case scPtrToInt: 5506 case scTruncate: 5507 case scZeroExtend: 5508 case scSignExtend: 5509 case scAddExpr: 5510 case scMulExpr: 5511 case scUMaxExpr: 5512 case scSMaxExpr: 5513 case scUMinExpr: 5514 case scSMinExpr: 5515 // These expressions are available if their operand(s) is/are. 5516 return true; 5517 5518 case scAddRecExpr: { 5519 // We allow add recurrences that are on the loop BB is in, or some 5520 // outer loop. This guarantees availability because the value of the 5521 // add recurrence at BB is simply the "current" value of the induction 5522 // variable. We can relax this in the future; for instance an add 5523 // recurrence on a sibling dominating loop is also available at BB. 5524 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5525 if (L && (ARLoop == L || ARLoop->contains(L))) 5526 return true; 5527 5528 return setUnavailable(); 5529 } 5530 5531 case scUnknown: { 5532 // For SCEVUnknown, we check for simple dominance. 5533 const auto *SU = cast<SCEVUnknown>(S); 5534 Value *V = SU->getValue(); 5535 5536 if (isa<Argument>(V)) 5537 return false; 5538 5539 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5540 return false; 5541 5542 return setUnavailable(); 5543 } 5544 5545 case scUDivExpr: 5546 case scCouldNotCompute: 5547 // We do not try to smart about these at all. 5548 return setUnavailable(); 5549 } 5550 llvm_unreachable("Unknown SCEV kind!"); 5551 } 5552 5553 bool isDone() { return TraversalDone; } 5554 }; 5555 5556 CheckAvailable CA(L, BB, DT); 5557 SCEVTraversal<CheckAvailable> ST(CA); 5558 5559 ST.visitAll(S); 5560 return CA.Available; 5561 } 5562 5563 // Try to match a control flow sequence that branches out at BI and merges back 5564 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5565 // match. 5566 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5567 Value *&C, Value *&LHS, Value *&RHS) { 5568 C = BI->getCondition(); 5569 5570 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5571 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5572 5573 if (!LeftEdge.isSingleEdge()) 5574 return false; 5575 5576 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5577 5578 Use &LeftUse = Merge->getOperandUse(0); 5579 Use &RightUse = Merge->getOperandUse(1); 5580 5581 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5582 LHS = LeftUse; 5583 RHS = RightUse; 5584 return true; 5585 } 5586 5587 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5588 LHS = RightUse; 5589 RHS = LeftUse; 5590 return true; 5591 } 5592 5593 return false; 5594 } 5595 5596 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5597 auto IsReachable = 5598 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5599 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5600 const Loop *L = LI.getLoopFor(PN->getParent()); 5601 5602 // We don't want to break LCSSA, even in a SCEV expression tree. 5603 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5604 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5605 return nullptr; 5606 5607 // Try to match 5608 // 5609 // br %cond, label %left, label %right 5610 // left: 5611 // br label %merge 5612 // right: 5613 // br label %merge 5614 // merge: 5615 // V = phi [ %x, %left ], [ %y, %right ] 5616 // 5617 // as "select %cond, %x, %y" 5618 5619 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5620 assert(IDom && "At least the entry block should dominate PN"); 5621 5622 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5623 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5624 5625 if (BI && BI->isConditional() && 5626 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5627 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5628 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5629 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5630 } 5631 5632 return nullptr; 5633 } 5634 5635 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5636 if (const SCEV *S = createAddRecFromPHI(PN)) 5637 return S; 5638 5639 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5640 return S; 5641 5642 // If the PHI has a single incoming value, follow that value, unless the 5643 // PHI's incoming blocks are in a different loop, in which case doing so 5644 // risks breaking LCSSA form. Instcombine would normally zap these, but 5645 // it doesn't have DominatorTree information, so it may miss cases. 5646 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5647 if (LI.replacementPreservesLCSSAForm(PN, V)) 5648 return getSCEV(V); 5649 5650 // If it's not a loop phi, we can't handle it yet. 5651 return getUnknown(PN); 5652 } 5653 5654 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5655 Value *Cond, 5656 Value *TrueVal, 5657 Value *FalseVal) { 5658 // Handle "constant" branch or select. This can occur for instance when a 5659 // loop pass transforms an inner loop and moves on to process the outer loop. 5660 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5661 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5662 5663 // Try to match some simple smax or umax patterns. 5664 auto *ICI = dyn_cast<ICmpInst>(Cond); 5665 if (!ICI) 5666 return getUnknown(I); 5667 5668 Value *LHS = ICI->getOperand(0); 5669 Value *RHS = ICI->getOperand(1); 5670 5671 switch (ICI->getPredicate()) { 5672 case ICmpInst::ICMP_SLT: 5673 case ICmpInst::ICMP_SLE: 5674 case ICmpInst::ICMP_ULT: 5675 case ICmpInst::ICMP_ULE: 5676 std::swap(LHS, RHS); 5677 LLVM_FALLTHROUGH; 5678 case ICmpInst::ICMP_SGT: 5679 case ICmpInst::ICMP_SGE: 5680 case ICmpInst::ICMP_UGT: 5681 case ICmpInst::ICMP_UGE: 5682 // a > b ? a+x : b+x -> max(a, b)+x 5683 // a > b ? b+x : a+x -> min(a, b)+x 5684 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5685 bool Signed = ICI->isSigned(); 5686 const SCEV *LA = getSCEV(TrueVal); 5687 const SCEV *RA = getSCEV(FalseVal); 5688 const SCEV *LS = getSCEV(LHS); 5689 const SCEV *RS = getSCEV(RHS); 5690 if (LA->getType()->isPointerTy()) { 5691 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5692 // Need to make sure we can't produce weird expressions involving 5693 // negated pointers. 5694 if (LA == LS && RA == RS) 5695 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5696 if (LA == RS && RA == LS) 5697 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5698 } 5699 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5700 if (Op->getType()->isPointerTy()) { 5701 Op = getLosslessPtrToIntExpr(Op); 5702 if (isa<SCEVCouldNotCompute>(Op)) 5703 return Op; 5704 } 5705 if (Signed) 5706 Op = getNoopOrSignExtend(Op, I->getType()); 5707 else 5708 Op = getNoopOrZeroExtend(Op, I->getType()); 5709 return Op; 5710 }; 5711 LS = CoerceOperand(LS); 5712 RS = CoerceOperand(RS); 5713 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5714 break; 5715 const SCEV *LDiff = getMinusSCEV(LA, LS); 5716 const SCEV *RDiff = getMinusSCEV(RA, RS); 5717 if (LDiff == RDiff) 5718 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5719 LDiff); 5720 LDiff = getMinusSCEV(LA, RS); 5721 RDiff = getMinusSCEV(RA, LS); 5722 if (LDiff == RDiff) 5723 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5724 LDiff); 5725 } 5726 break; 5727 case ICmpInst::ICMP_NE: 5728 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5729 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5730 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5731 const SCEV *One = getOne(I->getType()); 5732 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5733 const SCEV *LA = getSCEV(TrueVal); 5734 const SCEV *RA = getSCEV(FalseVal); 5735 const SCEV *LDiff = getMinusSCEV(LA, LS); 5736 const SCEV *RDiff = getMinusSCEV(RA, One); 5737 if (LDiff == RDiff) 5738 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5739 } 5740 break; 5741 case ICmpInst::ICMP_EQ: 5742 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5743 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5744 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5745 const SCEV *One = getOne(I->getType()); 5746 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5747 const SCEV *LA = getSCEV(TrueVal); 5748 const SCEV *RA = getSCEV(FalseVal); 5749 const SCEV *LDiff = getMinusSCEV(LA, One); 5750 const SCEV *RDiff = getMinusSCEV(RA, LS); 5751 if (LDiff == RDiff) 5752 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5753 } 5754 break; 5755 default: 5756 break; 5757 } 5758 5759 return getUnknown(I); 5760 } 5761 5762 /// Expand GEP instructions into add and multiply operations. This allows them 5763 /// to be analyzed by regular SCEV code. 5764 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5765 // Don't attempt to analyze GEPs over unsized objects. 5766 if (!GEP->getSourceElementType()->isSized()) 5767 return getUnknown(GEP); 5768 5769 SmallVector<const SCEV *, 4> IndexExprs; 5770 for (Value *Index : GEP->indices()) 5771 IndexExprs.push_back(getSCEV(Index)); 5772 return getGEPExpr(GEP, IndexExprs); 5773 } 5774 5775 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5776 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5777 return C->getAPInt().countTrailingZeros(); 5778 5779 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5780 return GetMinTrailingZeros(I->getOperand()); 5781 5782 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5783 return std::min(GetMinTrailingZeros(T->getOperand()), 5784 (uint32_t)getTypeSizeInBits(T->getType())); 5785 5786 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5787 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5788 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5789 ? getTypeSizeInBits(E->getType()) 5790 : OpRes; 5791 } 5792 5793 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5794 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5795 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5796 ? getTypeSizeInBits(E->getType()) 5797 : OpRes; 5798 } 5799 5800 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(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 SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5809 // The result is the sum of all operands results. 5810 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5811 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5812 for (unsigned i = 1, e = M->getNumOperands(); 5813 SumOpRes != BitWidth && i != e; ++i) 5814 SumOpRes = 5815 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5816 return SumOpRes; 5817 } 5818 5819 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5820 // The result is the min of all operands results. 5821 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5822 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5823 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5824 return MinOpRes; 5825 } 5826 5827 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5828 // The result is the min of all operands results. 5829 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5830 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5831 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5832 return MinOpRes; 5833 } 5834 5835 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5836 // The result is the min of all operands results. 5837 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5838 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5839 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5840 return MinOpRes; 5841 } 5842 5843 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5844 // For a SCEVUnknown, ask ValueTracking. 5845 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5846 return Known.countMinTrailingZeros(); 5847 } 5848 5849 // SCEVUDivExpr 5850 return 0; 5851 } 5852 5853 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5854 auto I = MinTrailingZerosCache.find(S); 5855 if (I != MinTrailingZerosCache.end()) 5856 return I->second; 5857 5858 uint32_t Result = GetMinTrailingZerosImpl(S); 5859 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5860 assert(InsertPair.second && "Should insert a new key"); 5861 return InsertPair.first->second; 5862 } 5863 5864 /// Helper method to assign a range to V from metadata present in the IR. 5865 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5866 if (Instruction *I = dyn_cast<Instruction>(V)) 5867 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5868 return getConstantRangeFromMetadata(*MD); 5869 5870 return None; 5871 } 5872 5873 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5874 SCEV::NoWrapFlags Flags) { 5875 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5876 AddRec->setNoWrapFlags(Flags); 5877 UnsignedRanges.erase(AddRec); 5878 SignedRanges.erase(AddRec); 5879 } 5880 } 5881 5882 ConstantRange ScalarEvolution:: 5883 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5884 const DataLayout &DL = getDataLayout(); 5885 5886 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5887 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5888 5889 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5890 // use information about the trip count to improve our available range. Note 5891 // that the trip count independent cases are already handled by known bits. 5892 // WARNING: The definition of recurrence used here is subtly different than 5893 // the one used by AddRec (and thus most of this file). Step is allowed to 5894 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5895 // and other addrecs in the same loop (for non-affine addrecs). The code 5896 // below intentionally handles the case where step is not loop invariant. 5897 auto *P = dyn_cast<PHINode>(U->getValue()); 5898 if (!P) 5899 return FullSet; 5900 5901 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5902 // even the values that are not available in these blocks may come from them, 5903 // and this leads to false-positive recurrence test. 5904 for (auto *Pred : predecessors(P->getParent())) 5905 if (!DT.isReachableFromEntry(Pred)) 5906 return FullSet; 5907 5908 BinaryOperator *BO; 5909 Value *Start, *Step; 5910 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5911 return FullSet; 5912 5913 // If we found a recurrence in reachable code, we must be in a loop. Note 5914 // that BO might be in some subloop of L, and that's completely okay. 5915 auto *L = LI.getLoopFor(P->getParent()); 5916 assert(L && L->getHeader() == P->getParent()); 5917 if (!L->contains(BO->getParent())) 5918 // NOTE: This bailout should be an assert instead. However, asserting 5919 // the condition here exposes a case where LoopFusion is querying SCEV 5920 // with malformed loop information during the midst of the transform. 5921 // There doesn't appear to be an obvious fix, so for the moment bailout 5922 // until the caller issue can be fixed. PR49566 tracks the bug. 5923 return FullSet; 5924 5925 // TODO: Extend to other opcodes such as mul, and div 5926 switch (BO->getOpcode()) { 5927 default: 5928 return FullSet; 5929 case Instruction::AShr: 5930 case Instruction::LShr: 5931 case Instruction::Shl: 5932 break; 5933 }; 5934 5935 if (BO->getOperand(0) != P) 5936 // TODO: Handle the power function forms some day. 5937 return FullSet; 5938 5939 unsigned TC = getSmallConstantMaxTripCount(L); 5940 if (!TC || TC >= BitWidth) 5941 return FullSet; 5942 5943 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5944 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5945 assert(KnownStart.getBitWidth() == BitWidth && 5946 KnownStep.getBitWidth() == BitWidth); 5947 5948 // Compute total shift amount, being careful of overflow and bitwidths. 5949 auto MaxShiftAmt = KnownStep.getMaxValue(); 5950 APInt TCAP(BitWidth, TC-1); 5951 bool Overflow = false; 5952 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5953 if (Overflow) 5954 return FullSet; 5955 5956 switch (BO->getOpcode()) { 5957 default: 5958 llvm_unreachable("filtered out above"); 5959 case Instruction::AShr: { 5960 // For each ashr, three cases: 5961 // shift = 0 => unchanged value 5962 // saturation => 0 or -1 5963 // other => a value closer to zero (of the same sign) 5964 // Thus, the end value is closer to zero than the start. 5965 auto KnownEnd = KnownBits::ashr(KnownStart, 5966 KnownBits::makeConstant(TotalShift)); 5967 if (KnownStart.isNonNegative()) 5968 // Analogous to lshr (simply not yet canonicalized) 5969 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5970 KnownStart.getMaxValue() + 1); 5971 if (KnownStart.isNegative()) 5972 // End >=u Start && End <=s Start 5973 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5974 KnownEnd.getMaxValue() + 1); 5975 break; 5976 } 5977 case Instruction::LShr: { 5978 // For each lshr, three cases: 5979 // shift = 0 => unchanged value 5980 // saturation => 0 5981 // other => a smaller positive number 5982 // Thus, the low end of the unsigned range is the last value produced. 5983 auto KnownEnd = KnownBits::lshr(KnownStart, 5984 KnownBits::makeConstant(TotalShift)); 5985 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5986 KnownStart.getMaxValue() + 1); 5987 } 5988 case Instruction::Shl: { 5989 // Iff no bits are shifted out, value increases on every shift. 5990 auto KnownEnd = KnownBits::shl(KnownStart, 5991 KnownBits::makeConstant(TotalShift)); 5992 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5993 return ConstantRange(KnownStart.getMinValue(), 5994 KnownEnd.getMaxValue() + 1); 5995 break; 5996 } 5997 }; 5998 return FullSet; 5999 } 6000 6001 /// Determine the range for a particular SCEV. If SignHint is 6002 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6003 /// with a "cleaner" unsigned (resp. signed) representation. 6004 const ConstantRange & 6005 ScalarEvolution::getRangeRef(const SCEV *S, 6006 ScalarEvolution::RangeSignHint SignHint) { 6007 DenseMap<const SCEV *, ConstantRange> &Cache = 6008 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6009 : SignedRanges; 6010 ConstantRange::PreferredRangeType RangeType = 6011 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6012 ? ConstantRange::Unsigned : ConstantRange::Signed; 6013 6014 // See if we've computed this range already. 6015 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6016 if (I != Cache.end()) 6017 return I->second; 6018 6019 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6020 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6021 6022 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6023 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6024 using OBO = OverflowingBinaryOperator; 6025 6026 // If the value has known zeros, the maximum value will have those known zeros 6027 // as well. 6028 uint32_t TZ = GetMinTrailingZeros(S); 6029 if (TZ != 0) { 6030 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6031 ConservativeResult = 6032 ConstantRange(APInt::getMinValue(BitWidth), 6033 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6034 else 6035 ConservativeResult = ConstantRange( 6036 APInt::getSignedMinValue(BitWidth), 6037 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6038 } 6039 6040 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6041 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6042 unsigned WrapType = OBO::AnyWrap; 6043 if (Add->hasNoSignedWrap()) 6044 WrapType |= OBO::NoSignedWrap; 6045 if (Add->hasNoUnsignedWrap()) 6046 WrapType |= OBO::NoUnsignedWrap; 6047 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6048 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6049 WrapType, RangeType); 6050 return setRange(Add, SignHint, 6051 ConservativeResult.intersectWith(X, RangeType)); 6052 } 6053 6054 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6055 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6056 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6057 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6058 return setRange(Mul, SignHint, 6059 ConservativeResult.intersectWith(X, RangeType)); 6060 } 6061 6062 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 6063 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 6064 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 6065 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 6066 return setRange(SMax, SignHint, 6067 ConservativeResult.intersectWith(X, RangeType)); 6068 } 6069 6070 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 6071 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 6072 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 6073 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 6074 return setRange(UMax, SignHint, 6075 ConservativeResult.intersectWith(X, RangeType)); 6076 } 6077 6078 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 6079 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 6080 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 6081 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 6082 return setRange(SMin, SignHint, 6083 ConservativeResult.intersectWith(X, RangeType)); 6084 } 6085 6086 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 6087 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 6088 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 6089 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 6090 return setRange(UMin, SignHint, 6091 ConservativeResult.intersectWith(X, RangeType)); 6092 } 6093 6094 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6095 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6096 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6097 return setRange(UDiv, SignHint, 6098 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6099 } 6100 6101 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6102 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6103 return setRange(ZExt, SignHint, 6104 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6105 RangeType)); 6106 } 6107 6108 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6109 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6110 return setRange(SExt, SignHint, 6111 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6112 RangeType)); 6113 } 6114 6115 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6116 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6117 return setRange(PtrToInt, SignHint, X); 6118 } 6119 6120 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6121 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6122 return setRange(Trunc, SignHint, 6123 ConservativeResult.intersectWith(X.truncate(BitWidth), 6124 RangeType)); 6125 } 6126 6127 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6128 // If there's no unsigned wrap, the value will never be less than its 6129 // initial value. 6130 if (AddRec->hasNoUnsignedWrap()) { 6131 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6132 if (!UnsignedMinValue.isNullValue()) 6133 ConservativeResult = ConservativeResult.intersectWith( 6134 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6135 } 6136 6137 // If there's no signed wrap, and all the operands except initial value have 6138 // the same sign or zero, the value won't ever be: 6139 // 1: smaller than initial value if operands are non negative, 6140 // 2: bigger than initial value if operands are non positive. 6141 // For both cases, value can not cross signed min/max boundary. 6142 if (AddRec->hasNoSignedWrap()) { 6143 bool AllNonNeg = true; 6144 bool AllNonPos = true; 6145 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6146 if (!isKnownNonNegative(AddRec->getOperand(i))) 6147 AllNonNeg = false; 6148 if (!isKnownNonPositive(AddRec->getOperand(i))) 6149 AllNonPos = false; 6150 } 6151 if (AllNonNeg) 6152 ConservativeResult = ConservativeResult.intersectWith( 6153 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6154 APInt::getSignedMinValue(BitWidth)), 6155 RangeType); 6156 else if (AllNonPos) 6157 ConservativeResult = ConservativeResult.intersectWith( 6158 ConstantRange::getNonEmpty( 6159 APInt::getSignedMinValue(BitWidth), 6160 getSignedRangeMax(AddRec->getStart()) + 1), 6161 RangeType); 6162 } 6163 6164 // TODO: non-affine addrec 6165 if (AddRec->isAffine()) { 6166 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6167 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6168 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6169 auto RangeFromAffine = getRangeForAffineAR( 6170 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6171 BitWidth); 6172 ConservativeResult = 6173 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6174 6175 auto RangeFromFactoring = getRangeViaFactoring( 6176 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6177 BitWidth); 6178 ConservativeResult = 6179 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6180 } 6181 6182 // Now try symbolic BE count and more powerful methods. 6183 if (UseExpensiveRangeSharpening) { 6184 const SCEV *SymbolicMaxBECount = 6185 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6186 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6187 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6188 AddRec->hasNoSelfWrap()) { 6189 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6190 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6191 ConservativeResult = 6192 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6193 } 6194 } 6195 } 6196 6197 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6198 } 6199 6200 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6201 6202 // Check if the IR explicitly contains !range metadata. 6203 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6204 if (MDRange.hasValue()) 6205 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6206 RangeType); 6207 6208 // Use facts about recurrences in the underlying IR. Note that add 6209 // recurrences are AddRecExprs and thus don't hit this path. This 6210 // primarily handles shift recurrences. 6211 auto CR = getRangeForUnknownRecurrence(U); 6212 ConservativeResult = ConservativeResult.intersectWith(CR); 6213 6214 // See if ValueTracking can give us a useful range. 6215 const DataLayout &DL = getDataLayout(); 6216 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6217 if (Known.getBitWidth() != BitWidth) 6218 Known = Known.zextOrTrunc(BitWidth); 6219 6220 // ValueTracking may be able to compute a tighter result for the number of 6221 // sign bits than for the value of those sign bits. 6222 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6223 if (U->getType()->isPointerTy()) { 6224 // If the pointer size is larger than the index size type, this can cause 6225 // NS to be larger than BitWidth. So compensate for this. 6226 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6227 int ptrIdxDiff = ptrSize - BitWidth; 6228 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6229 NS -= ptrIdxDiff; 6230 } 6231 6232 if (NS > 1) { 6233 // If we know any of the sign bits, we know all of the sign bits. 6234 if (!Known.Zero.getHiBits(NS).isNullValue()) 6235 Known.Zero.setHighBits(NS); 6236 if (!Known.One.getHiBits(NS).isNullValue()) 6237 Known.One.setHighBits(NS); 6238 } 6239 6240 if (Known.getMinValue() != Known.getMaxValue() + 1) 6241 ConservativeResult = ConservativeResult.intersectWith( 6242 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6243 RangeType); 6244 if (NS > 1) 6245 ConservativeResult = ConservativeResult.intersectWith( 6246 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6247 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6248 RangeType); 6249 6250 // A range of Phi is a subset of union of all ranges of its input. 6251 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6252 // Make sure that we do not run over cycled Phis. 6253 if (PendingPhiRanges.insert(Phi).second) { 6254 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6255 for (auto &Op : Phi->operands()) { 6256 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6257 RangeFromOps = RangeFromOps.unionWith(OpRange); 6258 // No point to continue if we already have a full set. 6259 if (RangeFromOps.isFullSet()) 6260 break; 6261 } 6262 ConservativeResult = 6263 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6264 bool Erased = PendingPhiRanges.erase(Phi); 6265 assert(Erased && "Failed to erase Phi properly?"); 6266 (void) Erased; 6267 } 6268 } 6269 6270 return setRange(U, SignHint, std::move(ConservativeResult)); 6271 } 6272 6273 return setRange(S, SignHint, std::move(ConservativeResult)); 6274 } 6275 6276 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6277 // values that the expression can take. Initially, the expression has a value 6278 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6279 // argument defines if we treat Step as signed or unsigned. 6280 static ConstantRange getRangeForAffineARHelper(APInt Step, 6281 const ConstantRange &StartRange, 6282 const APInt &MaxBECount, 6283 unsigned BitWidth, bool Signed) { 6284 // If either Step or MaxBECount is 0, then the expression won't change, and we 6285 // just need to return the initial range. 6286 if (Step == 0 || MaxBECount == 0) 6287 return StartRange; 6288 6289 // If we don't know anything about the initial value (i.e. StartRange is 6290 // FullRange), then we don't know anything about the final range either. 6291 // Return FullRange. 6292 if (StartRange.isFullSet()) 6293 return ConstantRange::getFull(BitWidth); 6294 6295 // If Step is signed and negative, then we use its absolute value, but we also 6296 // note that we're moving in the opposite direction. 6297 bool Descending = Signed && Step.isNegative(); 6298 6299 if (Signed) 6300 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6301 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6302 // This equations hold true due to the well-defined wrap-around behavior of 6303 // APInt. 6304 Step = Step.abs(); 6305 6306 // Check if Offset is more than full span of BitWidth. If it is, the 6307 // expression is guaranteed to overflow. 6308 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6309 return ConstantRange::getFull(BitWidth); 6310 6311 // Offset is by how much the expression can change. Checks above guarantee no 6312 // overflow here. 6313 APInt Offset = Step * MaxBECount; 6314 6315 // Minimum value of the final range will match the minimal value of StartRange 6316 // if the expression is increasing and will be decreased by Offset otherwise. 6317 // Maximum value of the final range will match the maximal value of StartRange 6318 // if the expression is decreasing and will be increased by Offset otherwise. 6319 APInt StartLower = StartRange.getLower(); 6320 APInt StartUpper = StartRange.getUpper() - 1; 6321 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6322 : (StartUpper + std::move(Offset)); 6323 6324 // It's possible that the new minimum/maximum value will fall into the initial 6325 // range (due to wrap around). This means that the expression can take any 6326 // value in this bitwidth, and we have to return full range. 6327 if (StartRange.contains(MovedBoundary)) 6328 return ConstantRange::getFull(BitWidth); 6329 6330 APInt NewLower = 6331 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6332 APInt NewUpper = 6333 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6334 NewUpper += 1; 6335 6336 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6337 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6338 } 6339 6340 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6341 const SCEV *Step, 6342 const SCEV *MaxBECount, 6343 unsigned BitWidth) { 6344 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6345 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6346 "Precondition!"); 6347 6348 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6349 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6350 6351 // First, consider step signed. 6352 ConstantRange StartSRange = getSignedRange(Start); 6353 ConstantRange StepSRange = getSignedRange(Step); 6354 6355 // If Step can be both positive and negative, we need to find ranges for the 6356 // maximum absolute step values in both directions and union them. 6357 ConstantRange SR = 6358 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6359 MaxBECountValue, BitWidth, /* Signed = */ true); 6360 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6361 StartSRange, MaxBECountValue, 6362 BitWidth, /* Signed = */ true)); 6363 6364 // Next, consider step unsigned. 6365 ConstantRange UR = getRangeForAffineARHelper( 6366 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6367 MaxBECountValue, BitWidth, /* Signed = */ false); 6368 6369 // Finally, intersect signed and unsigned ranges. 6370 return SR.intersectWith(UR, ConstantRange::Smallest); 6371 } 6372 6373 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6374 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6375 ScalarEvolution::RangeSignHint SignHint) { 6376 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6377 assert(AddRec->hasNoSelfWrap() && 6378 "This only works for non-self-wrapping AddRecs!"); 6379 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6380 const SCEV *Step = AddRec->getStepRecurrence(*this); 6381 // Only deal with constant step to save compile time. 6382 if (!isa<SCEVConstant>(Step)) 6383 return ConstantRange::getFull(BitWidth); 6384 // Let's make sure that we can prove that we do not self-wrap during 6385 // MaxBECount iterations. We need this because MaxBECount is a maximum 6386 // iteration count estimate, and we might infer nw from some exit for which we 6387 // do not know max exit count (or any other side reasoning). 6388 // TODO: Turn into assert at some point. 6389 if (getTypeSizeInBits(MaxBECount->getType()) > 6390 getTypeSizeInBits(AddRec->getType())) 6391 return ConstantRange::getFull(BitWidth); 6392 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6393 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6394 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6395 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6396 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6397 MaxItersWithoutWrap)) 6398 return ConstantRange::getFull(BitWidth); 6399 6400 ICmpInst::Predicate LEPred = 6401 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6402 ICmpInst::Predicate GEPred = 6403 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6404 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6405 6406 // We know that there is no self-wrap. Let's take Start and End values and 6407 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6408 // the iteration. They either lie inside the range [Min(Start, End), 6409 // Max(Start, End)] or outside it: 6410 // 6411 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6412 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6413 // 6414 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6415 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6416 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6417 // Start <= End and step is positive, or Start >= End and step is negative. 6418 const SCEV *Start = AddRec->getStart(); 6419 ConstantRange StartRange = getRangeRef(Start, SignHint); 6420 ConstantRange EndRange = getRangeRef(End, SignHint); 6421 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6422 // If they already cover full iteration space, we will know nothing useful 6423 // even if we prove what we want to prove. 6424 if (RangeBetween.isFullSet()) 6425 return RangeBetween; 6426 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6427 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6428 : RangeBetween.isWrappedSet(); 6429 if (IsWrappedSet) 6430 return ConstantRange::getFull(BitWidth); 6431 6432 if (isKnownPositive(Step) && 6433 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6434 return RangeBetween; 6435 else if (isKnownNegative(Step) && 6436 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6437 return RangeBetween; 6438 return ConstantRange::getFull(BitWidth); 6439 } 6440 6441 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6442 const SCEV *Step, 6443 const SCEV *MaxBECount, 6444 unsigned BitWidth) { 6445 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6446 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6447 6448 struct SelectPattern { 6449 Value *Condition = nullptr; 6450 APInt TrueValue; 6451 APInt FalseValue; 6452 6453 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6454 const SCEV *S) { 6455 Optional<unsigned> CastOp; 6456 APInt Offset(BitWidth, 0); 6457 6458 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6459 "Should be!"); 6460 6461 // Peel off a constant offset: 6462 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6463 // In the future we could consider being smarter here and handle 6464 // {Start+Step,+,Step} too. 6465 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6466 return; 6467 6468 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6469 S = SA->getOperand(1); 6470 } 6471 6472 // Peel off a cast operation 6473 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6474 CastOp = SCast->getSCEVType(); 6475 S = SCast->getOperand(); 6476 } 6477 6478 using namespace llvm::PatternMatch; 6479 6480 auto *SU = dyn_cast<SCEVUnknown>(S); 6481 const APInt *TrueVal, *FalseVal; 6482 if (!SU || 6483 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6484 m_APInt(FalseVal)))) { 6485 Condition = nullptr; 6486 return; 6487 } 6488 6489 TrueValue = *TrueVal; 6490 FalseValue = *FalseVal; 6491 6492 // Re-apply the cast we peeled off earlier 6493 if (CastOp.hasValue()) 6494 switch (*CastOp) { 6495 default: 6496 llvm_unreachable("Unknown SCEV cast type!"); 6497 6498 case scTruncate: 6499 TrueValue = TrueValue.trunc(BitWidth); 6500 FalseValue = FalseValue.trunc(BitWidth); 6501 break; 6502 case scZeroExtend: 6503 TrueValue = TrueValue.zext(BitWidth); 6504 FalseValue = FalseValue.zext(BitWidth); 6505 break; 6506 case scSignExtend: 6507 TrueValue = TrueValue.sext(BitWidth); 6508 FalseValue = FalseValue.sext(BitWidth); 6509 break; 6510 } 6511 6512 // Re-apply the constant offset we peeled off earlier 6513 TrueValue += Offset; 6514 FalseValue += Offset; 6515 } 6516 6517 bool isRecognized() { return Condition != nullptr; } 6518 }; 6519 6520 SelectPattern StartPattern(*this, BitWidth, Start); 6521 if (!StartPattern.isRecognized()) 6522 return ConstantRange::getFull(BitWidth); 6523 6524 SelectPattern StepPattern(*this, BitWidth, Step); 6525 if (!StepPattern.isRecognized()) 6526 return ConstantRange::getFull(BitWidth); 6527 6528 if (StartPattern.Condition != StepPattern.Condition) { 6529 // We don't handle this case today; but we could, by considering four 6530 // possibilities below instead of two. I'm not sure if there are cases where 6531 // that will help over what getRange already does, though. 6532 return ConstantRange::getFull(BitWidth); 6533 } 6534 6535 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6536 // construct arbitrary general SCEV expressions here. This function is called 6537 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6538 // say) can end up caching a suboptimal value. 6539 6540 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6541 // C2352 and C2512 (otherwise it isn't needed). 6542 6543 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6544 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6545 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6546 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6547 6548 ConstantRange TrueRange = 6549 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6550 ConstantRange FalseRange = 6551 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6552 6553 return TrueRange.unionWith(FalseRange); 6554 } 6555 6556 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6557 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6558 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6559 6560 // Return early if there are no flags to propagate to the SCEV. 6561 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6562 if (BinOp->hasNoUnsignedWrap()) 6563 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6564 if (BinOp->hasNoSignedWrap()) 6565 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6566 if (Flags == SCEV::FlagAnyWrap) 6567 return SCEV::FlagAnyWrap; 6568 6569 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6570 } 6571 6572 const Instruction *ScalarEvolution::getDefinedScopeRoot(const SCEV *S) { 6573 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6574 return &*AddRec->getLoop()->getHeader()->begin(); 6575 // TODO: add SCEVConstant and SCEVUnknown caxes here 6576 return nullptr; 6577 } 6578 6579 static bool 6580 isGuaranteedToTransferExecutionToSuccessor(BasicBlock::const_iterator Begin, 6581 BasicBlock::const_iterator End) { 6582 return llvm::all_of( make_range(Begin, End), [](const Instruction &I) { 6583 return isGuaranteedToTransferExecutionToSuccessor(&I); 6584 }); 6585 } 6586 6587 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6588 const Instruction *B) { 6589 if (A->getParent() == B->getParent() && 6590 ::isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6591 B->getIterator())) 6592 return true; 6593 return false; 6594 } 6595 6596 6597 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6598 // Here we check that I is in the header of the innermost loop containing I, 6599 // since we only deal with instructions in the loop header. The actual loop we 6600 // need to check later will come from an add recurrence, but getting that 6601 // requires computing the SCEV of the operands, which can be expensive. This 6602 // check we can do cheaply to rule out some cases early. 6603 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6604 if (InnermostContainingLoop == nullptr || 6605 InnermostContainingLoop->getHeader() != I->getParent()) 6606 return false; 6607 6608 // Only proceed if we can prove that I does not yield poison. 6609 if (!programUndefinedIfPoison(I)) 6610 return false; 6611 6612 // At this point we know that if I is executed, then it does not wrap 6613 // according to at least one of NSW or NUW. If I is not executed, then we do 6614 // not know if the calculation that I represents would wrap. Multiple 6615 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6616 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6617 // derived from other instructions that map to the same SCEV. We cannot make 6618 // that guarantee for cases where I is not executed. So we need to find a 6619 // upper bound on the defining scope for the SCEV, and prove that I is 6620 // executed every time we enter that scope. When the bounding scope is a 6621 // loop (the common case), this is equivalent to proving I executes on every 6622 // iteration of that loop. 6623 for (const Use &Op : I->operands()) { 6624 // I could be an extractvalue from a call to an overflow intrinsic. 6625 // TODO: We can do better here in some cases. 6626 if (!isSCEVable(Op->getType())) 6627 return false; 6628 if (auto *DefI = getDefinedScopeRoot(getSCEV(Op))) 6629 if (isGuaranteedToTransferExecutionTo(DefI, I)) 6630 return true; 6631 } 6632 return false; 6633 } 6634 6635 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6636 // If we know that \c I can never be poison period, then that's enough. 6637 if (isSCEVExprNeverPoison(I)) 6638 return true; 6639 6640 // For an add recurrence specifically, we assume that infinite loops without 6641 // side effects are undefined behavior, and then reason as follows: 6642 // 6643 // If the add recurrence is poison in any iteration, it is poison on all 6644 // future iterations (since incrementing poison yields poison). If the result 6645 // of the add recurrence is fed into the loop latch condition and the loop 6646 // does not contain any throws or exiting blocks other than the latch, we now 6647 // have the ability to "choose" whether the backedge is taken or not (by 6648 // choosing a sufficiently evil value for the poison feeding into the branch) 6649 // for every iteration including and after the one in which \p I first became 6650 // poison. There are two possibilities (let's call the iteration in which \p 6651 // I first became poison as K): 6652 // 6653 // 1. In the set of iterations including and after K, the loop body executes 6654 // no side effects. In this case executing the backege an infinte number 6655 // of times will yield undefined behavior. 6656 // 6657 // 2. In the set of iterations including and after K, the loop body executes 6658 // at least one side effect. In this case, that specific instance of side 6659 // effect is control dependent on poison, which also yields undefined 6660 // behavior. 6661 6662 auto *ExitingBB = L->getExitingBlock(); 6663 auto *LatchBB = L->getLoopLatch(); 6664 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6665 return false; 6666 6667 SmallPtrSet<const Instruction *, 16> Pushed; 6668 SmallVector<const Instruction *, 8> PoisonStack; 6669 6670 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6671 // things that are known to be poison under that assumption go on the 6672 // PoisonStack. 6673 Pushed.insert(I); 6674 PoisonStack.push_back(I); 6675 6676 bool LatchControlDependentOnPoison = false; 6677 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6678 const Instruction *Poison = PoisonStack.pop_back_val(); 6679 6680 for (auto *PoisonUser : Poison->users()) { 6681 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6682 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6683 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6684 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6685 assert(BI->isConditional() && "Only possibility!"); 6686 if (BI->getParent() == LatchBB) { 6687 LatchControlDependentOnPoison = true; 6688 break; 6689 } 6690 } 6691 } 6692 } 6693 6694 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6695 } 6696 6697 ScalarEvolution::LoopProperties 6698 ScalarEvolution::getLoopProperties(const Loop *L) { 6699 using LoopProperties = ScalarEvolution::LoopProperties; 6700 6701 auto Itr = LoopPropertiesCache.find(L); 6702 if (Itr == LoopPropertiesCache.end()) { 6703 auto HasSideEffects = [](Instruction *I) { 6704 if (auto *SI = dyn_cast<StoreInst>(I)) 6705 return !SI->isSimple(); 6706 6707 return I->mayThrow() || I->mayWriteToMemory(); 6708 }; 6709 6710 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6711 /*HasNoSideEffects*/ true}; 6712 6713 for (auto *BB : L->getBlocks()) 6714 for (auto &I : *BB) { 6715 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6716 LP.HasNoAbnormalExits = false; 6717 if (HasSideEffects(&I)) 6718 LP.HasNoSideEffects = false; 6719 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6720 break; // We're already as pessimistic as we can get. 6721 } 6722 6723 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6724 assert(InsertPair.second && "We just checked!"); 6725 Itr = InsertPair.first; 6726 } 6727 6728 return Itr->second; 6729 } 6730 6731 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6732 // A mustprogress loop without side effects must be finite. 6733 // TODO: The check used here is very conservative. It's only *specific* 6734 // side effects which are well defined in infinite loops. 6735 return isMustProgress(L) && loopHasNoSideEffects(L); 6736 } 6737 6738 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6739 if (!isSCEVable(V->getType())) 6740 return getUnknown(V); 6741 6742 if (Instruction *I = dyn_cast<Instruction>(V)) { 6743 // Don't attempt to analyze instructions in blocks that aren't 6744 // reachable. Such instructions don't matter, and they aren't required 6745 // to obey basic rules for definitions dominating uses which this 6746 // analysis depends on. 6747 if (!DT.isReachableFromEntry(I->getParent())) 6748 return getUnknown(UndefValue::get(V->getType())); 6749 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6750 return getConstant(CI); 6751 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6752 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6753 else if (!isa<ConstantExpr>(V)) 6754 return getUnknown(V); 6755 6756 Operator *U = cast<Operator>(V); 6757 if (auto BO = MatchBinaryOp(U, DT)) { 6758 switch (BO->Opcode) { 6759 case Instruction::Add: { 6760 // The simple thing to do would be to just call getSCEV on both operands 6761 // and call getAddExpr with the result. However if we're looking at a 6762 // bunch of things all added together, this can be quite inefficient, 6763 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6764 // Instead, gather up all the operands and make a single getAddExpr call. 6765 // LLVM IR canonical form means we need only traverse the left operands. 6766 SmallVector<const SCEV *, 4> AddOps; 6767 do { 6768 if (BO->Op) { 6769 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6770 AddOps.push_back(OpSCEV); 6771 break; 6772 } 6773 6774 // If a NUW or NSW flag can be applied to the SCEV for this 6775 // addition, then compute the SCEV for this addition by itself 6776 // with a separate call to getAddExpr. We need to do that 6777 // instead of pushing the operands of the addition onto AddOps, 6778 // since the flags are only known to apply to this particular 6779 // addition - they may not apply to other additions that can be 6780 // formed with operands from AddOps. 6781 const SCEV *RHS = getSCEV(BO->RHS); 6782 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6783 if (Flags != SCEV::FlagAnyWrap) { 6784 const SCEV *LHS = getSCEV(BO->LHS); 6785 if (BO->Opcode == Instruction::Sub) 6786 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6787 else 6788 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6789 break; 6790 } 6791 } 6792 6793 if (BO->Opcode == Instruction::Sub) 6794 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6795 else 6796 AddOps.push_back(getSCEV(BO->RHS)); 6797 6798 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6799 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6800 NewBO->Opcode != Instruction::Sub)) { 6801 AddOps.push_back(getSCEV(BO->LHS)); 6802 break; 6803 } 6804 BO = NewBO; 6805 } while (true); 6806 6807 return getAddExpr(AddOps); 6808 } 6809 6810 case Instruction::Mul: { 6811 SmallVector<const SCEV *, 4> MulOps; 6812 do { 6813 if (BO->Op) { 6814 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6815 MulOps.push_back(OpSCEV); 6816 break; 6817 } 6818 6819 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6820 if (Flags != SCEV::FlagAnyWrap) { 6821 MulOps.push_back( 6822 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6823 break; 6824 } 6825 } 6826 6827 MulOps.push_back(getSCEV(BO->RHS)); 6828 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6829 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6830 MulOps.push_back(getSCEV(BO->LHS)); 6831 break; 6832 } 6833 BO = NewBO; 6834 } while (true); 6835 6836 return getMulExpr(MulOps); 6837 } 6838 case Instruction::UDiv: 6839 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6840 case Instruction::URem: 6841 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6842 case Instruction::Sub: { 6843 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6844 if (BO->Op) 6845 Flags = getNoWrapFlagsFromUB(BO->Op); 6846 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6847 } 6848 case Instruction::And: 6849 // For an expression like x&255 that merely masks off the high bits, 6850 // use zext(trunc(x)) as the SCEV expression. 6851 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6852 if (CI->isZero()) 6853 return getSCEV(BO->RHS); 6854 if (CI->isMinusOne()) 6855 return getSCEV(BO->LHS); 6856 const APInt &A = CI->getValue(); 6857 6858 // Instcombine's ShrinkDemandedConstant may strip bits out of 6859 // constants, obscuring what would otherwise be a low-bits mask. 6860 // Use computeKnownBits to compute what ShrinkDemandedConstant 6861 // knew about to reconstruct a low-bits mask value. 6862 unsigned LZ = A.countLeadingZeros(); 6863 unsigned TZ = A.countTrailingZeros(); 6864 unsigned BitWidth = A.getBitWidth(); 6865 KnownBits Known(BitWidth); 6866 computeKnownBits(BO->LHS, Known, getDataLayout(), 6867 0, &AC, nullptr, &DT); 6868 6869 APInt EffectiveMask = 6870 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6871 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6872 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6873 const SCEV *LHS = getSCEV(BO->LHS); 6874 const SCEV *ShiftedLHS = nullptr; 6875 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6876 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6877 // For an expression like (x * 8) & 8, simplify the multiply. 6878 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6879 unsigned GCD = std::min(MulZeros, TZ); 6880 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6881 SmallVector<const SCEV*, 4> MulOps; 6882 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6883 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6884 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6885 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6886 } 6887 } 6888 if (!ShiftedLHS) 6889 ShiftedLHS = getUDivExpr(LHS, MulCount); 6890 return getMulExpr( 6891 getZeroExtendExpr( 6892 getTruncateExpr(ShiftedLHS, 6893 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6894 BO->LHS->getType()), 6895 MulCount); 6896 } 6897 } 6898 break; 6899 6900 case Instruction::Or: 6901 // If the RHS of the Or is a constant, we may have something like: 6902 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6903 // optimizations will transparently handle this case. 6904 // 6905 // In order for this transformation to be safe, the LHS must be of the 6906 // form X*(2^n) and the Or constant must be less than 2^n. 6907 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6908 const SCEV *LHS = getSCEV(BO->LHS); 6909 const APInt &CIVal = CI->getValue(); 6910 if (GetMinTrailingZeros(LHS) >= 6911 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6912 // Build a plain add SCEV. 6913 return getAddExpr(LHS, getSCEV(CI), 6914 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6915 } 6916 } 6917 break; 6918 6919 case Instruction::Xor: 6920 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6921 // If the RHS of xor is -1, then this is a not operation. 6922 if (CI->isMinusOne()) 6923 return getNotSCEV(getSCEV(BO->LHS)); 6924 6925 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6926 // This is a variant of the check for xor with -1, and it handles 6927 // the case where instcombine has trimmed non-demanded bits out 6928 // of an xor with -1. 6929 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6930 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6931 if (LBO->getOpcode() == Instruction::And && 6932 LCI->getValue() == CI->getValue()) 6933 if (const SCEVZeroExtendExpr *Z = 6934 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6935 Type *UTy = BO->LHS->getType(); 6936 const SCEV *Z0 = Z->getOperand(); 6937 Type *Z0Ty = Z0->getType(); 6938 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6939 6940 // If C is a low-bits mask, the zero extend is serving to 6941 // mask off the high bits. Complement the operand and 6942 // re-apply the zext. 6943 if (CI->getValue().isMask(Z0TySize)) 6944 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6945 6946 // If C is a single bit, it may be in the sign-bit position 6947 // before the zero-extend. In this case, represent the xor 6948 // using an add, which is equivalent, and re-apply the zext. 6949 APInt Trunc = CI->getValue().trunc(Z0TySize); 6950 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6951 Trunc.isSignMask()) 6952 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6953 UTy); 6954 } 6955 } 6956 break; 6957 6958 case Instruction::Shl: 6959 // Turn shift left of a constant amount into a multiply. 6960 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6961 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6962 6963 // If the shift count is not less than the bitwidth, the result of 6964 // the shift is undefined. Don't try to analyze it, because the 6965 // resolution chosen here may differ from the resolution chosen in 6966 // other parts of the compiler. 6967 if (SA->getValue().uge(BitWidth)) 6968 break; 6969 6970 // We can safely preserve the nuw flag in all cases. It's also safe to 6971 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6972 // requires special handling. It can be preserved as long as we're not 6973 // left shifting by bitwidth - 1. 6974 auto Flags = SCEV::FlagAnyWrap; 6975 if (BO->Op) { 6976 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6977 if ((MulFlags & SCEV::FlagNSW) && 6978 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6979 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6980 if (MulFlags & SCEV::FlagNUW) 6981 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6982 } 6983 6984 Constant *X = ConstantInt::get( 6985 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6986 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6987 } 6988 break; 6989 6990 case Instruction::AShr: { 6991 // AShr X, C, where C is a constant. 6992 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6993 if (!CI) 6994 break; 6995 6996 Type *OuterTy = BO->LHS->getType(); 6997 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6998 // If the shift count is not less than the bitwidth, the result of 6999 // the shift is undefined. Don't try to analyze it, because the 7000 // resolution chosen here may differ from the resolution chosen in 7001 // other parts of the compiler. 7002 if (CI->getValue().uge(BitWidth)) 7003 break; 7004 7005 if (CI->isZero()) 7006 return getSCEV(BO->LHS); // shift by zero --> noop 7007 7008 uint64_t AShrAmt = CI->getZExtValue(); 7009 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7010 7011 Operator *L = dyn_cast<Operator>(BO->LHS); 7012 if (L && L->getOpcode() == Instruction::Shl) { 7013 // X = Shl A, n 7014 // Y = AShr X, m 7015 // Both n and m are constant. 7016 7017 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7018 if (L->getOperand(1) == BO->RHS) 7019 // For a two-shift sext-inreg, i.e. n = m, 7020 // use sext(trunc(x)) as the SCEV expression. 7021 return getSignExtendExpr( 7022 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7023 7024 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7025 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7026 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7027 if (ShlAmt > AShrAmt) { 7028 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7029 // expression. We already checked that ShlAmt < BitWidth, so 7030 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7031 // ShlAmt - AShrAmt < Amt. 7032 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7033 ShlAmt - AShrAmt); 7034 return getSignExtendExpr( 7035 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7036 getConstant(Mul)), OuterTy); 7037 } 7038 } 7039 } 7040 break; 7041 } 7042 } 7043 } 7044 7045 switch (U->getOpcode()) { 7046 case Instruction::Trunc: 7047 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7048 7049 case Instruction::ZExt: 7050 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7051 7052 case Instruction::SExt: 7053 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7054 // The NSW flag of a subtract does not always survive the conversion to 7055 // A + (-1)*B. By pushing sign extension onto its operands we are much 7056 // more likely to preserve NSW and allow later AddRec optimisations. 7057 // 7058 // NOTE: This is effectively duplicating this logic from getSignExtend: 7059 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7060 // but by that point the NSW information has potentially been lost. 7061 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7062 Type *Ty = U->getType(); 7063 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7064 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7065 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7066 } 7067 } 7068 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7069 7070 case Instruction::BitCast: 7071 // BitCasts are no-op casts so we just eliminate the cast. 7072 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7073 return getSCEV(U->getOperand(0)); 7074 break; 7075 7076 case Instruction::PtrToInt: { 7077 // Pointer to integer cast is straight-forward, so do model it. 7078 const SCEV *Op = getSCEV(U->getOperand(0)); 7079 Type *DstIntTy = U->getType(); 7080 // But only if effective SCEV (integer) type is wide enough to represent 7081 // all possible pointer values. 7082 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7083 if (isa<SCEVCouldNotCompute>(IntOp)) 7084 return getUnknown(V); 7085 return IntOp; 7086 } 7087 case Instruction::IntToPtr: 7088 // Just don't deal with inttoptr casts. 7089 return getUnknown(V); 7090 7091 case Instruction::SDiv: 7092 // If both operands are non-negative, this is just an udiv. 7093 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7094 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7095 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7096 break; 7097 7098 case Instruction::SRem: 7099 // If both operands are non-negative, this is just an urem. 7100 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7101 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7102 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7103 break; 7104 7105 case Instruction::GetElementPtr: 7106 return createNodeForGEP(cast<GEPOperator>(U)); 7107 7108 case Instruction::PHI: 7109 return createNodeForPHI(cast<PHINode>(U)); 7110 7111 case Instruction::Select: 7112 // U can also be a select constant expr, which let fall through. Since 7113 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7114 // constant expressions cannot have instructions as operands, we'd have 7115 // returned getUnknown for a select constant expressions anyway. 7116 if (isa<Instruction>(U)) 7117 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7118 U->getOperand(1), U->getOperand(2)); 7119 break; 7120 7121 case Instruction::Call: 7122 case Instruction::Invoke: 7123 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7124 return getSCEV(RV); 7125 7126 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7127 switch (II->getIntrinsicID()) { 7128 case Intrinsic::abs: 7129 return getAbsExpr( 7130 getSCEV(II->getArgOperand(0)), 7131 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7132 case Intrinsic::umax: 7133 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7134 getSCEV(II->getArgOperand(1))); 7135 case Intrinsic::umin: 7136 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7137 getSCEV(II->getArgOperand(1))); 7138 case Intrinsic::smax: 7139 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7140 getSCEV(II->getArgOperand(1))); 7141 case Intrinsic::smin: 7142 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7143 getSCEV(II->getArgOperand(1))); 7144 case Intrinsic::usub_sat: { 7145 const SCEV *X = getSCEV(II->getArgOperand(0)); 7146 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7147 const SCEV *ClampedY = getUMinExpr(X, Y); 7148 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7149 } 7150 case Intrinsic::uadd_sat: { 7151 const SCEV *X = getSCEV(II->getArgOperand(0)); 7152 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7153 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7154 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7155 } 7156 case Intrinsic::start_loop_iterations: 7157 // A start_loop_iterations is just equivalent to the first operand for 7158 // SCEV purposes. 7159 return getSCEV(II->getArgOperand(0)); 7160 default: 7161 break; 7162 } 7163 } 7164 break; 7165 } 7166 7167 return getUnknown(V); 7168 } 7169 7170 //===----------------------------------------------------------------------===// 7171 // Iteration Count Computation Code 7172 // 7173 7174 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7175 // Get the trip count from the BE count by adding 1. Overflow, results 7176 // in zero which means "unknown". 7177 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7178 } 7179 7180 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7181 if (!ExitCount) 7182 return 0; 7183 7184 ConstantInt *ExitConst = ExitCount->getValue(); 7185 7186 // Guard against huge trip counts. 7187 if (ExitConst->getValue().getActiveBits() > 32) 7188 return 0; 7189 7190 // In case of integer overflow, this returns 0, which is correct. 7191 return ((unsigned)ExitConst->getZExtValue()) + 1; 7192 } 7193 7194 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7195 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7196 return getConstantTripCount(ExitCount); 7197 } 7198 7199 unsigned 7200 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7201 const BasicBlock *ExitingBlock) { 7202 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7203 assert(L->isLoopExiting(ExitingBlock) && 7204 "Exiting block must actually branch out of the loop!"); 7205 const SCEVConstant *ExitCount = 7206 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7207 return getConstantTripCount(ExitCount); 7208 } 7209 7210 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7211 const auto *MaxExitCount = 7212 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7213 return getConstantTripCount(MaxExitCount); 7214 } 7215 7216 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7217 SmallVector<BasicBlock *, 8> ExitingBlocks; 7218 L->getExitingBlocks(ExitingBlocks); 7219 7220 Optional<unsigned> Res = None; 7221 for (auto *ExitingBB : ExitingBlocks) { 7222 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7223 if (!Res) 7224 Res = Multiple; 7225 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7226 } 7227 return Res.getValueOr(1); 7228 } 7229 7230 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7231 const SCEV *ExitCount) { 7232 if (ExitCount == getCouldNotCompute()) 7233 return 1; 7234 7235 // Get the trip count 7236 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7237 7238 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7239 if (!TC) 7240 // Attempt to factor more general cases. Returns the greatest power of 7241 // two divisor. If overflow happens, the trip count expression is still 7242 // divisible by the greatest power of 2 divisor returned. 7243 return 1U << std::min((uint32_t)31, 7244 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7245 7246 ConstantInt *Result = TC->getValue(); 7247 7248 // Guard against huge trip counts (this requires checking 7249 // for zero to handle the case where the trip count == -1 and the 7250 // addition wraps). 7251 if (!Result || Result->getValue().getActiveBits() > 32 || 7252 Result->getValue().getActiveBits() == 0) 7253 return 1; 7254 7255 return (unsigned)Result->getZExtValue(); 7256 } 7257 7258 /// Returns the largest constant divisor of the trip count of this loop as a 7259 /// normal unsigned value, if possible. This means that the actual trip count is 7260 /// always a multiple of the returned value (don't forget the trip count could 7261 /// very well be zero as well!). 7262 /// 7263 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7264 /// multiple of a constant (which is also the case if the trip count is simply 7265 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7266 /// if the trip count is very large (>= 2^32). 7267 /// 7268 /// As explained in the comments for getSmallConstantTripCount, this assumes 7269 /// that control exits the loop via ExitingBlock. 7270 unsigned 7271 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7272 const BasicBlock *ExitingBlock) { 7273 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7274 assert(L->isLoopExiting(ExitingBlock) && 7275 "Exiting block must actually branch out of the loop!"); 7276 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7277 return getSmallConstantTripMultiple(L, ExitCount); 7278 } 7279 7280 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7281 const BasicBlock *ExitingBlock, 7282 ExitCountKind Kind) { 7283 switch (Kind) { 7284 case Exact: 7285 case SymbolicMaximum: 7286 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7287 case ConstantMaximum: 7288 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7289 }; 7290 llvm_unreachable("Invalid ExitCountKind!"); 7291 } 7292 7293 const SCEV * 7294 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7295 SCEVUnionPredicate &Preds) { 7296 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7297 } 7298 7299 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7300 ExitCountKind Kind) { 7301 switch (Kind) { 7302 case Exact: 7303 return getBackedgeTakenInfo(L).getExact(L, this); 7304 case ConstantMaximum: 7305 return getBackedgeTakenInfo(L).getConstantMax(this); 7306 case SymbolicMaximum: 7307 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7308 }; 7309 llvm_unreachable("Invalid ExitCountKind!"); 7310 } 7311 7312 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7313 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7314 } 7315 7316 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7317 static void 7318 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7319 BasicBlock *Header = L->getHeader(); 7320 7321 // Push all Loop-header PHIs onto the Worklist stack. 7322 for (PHINode &PN : Header->phis()) 7323 Worklist.push_back(&PN); 7324 } 7325 7326 const ScalarEvolution::BackedgeTakenInfo & 7327 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7328 auto &BTI = getBackedgeTakenInfo(L); 7329 if (BTI.hasFullInfo()) 7330 return BTI; 7331 7332 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7333 7334 if (!Pair.second) 7335 return Pair.first->second; 7336 7337 BackedgeTakenInfo Result = 7338 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7339 7340 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7341 } 7342 7343 ScalarEvolution::BackedgeTakenInfo & 7344 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7345 // Initially insert an invalid entry for this loop. If the insertion 7346 // succeeds, proceed to actually compute a backedge-taken count and 7347 // update the value. The temporary CouldNotCompute value tells SCEV 7348 // code elsewhere that it shouldn't attempt to request a new 7349 // backedge-taken count, which could result in infinite recursion. 7350 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7351 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7352 if (!Pair.second) 7353 return Pair.first->second; 7354 7355 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7356 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7357 // must be cleared in this scope. 7358 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7359 7360 // In product build, there are no usage of statistic. 7361 (void)NumTripCountsComputed; 7362 (void)NumTripCountsNotComputed; 7363 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7364 const SCEV *BEExact = Result.getExact(L, this); 7365 if (BEExact != getCouldNotCompute()) { 7366 assert(isLoopInvariant(BEExact, L) && 7367 isLoopInvariant(Result.getConstantMax(this), L) && 7368 "Computed backedge-taken count isn't loop invariant for loop!"); 7369 ++NumTripCountsComputed; 7370 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7371 isa<PHINode>(L->getHeader()->begin())) { 7372 // Only count loops that have phi nodes as not being computable. 7373 ++NumTripCountsNotComputed; 7374 } 7375 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7376 7377 // Now that we know more about the trip count for this loop, forget any 7378 // existing SCEV values for PHI nodes in this loop since they are only 7379 // conservative estimates made without the benefit of trip count 7380 // information. This is similar to the code in forgetLoop, except that 7381 // it handles SCEVUnknown PHI nodes specially. 7382 if (Result.hasAnyInfo()) { 7383 SmallVector<Instruction *, 16> Worklist; 7384 PushLoopPHIs(L, Worklist); 7385 7386 SmallPtrSet<Instruction *, 8> Discovered; 7387 while (!Worklist.empty()) { 7388 Instruction *I = Worklist.pop_back_val(); 7389 7390 ValueExprMapType::iterator It = 7391 ValueExprMap.find_as(static_cast<Value *>(I)); 7392 if (It != ValueExprMap.end()) { 7393 const SCEV *Old = It->second; 7394 7395 // SCEVUnknown for a PHI either means that it has an unrecognized 7396 // structure, or it's a PHI that's in the progress of being computed 7397 // by createNodeForPHI. In the former case, additional loop trip 7398 // count information isn't going to change anything. In the later 7399 // case, createNodeForPHI will perform the necessary updates on its 7400 // own when it gets to that point. 7401 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7402 eraseValueFromMap(It->first); 7403 forgetMemoizedResults(Old); 7404 } 7405 if (PHINode *PN = dyn_cast<PHINode>(I)) 7406 ConstantEvolutionLoopExitValue.erase(PN); 7407 } 7408 7409 // Since we don't need to invalidate anything for correctness and we're 7410 // only invalidating to make SCEV's results more precise, we get to stop 7411 // early to avoid invalidating too much. This is especially important in 7412 // cases like: 7413 // 7414 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7415 // loop0: 7416 // %pn0 = phi 7417 // ... 7418 // loop1: 7419 // %pn1 = phi 7420 // ... 7421 // 7422 // where both loop0 and loop1's backedge taken count uses the SCEV 7423 // expression for %v. If we don't have the early stop below then in cases 7424 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7425 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7426 // count for loop1, effectively nullifying SCEV's trip count cache. 7427 for (auto *U : I->users()) 7428 if (auto *I = dyn_cast<Instruction>(U)) { 7429 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7430 if (LoopForUser && L->contains(LoopForUser) && 7431 Discovered.insert(I).second) 7432 Worklist.push_back(I); 7433 } 7434 } 7435 } 7436 7437 // Re-lookup the insert position, since the call to 7438 // computeBackedgeTakenCount above could result in a 7439 // recusive call to getBackedgeTakenInfo (on a different 7440 // loop), which would invalidate the iterator computed 7441 // earlier. 7442 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7443 } 7444 7445 void ScalarEvolution::forgetAllLoops() { 7446 // This method is intended to forget all info about loops. It should 7447 // invalidate caches as if the following happened: 7448 // - The trip counts of all loops have changed arbitrarily 7449 // - Every llvm::Value has been updated in place to produce a different 7450 // result. 7451 BackedgeTakenCounts.clear(); 7452 PredicatedBackedgeTakenCounts.clear(); 7453 LoopPropertiesCache.clear(); 7454 ConstantEvolutionLoopExitValue.clear(); 7455 ValueExprMap.clear(); 7456 ValuesAtScopes.clear(); 7457 LoopDispositions.clear(); 7458 BlockDispositions.clear(); 7459 UnsignedRanges.clear(); 7460 SignedRanges.clear(); 7461 ExprValueMap.clear(); 7462 HasRecMap.clear(); 7463 MinTrailingZerosCache.clear(); 7464 PredicatedSCEVRewrites.clear(); 7465 } 7466 7467 void ScalarEvolution::forgetLoop(const Loop *L) { 7468 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7469 SmallVector<Instruction *, 32> Worklist; 7470 SmallPtrSet<Instruction *, 16> Visited; 7471 7472 // Iterate over all the loops and sub-loops to drop SCEV information. 7473 while (!LoopWorklist.empty()) { 7474 auto *CurrL = LoopWorklist.pop_back_val(); 7475 7476 // Drop any stored trip count value. 7477 BackedgeTakenCounts.erase(CurrL); 7478 PredicatedBackedgeTakenCounts.erase(CurrL); 7479 7480 // Drop information about predicated SCEV rewrites for this loop. 7481 for (auto I = PredicatedSCEVRewrites.begin(); 7482 I != PredicatedSCEVRewrites.end();) { 7483 std::pair<const SCEV *, const Loop *> Entry = I->first; 7484 if (Entry.second == CurrL) 7485 PredicatedSCEVRewrites.erase(I++); 7486 else 7487 ++I; 7488 } 7489 7490 auto LoopUsersItr = LoopUsers.find(CurrL); 7491 if (LoopUsersItr != LoopUsers.end()) { 7492 for (auto *S : LoopUsersItr->second) 7493 forgetMemoizedResults(S); 7494 LoopUsers.erase(LoopUsersItr); 7495 } 7496 7497 // Drop information about expressions based on loop-header PHIs. 7498 PushLoopPHIs(CurrL, Worklist); 7499 7500 while (!Worklist.empty()) { 7501 Instruction *I = Worklist.pop_back_val(); 7502 if (!Visited.insert(I).second) 7503 continue; 7504 7505 ValueExprMapType::iterator It = 7506 ValueExprMap.find_as(static_cast<Value *>(I)); 7507 if (It != ValueExprMap.end()) { 7508 eraseValueFromMap(It->first); 7509 forgetMemoizedResults(It->second); 7510 if (PHINode *PN = dyn_cast<PHINode>(I)) 7511 ConstantEvolutionLoopExitValue.erase(PN); 7512 } 7513 7514 PushDefUseChildren(I, Worklist); 7515 } 7516 7517 LoopPropertiesCache.erase(CurrL); 7518 // Forget all contained loops too, to avoid dangling entries in the 7519 // ValuesAtScopes map. 7520 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7521 } 7522 } 7523 7524 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7525 while (Loop *Parent = L->getParentLoop()) 7526 L = Parent; 7527 forgetLoop(L); 7528 } 7529 7530 void ScalarEvolution::forgetValue(Value *V) { 7531 Instruction *I = dyn_cast<Instruction>(V); 7532 if (!I) return; 7533 7534 // Drop information about expressions based on loop-header PHIs. 7535 SmallVector<Instruction *, 16> Worklist; 7536 Worklist.push_back(I); 7537 7538 SmallPtrSet<Instruction *, 8> Visited; 7539 while (!Worklist.empty()) { 7540 I = Worklist.pop_back_val(); 7541 if (!Visited.insert(I).second) 7542 continue; 7543 7544 ValueExprMapType::iterator It = 7545 ValueExprMap.find_as(static_cast<Value *>(I)); 7546 if (It != ValueExprMap.end()) { 7547 eraseValueFromMap(It->first); 7548 forgetMemoizedResults(It->second); 7549 if (PHINode *PN = dyn_cast<PHINode>(I)) 7550 ConstantEvolutionLoopExitValue.erase(PN); 7551 } 7552 7553 PushDefUseChildren(I, Worklist); 7554 } 7555 } 7556 7557 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7558 LoopDispositions.clear(); 7559 } 7560 7561 /// Get the exact loop backedge taken count considering all loop exits. A 7562 /// computable result can only be returned for loops with all exiting blocks 7563 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7564 /// is never skipped. This is a valid assumption as long as the loop exits via 7565 /// that test. For precise results, it is the caller's responsibility to specify 7566 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7567 const SCEV * 7568 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7569 SCEVUnionPredicate *Preds) const { 7570 // If any exits were not computable, the loop is not computable. 7571 if (!isComplete() || ExitNotTaken.empty()) 7572 return SE->getCouldNotCompute(); 7573 7574 const BasicBlock *Latch = L->getLoopLatch(); 7575 // All exiting blocks we have collected must dominate the only backedge. 7576 if (!Latch) 7577 return SE->getCouldNotCompute(); 7578 7579 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7580 // count is simply a minimum out of all these calculated exit counts. 7581 SmallVector<const SCEV *, 2> Ops; 7582 for (auto &ENT : ExitNotTaken) { 7583 const SCEV *BECount = ENT.ExactNotTaken; 7584 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7585 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7586 "We should only have known counts for exiting blocks that dominate " 7587 "latch!"); 7588 7589 Ops.push_back(BECount); 7590 7591 if (Preds && !ENT.hasAlwaysTruePredicate()) 7592 Preds->add(ENT.Predicate.get()); 7593 7594 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7595 "Predicate should be always true!"); 7596 } 7597 7598 return SE->getUMinFromMismatchedTypes(Ops); 7599 } 7600 7601 /// Get the exact not taken count for this loop exit. 7602 const SCEV * 7603 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7604 ScalarEvolution *SE) const { 7605 for (auto &ENT : ExitNotTaken) 7606 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7607 return ENT.ExactNotTaken; 7608 7609 return SE->getCouldNotCompute(); 7610 } 7611 7612 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7613 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7614 for (auto &ENT : ExitNotTaken) 7615 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7616 return ENT.MaxNotTaken; 7617 7618 return SE->getCouldNotCompute(); 7619 } 7620 7621 /// getConstantMax - Get the constant max backedge taken count for the loop. 7622 const SCEV * 7623 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7624 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7625 return !ENT.hasAlwaysTruePredicate(); 7626 }; 7627 7628 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7629 return SE->getCouldNotCompute(); 7630 7631 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7632 isa<SCEVConstant>(getConstantMax())) && 7633 "No point in having a non-constant max backedge taken count!"); 7634 return getConstantMax(); 7635 } 7636 7637 const SCEV * 7638 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7639 ScalarEvolution *SE) { 7640 if (!SymbolicMax) 7641 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7642 return SymbolicMax; 7643 } 7644 7645 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7646 ScalarEvolution *SE) const { 7647 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7648 return !ENT.hasAlwaysTruePredicate(); 7649 }; 7650 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7651 } 7652 7653 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7654 return Operands.contains(S); 7655 } 7656 7657 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7658 : ExitLimit(E, E, false, None) { 7659 } 7660 7661 ScalarEvolution::ExitLimit::ExitLimit( 7662 const SCEV *E, const SCEV *M, bool MaxOrZero, 7663 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7664 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7665 // If we prove the max count is zero, so is the symbolic bound. This happens 7666 // in practice due to differences in a) how context sensitive we've chosen 7667 // to be and b) how we reason about bounds impied by UB. 7668 if (MaxNotTaken->isZero()) 7669 ExactNotTaken = MaxNotTaken; 7670 7671 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7672 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7673 "Exact is not allowed to be less precise than Max"); 7674 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7675 isa<SCEVConstant>(MaxNotTaken)) && 7676 "No point in having a non-constant max backedge taken count!"); 7677 for (auto *PredSet : PredSetList) 7678 for (auto *P : *PredSet) 7679 addPredicate(P); 7680 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 7681 "Backedge count should be int"); 7682 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 7683 "Max backedge count should be int"); 7684 } 7685 7686 ScalarEvolution::ExitLimit::ExitLimit( 7687 const SCEV *E, const SCEV *M, bool MaxOrZero, 7688 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7689 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7690 } 7691 7692 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7693 bool MaxOrZero) 7694 : ExitLimit(E, M, MaxOrZero, None) { 7695 } 7696 7697 class SCEVRecordOperands { 7698 SmallPtrSetImpl<const SCEV *> &Operands; 7699 7700 public: 7701 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7702 : Operands(Operands) {} 7703 bool follow(const SCEV *S) { 7704 Operands.insert(S); 7705 return true; 7706 } 7707 bool isDone() { return false; } 7708 }; 7709 7710 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7711 /// computable exit into a persistent ExitNotTakenInfo array. 7712 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7713 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7714 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7715 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7716 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7717 7718 ExitNotTaken.reserve(ExitCounts.size()); 7719 std::transform( 7720 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7721 [&](const EdgeExitInfo &EEI) { 7722 BasicBlock *ExitBB = EEI.first; 7723 const ExitLimit &EL = EEI.second; 7724 if (EL.Predicates.empty()) 7725 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7726 nullptr); 7727 7728 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7729 for (auto *Pred : EL.Predicates) 7730 Predicate->add(Pred); 7731 7732 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7733 std::move(Predicate)); 7734 }); 7735 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7736 isa<SCEVConstant>(ConstantMax)) && 7737 "No point in having a non-constant max backedge taken count!"); 7738 7739 SCEVRecordOperands RecordOperands(Operands); 7740 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7741 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7742 ST.visitAll(ConstantMax); 7743 for (auto &ENT : ExitNotTaken) 7744 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7745 ST.visitAll(ENT.ExactNotTaken); 7746 } 7747 7748 /// Compute the number of times the backedge of the specified loop will execute. 7749 ScalarEvolution::BackedgeTakenInfo 7750 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7751 bool AllowPredicates) { 7752 SmallVector<BasicBlock *, 8> ExitingBlocks; 7753 L->getExitingBlocks(ExitingBlocks); 7754 7755 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7756 7757 SmallVector<EdgeExitInfo, 4> ExitCounts; 7758 bool CouldComputeBECount = true; 7759 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7760 const SCEV *MustExitMaxBECount = nullptr; 7761 const SCEV *MayExitMaxBECount = nullptr; 7762 bool MustExitMaxOrZero = false; 7763 7764 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7765 // and compute maxBECount. 7766 // Do a union of all the predicates here. 7767 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7768 BasicBlock *ExitBB = ExitingBlocks[i]; 7769 7770 // We canonicalize untaken exits to br (constant), ignore them so that 7771 // proving an exit untaken doesn't negatively impact our ability to reason 7772 // about the loop as whole. 7773 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7774 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7775 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7776 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7777 continue; 7778 } 7779 7780 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7781 7782 assert((AllowPredicates || EL.Predicates.empty()) && 7783 "Predicated exit limit when predicates are not allowed!"); 7784 7785 // 1. For each exit that can be computed, add an entry to ExitCounts. 7786 // CouldComputeBECount is true only if all exits can be computed. 7787 if (EL.ExactNotTaken == getCouldNotCompute()) 7788 // We couldn't compute an exact value for this exit, so 7789 // we won't be able to compute an exact value for the loop. 7790 CouldComputeBECount = false; 7791 else 7792 ExitCounts.emplace_back(ExitBB, EL); 7793 7794 // 2. Derive the loop's MaxBECount from each exit's max number of 7795 // non-exiting iterations. Partition the loop exits into two kinds: 7796 // LoopMustExits and LoopMayExits. 7797 // 7798 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7799 // is a LoopMayExit. If any computable LoopMustExit is found, then 7800 // MaxBECount is the minimum EL.MaxNotTaken of computable 7801 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7802 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7803 // computable EL.MaxNotTaken. 7804 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7805 DT.dominates(ExitBB, Latch)) { 7806 if (!MustExitMaxBECount) { 7807 MustExitMaxBECount = EL.MaxNotTaken; 7808 MustExitMaxOrZero = EL.MaxOrZero; 7809 } else { 7810 MustExitMaxBECount = 7811 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7812 } 7813 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7814 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7815 MayExitMaxBECount = EL.MaxNotTaken; 7816 else { 7817 MayExitMaxBECount = 7818 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7819 } 7820 } 7821 } 7822 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7823 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7824 // The loop backedge will be taken the maximum or zero times if there's 7825 // a single exit that must be taken the maximum or zero times. 7826 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7827 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7828 MaxBECount, MaxOrZero); 7829 } 7830 7831 ScalarEvolution::ExitLimit 7832 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7833 bool AllowPredicates) { 7834 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7835 // If our exiting block does not dominate the latch, then its connection with 7836 // loop's exit limit may be far from trivial. 7837 const BasicBlock *Latch = L->getLoopLatch(); 7838 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7839 return getCouldNotCompute(); 7840 7841 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7842 Instruction *Term = ExitingBlock->getTerminator(); 7843 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7844 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7845 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7846 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7847 "It should have one successor in loop and one exit block!"); 7848 // Proceed to the next level to examine the exit condition expression. 7849 return computeExitLimitFromCond( 7850 L, BI->getCondition(), ExitIfTrue, 7851 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7852 } 7853 7854 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7855 // For switch, make sure that there is a single exit from the loop. 7856 BasicBlock *Exit = nullptr; 7857 for (auto *SBB : successors(ExitingBlock)) 7858 if (!L->contains(SBB)) { 7859 if (Exit) // Multiple exit successors. 7860 return getCouldNotCompute(); 7861 Exit = SBB; 7862 } 7863 assert(Exit && "Exiting block must have at least one exit"); 7864 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7865 /*ControlsExit=*/IsOnlyExit); 7866 } 7867 7868 return getCouldNotCompute(); 7869 } 7870 7871 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7872 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7873 bool ControlsExit, bool AllowPredicates) { 7874 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7875 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7876 ControlsExit, AllowPredicates); 7877 } 7878 7879 Optional<ScalarEvolution::ExitLimit> 7880 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7881 bool ExitIfTrue, bool ControlsExit, 7882 bool AllowPredicates) { 7883 (void)this->L; 7884 (void)this->ExitIfTrue; 7885 (void)this->AllowPredicates; 7886 7887 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7888 this->AllowPredicates == AllowPredicates && 7889 "Variance in assumed invariant key components!"); 7890 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7891 if (Itr == TripCountMap.end()) 7892 return None; 7893 return Itr->second; 7894 } 7895 7896 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7897 bool ExitIfTrue, 7898 bool ControlsExit, 7899 bool AllowPredicates, 7900 const ExitLimit &EL) { 7901 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7902 this->AllowPredicates == AllowPredicates && 7903 "Variance in assumed invariant key components!"); 7904 7905 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7906 assert(InsertResult.second && "Expected successful insertion!"); 7907 (void)InsertResult; 7908 (void)ExitIfTrue; 7909 } 7910 7911 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7912 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7913 bool ControlsExit, bool AllowPredicates) { 7914 7915 if (auto MaybeEL = 7916 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7917 return *MaybeEL; 7918 7919 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7920 ControlsExit, AllowPredicates); 7921 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7922 return EL; 7923 } 7924 7925 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7926 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7927 bool ControlsExit, bool AllowPredicates) { 7928 // Handle BinOp conditions (And, Or). 7929 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7930 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7931 return *LimitFromBinOp; 7932 7933 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7934 // Proceed to the next level to examine the icmp. 7935 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7936 ExitLimit EL = 7937 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7938 if (EL.hasFullInfo() || !AllowPredicates) 7939 return EL; 7940 7941 // Try again, but use SCEV predicates this time. 7942 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7943 /*AllowPredicates=*/true); 7944 } 7945 7946 // Check for a constant condition. These are normally stripped out by 7947 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7948 // preserve the CFG and is temporarily leaving constant conditions 7949 // in place. 7950 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7951 if (ExitIfTrue == !CI->getZExtValue()) 7952 // The backedge is always taken. 7953 return getCouldNotCompute(); 7954 else 7955 // The backedge is never taken. 7956 return getZero(CI->getType()); 7957 } 7958 7959 // If it's not an integer or pointer comparison then compute it the hard way. 7960 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7961 } 7962 7963 Optional<ScalarEvolution::ExitLimit> 7964 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7965 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7966 bool ControlsExit, bool AllowPredicates) { 7967 // Check if the controlling expression for this loop is an And or Or. 7968 Value *Op0, *Op1; 7969 bool IsAnd = false; 7970 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7971 IsAnd = true; 7972 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7973 IsAnd = false; 7974 else 7975 return None; 7976 7977 // EitherMayExit is true in these two cases: 7978 // br (and Op0 Op1), loop, exit 7979 // br (or Op0 Op1), exit, loop 7980 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7981 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7982 ControlsExit && !EitherMayExit, 7983 AllowPredicates); 7984 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7985 ControlsExit && !EitherMayExit, 7986 AllowPredicates); 7987 7988 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7989 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7990 if (isa<ConstantInt>(Op1)) 7991 return Op1 == NeutralElement ? EL0 : EL1; 7992 if (isa<ConstantInt>(Op0)) 7993 return Op0 == NeutralElement ? EL1 : EL0; 7994 7995 const SCEV *BECount = getCouldNotCompute(); 7996 const SCEV *MaxBECount = getCouldNotCompute(); 7997 if (EitherMayExit) { 7998 // Both conditions must be same for the loop to continue executing. 7999 // Choose the less conservative count. 8000 // If ExitCond is a short-circuit form (select), using 8001 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 8002 // To see the detailed examples, please see 8003 // test/Analysis/ScalarEvolution/exit-count-select.ll 8004 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 8005 if (!PoisonSafe) 8006 // Even if ExitCond is select, we can safely derive BECount using both 8007 // EL0 and EL1 in these cases: 8008 // (1) EL0.ExactNotTaken is non-zero 8009 // (2) EL1.ExactNotTaken is non-poison 8010 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 8011 // it cannot be umin(0, ..)) 8012 // The PoisonSafe assignment below is simplified and the assertion after 8013 // BECount calculation fully guarantees the condition (3). 8014 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 8015 isa<SCEVConstant>(EL1.ExactNotTaken); 8016 if (EL0.ExactNotTaken != getCouldNotCompute() && 8017 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 8018 BECount = 8019 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 8020 8021 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8022 // it should have been simplified to zero (see the condition (3) above) 8023 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8024 BECount->isZero()); 8025 } 8026 if (EL0.MaxNotTaken == getCouldNotCompute()) 8027 MaxBECount = EL1.MaxNotTaken; 8028 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8029 MaxBECount = EL0.MaxNotTaken; 8030 else 8031 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8032 } else { 8033 // Both conditions must be same at the same time for the loop to exit. 8034 // For now, be conservative. 8035 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8036 BECount = EL0.ExactNotTaken; 8037 } 8038 8039 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8040 // to be more aggressive when computing BECount than when computing 8041 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8042 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8043 // to not. 8044 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8045 !isa<SCEVCouldNotCompute>(BECount)) 8046 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8047 8048 return ExitLimit(BECount, MaxBECount, false, 8049 { &EL0.Predicates, &EL1.Predicates }); 8050 } 8051 8052 ScalarEvolution::ExitLimit 8053 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8054 ICmpInst *ExitCond, 8055 bool ExitIfTrue, 8056 bool ControlsExit, 8057 bool AllowPredicates) { 8058 // If the condition was exit on true, convert the condition to exit on false 8059 ICmpInst::Predicate Pred; 8060 if (!ExitIfTrue) 8061 Pred = ExitCond->getPredicate(); 8062 else 8063 Pred = ExitCond->getInversePredicate(); 8064 const ICmpInst::Predicate OriginalPred = Pred; 8065 8066 // Handle common loops like: for (X = "string"; *X; ++X) 8067 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 8068 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 8069 ExitLimit ItCnt = 8070 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 8071 if (ItCnt.hasAnyInfo()) 8072 return ItCnt; 8073 } 8074 8075 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8076 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8077 8078 // Try to evaluate any dependencies out of the loop. 8079 LHS = getSCEVAtScope(LHS, L); 8080 RHS = getSCEVAtScope(RHS, L); 8081 8082 // At this point, we would like to compute how many iterations of the 8083 // loop the predicate will return true for these inputs. 8084 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8085 // If there is a loop-invariant, force it into the RHS. 8086 std::swap(LHS, RHS); 8087 Pred = ICmpInst::getSwappedPredicate(Pred); 8088 } 8089 8090 // Simplify the operands before analyzing them. 8091 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8092 8093 // If we have a comparison of a chrec against a constant, try to use value 8094 // ranges to answer this query. 8095 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8096 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8097 if (AddRec->getLoop() == L) { 8098 // Form the constant range. 8099 ConstantRange CompRange = 8100 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8101 8102 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8103 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8104 } 8105 8106 switch (Pred) { 8107 case ICmpInst::ICMP_NE: { // while (X != Y) 8108 // Convert to: while (X-Y != 0) 8109 if (LHS->getType()->isPointerTy()) { 8110 LHS = getLosslessPtrToIntExpr(LHS); 8111 if (isa<SCEVCouldNotCompute>(LHS)) 8112 return LHS; 8113 } 8114 if (RHS->getType()->isPointerTy()) { 8115 RHS = getLosslessPtrToIntExpr(RHS); 8116 if (isa<SCEVCouldNotCompute>(RHS)) 8117 return RHS; 8118 } 8119 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8120 AllowPredicates); 8121 if (EL.hasAnyInfo()) return EL; 8122 break; 8123 } 8124 case ICmpInst::ICMP_EQ: { // while (X == Y) 8125 // Convert to: while (X-Y == 0) 8126 if (LHS->getType()->isPointerTy()) { 8127 LHS = getLosslessPtrToIntExpr(LHS); 8128 if (isa<SCEVCouldNotCompute>(LHS)) 8129 return LHS; 8130 } 8131 if (RHS->getType()->isPointerTy()) { 8132 RHS = getLosslessPtrToIntExpr(RHS); 8133 if (isa<SCEVCouldNotCompute>(RHS)) 8134 return RHS; 8135 } 8136 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8137 if (EL.hasAnyInfo()) return EL; 8138 break; 8139 } 8140 case ICmpInst::ICMP_SLT: 8141 case ICmpInst::ICMP_ULT: { // while (X < Y) 8142 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8143 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8144 AllowPredicates); 8145 if (EL.hasAnyInfo()) return EL; 8146 break; 8147 } 8148 case ICmpInst::ICMP_SGT: 8149 case ICmpInst::ICMP_UGT: { // while (X > Y) 8150 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8151 ExitLimit EL = 8152 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8153 AllowPredicates); 8154 if (EL.hasAnyInfo()) return EL; 8155 break; 8156 } 8157 default: 8158 break; 8159 } 8160 8161 auto *ExhaustiveCount = 8162 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8163 8164 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8165 return ExhaustiveCount; 8166 8167 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8168 ExitCond->getOperand(1), L, OriginalPred); 8169 } 8170 8171 ScalarEvolution::ExitLimit 8172 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8173 SwitchInst *Switch, 8174 BasicBlock *ExitingBlock, 8175 bool ControlsExit) { 8176 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8177 8178 // Give up if the exit is the default dest of a switch. 8179 if (Switch->getDefaultDest() == ExitingBlock) 8180 return getCouldNotCompute(); 8181 8182 assert(L->contains(Switch->getDefaultDest()) && 8183 "Default case must not exit the loop!"); 8184 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8185 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8186 8187 // while (X != Y) --> while (X-Y != 0) 8188 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8189 if (EL.hasAnyInfo()) 8190 return EL; 8191 8192 return getCouldNotCompute(); 8193 } 8194 8195 static ConstantInt * 8196 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8197 ScalarEvolution &SE) { 8198 const SCEV *InVal = SE.getConstant(C); 8199 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8200 assert(isa<SCEVConstant>(Val) && 8201 "Evaluation of SCEV at constant didn't fold correctly?"); 8202 return cast<SCEVConstant>(Val)->getValue(); 8203 } 8204 8205 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8206 /// compute the backedge execution count. 8207 ScalarEvolution::ExitLimit 8208 ScalarEvolution::computeLoadConstantCompareExitLimit( 8209 LoadInst *LI, 8210 Constant *RHS, 8211 const Loop *L, 8212 ICmpInst::Predicate predicate) { 8213 if (LI->isVolatile()) return getCouldNotCompute(); 8214 8215 // Check to see if the loaded pointer is a getelementptr of a global. 8216 // TODO: Use SCEV instead of manually grubbing with GEPs. 8217 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8218 if (!GEP) return getCouldNotCompute(); 8219 8220 // Make sure that it is really a constant global we are gepping, with an 8221 // initializer, and make sure the first IDX is really 0. 8222 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8223 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8224 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8225 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8226 return getCouldNotCompute(); 8227 8228 // Okay, we allow one non-constant index into the GEP instruction. 8229 Value *VarIdx = nullptr; 8230 std::vector<Constant*> Indexes; 8231 unsigned VarIdxNum = 0; 8232 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8233 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8234 Indexes.push_back(CI); 8235 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8236 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8237 VarIdx = GEP->getOperand(i); 8238 VarIdxNum = i-2; 8239 Indexes.push_back(nullptr); 8240 } 8241 8242 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8243 if (!VarIdx) 8244 return getCouldNotCompute(); 8245 8246 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8247 // Check to see if X is a loop variant variable value now. 8248 const SCEV *Idx = getSCEV(VarIdx); 8249 Idx = getSCEVAtScope(Idx, L); 8250 8251 // We can only recognize very limited forms of loop index expressions, in 8252 // particular, only affine AddRec's like {C1,+,C2}<L>. 8253 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8254 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8255 isLoopInvariant(IdxExpr, L) || 8256 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8257 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8258 return getCouldNotCompute(); 8259 8260 unsigned MaxSteps = MaxBruteForceIterations; 8261 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8262 ConstantInt *ItCst = ConstantInt::get( 8263 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8264 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8265 8266 // Form the GEP offset. 8267 Indexes[VarIdxNum] = Val; 8268 8269 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8270 Indexes); 8271 if (!Result) break; // Cannot compute! 8272 8273 // Evaluate the condition for this iteration. 8274 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8275 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8276 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8277 ++NumArrayLenItCounts; 8278 return getConstant(ItCst); // Found terminating iteration! 8279 } 8280 } 8281 return getCouldNotCompute(); 8282 } 8283 8284 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8285 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8286 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8287 if (!RHS) 8288 return getCouldNotCompute(); 8289 8290 const BasicBlock *Latch = L->getLoopLatch(); 8291 if (!Latch) 8292 return getCouldNotCompute(); 8293 8294 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8295 if (!Predecessor) 8296 return getCouldNotCompute(); 8297 8298 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8299 // Return LHS in OutLHS and shift_opt in OutOpCode. 8300 auto MatchPositiveShift = 8301 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8302 8303 using namespace PatternMatch; 8304 8305 ConstantInt *ShiftAmt; 8306 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8307 OutOpCode = Instruction::LShr; 8308 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8309 OutOpCode = Instruction::AShr; 8310 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8311 OutOpCode = Instruction::Shl; 8312 else 8313 return false; 8314 8315 return ShiftAmt->getValue().isStrictlyPositive(); 8316 }; 8317 8318 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8319 // 8320 // loop: 8321 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8322 // %iv.shifted = lshr i32 %iv, <positive constant> 8323 // 8324 // Return true on a successful match. Return the corresponding PHI node (%iv 8325 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8326 auto MatchShiftRecurrence = 8327 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8328 Optional<Instruction::BinaryOps> PostShiftOpCode; 8329 8330 { 8331 Instruction::BinaryOps OpC; 8332 Value *V; 8333 8334 // If we encounter a shift instruction, "peel off" the shift operation, 8335 // and remember that we did so. Later when we inspect %iv's backedge 8336 // value, we will make sure that the backedge value uses the same 8337 // operation. 8338 // 8339 // Note: the peeled shift operation does not have to be the same 8340 // instruction as the one feeding into the PHI's backedge value. We only 8341 // really care about it being the same *kind* of shift instruction -- 8342 // that's all that is required for our later inferences to hold. 8343 if (MatchPositiveShift(LHS, V, OpC)) { 8344 PostShiftOpCode = OpC; 8345 LHS = V; 8346 } 8347 } 8348 8349 PNOut = dyn_cast<PHINode>(LHS); 8350 if (!PNOut || PNOut->getParent() != L->getHeader()) 8351 return false; 8352 8353 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8354 Value *OpLHS; 8355 8356 return 8357 // The backedge value for the PHI node must be a shift by a positive 8358 // amount 8359 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8360 8361 // of the PHI node itself 8362 OpLHS == PNOut && 8363 8364 // and the kind of shift should be match the kind of shift we peeled 8365 // off, if any. 8366 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8367 }; 8368 8369 PHINode *PN; 8370 Instruction::BinaryOps OpCode; 8371 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8372 return getCouldNotCompute(); 8373 8374 const DataLayout &DL = getDataLayout(); 8375 8376 // The key rationale for this optimization is that for some kinds of shift 8377 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8378 // within a finite number of iterations. If the condition guarding the 8379 // backedge (in the sense that the backedge is taken if the condition is true) 8380 // is false for the value the shift recurrence stabilizes to, then we know 8381 // that the backedge is taken only a finite number of times. 8382 8383 ConstantInt *StableValue = nullptr; 8384 switch (OpCode) { 8385 default: 8386 llvm_unreachable("Impossible case!"); 8387 8388 case Instruction::AShr: { 8389 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8390 // bitwidth(K) iterations. 8391 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8392 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8393 Predecessor->getTerminator(), &DT); 8394 auto *Ty = cast<IntegerType>(RHS->getType()); 8395 if (Known.isNonNegative()) 8396 StableValue = ConstantInt::get(Ty, 0); 8397 else if (Known.isNegative()) 8398 StableValue = ConstantInt::get(Ty, -1, true); 8399 else 8400 return getCouldNotCompute(); 8401 8402 break; 8403 } 8404 case Instruction::LShr: 8405 case Instruction::Shl: 8406 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8407 // stabilize to 0 in at most bitwidth(K) iterations. 8408 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8409 break; 8410 } 8411 8412 auto *Result = 8413 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8414 assert(Result->getType()->isIntegerTy(1) && 8415 "Otherwise cannot be an operand to a branch instruction"); 8416 8417 if (Result->isZeroValue()) { 8418 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8419 const SCEV *UpperBound = 8420 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8421 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8422 } 8423 8424 return getCouldNotCompute(); 8425 } 8426 8427 /// Return true if we can constant fold an instruction of the specified type, 8428 /// assuming that all operands were constants. 8429 static bool CanConstantFold(const Instruction *I) { 8430 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8431 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8432 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8433 return true; 8434 8435 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8436 if (const Function *F = CI->getCalledFunction()) 8437 return canConstantFoldCallTo(CI, F); 8438 return false; 8439 } 8440 8441 /// Determine whether this instruction can constant evolve within this loop 8442 /// assuming its operands can all constant evolve. 8443 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8444 // An instruction outside of the loop can't be derived from a loop PHI. 8445 if (!L->contains(I)) return false; 8446 8447 if (isa<PHINode>(I)) { 8448 // We don't currently keep track of the control flow needed to evaluate 8449 // PHIs, so we cannot handle PHIs inside of loops. 8450 return L->getHeader() == I->getParent(); 8451 } 8452 8453 // If we won't be able to constant fold this expression even if the operands 8454 // are constants, bail early. 8455 return CanConstantFold(I); 8456 } 8457 8458 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8459 /// recursing through each instruction operand until reaching a loop header phi. 8460 static PHINode * 8461 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8462 DenseMap<Instruction *, PHINode *> &PHIMap, 8463 unsigned Depth) { 8464 if (Depth > MaxConstantEvolvingDepth) 8465 return nullptr; 8466 8467 // Otherwise, we can evaluate this instruction if all of its operands are 8468 // constant or derived from a PHI node themselves. 8469 PHINode *PHI = nullptr; 8470 for (Value *Op : UseInst->operands()) { 8471 if (isa<Constant>(Op)) continue; 8472 8473 Instruction *OpInst = dyn_cast<Instruction>(Op); 8474 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8475 8476 PHINode *P = dyn_cast<PHINode>(OpInst); 8477 if (!P) 8478 // If this operand is already visited, reuse the prior result. 8479 // We may have P != PHI if this is the deepest point at which the 8480 // inconsistent paths meet. 8481 P = PHIMap.lookup(OpInst); 8482 if (!P) { 8483 // Recurse and memoize the results, whether a phi is found or not. 8484 // This recursive call invalidates pointers into PHIMap. 8485 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8486 PHIMap[OpInst] = P; 8487 } 8488 if (!P) 8489 return nullptr; // Not evolving from PHI 8490 if (PHI && PHI != P) 8491 return nullptr; // Evolving from multiple different PHIs. 8492 PHI = P; 8493 } 8494 // This is a expression evolving from a constant PHI! 8495 return PHI; 8496 } 8497 8498 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8499 /// in the loop that V is derived from. We allow arbitrary operations along the 8500 /// way, but the operands of an operation must either be constants or a value 8501 /// derived from a constant PHI. If this expression does not fit with these 8502 /// constraints, return null. 8503 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8504 Instruction *I = dyn_cast<Instruction>(V); 8505 if (!I || !canConstantEvolve(I, L)) return nullptr; 8506 8507 if (PHINode *PN = dyn_cast<PHINode>(I)) 8508 return PN; 8509 8510 // Record non-constant instructions contained by the loop. 8511 DenseMap<Instruction *, PHINode *> PHIMap; 8512 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8513 } 8514 8515 /// EvaluateExpression - Given an expression that passes the 8516 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8517 /// in the loop has the value PHIVal. If we can't fold this expression for some 8518 /// reason, return null. 8519 static Constant *EvaluateExpression(Value *V, const Loop *L, 8520 DenseMap<Instruction *, Constant *> &Vals, 8521 const DataLayout &DL, 8522 const TargetLibraryInfo *TLI) { 8523 // Convenient constant check, but redundant for recursive calls. 8524 if (Constant *C = dyn_cast<Constant>(V)) return C; 8525 Instruction *I = dyn_cast<Instruction>(V); 8526 if (!I) return nullptr; 8527 8528 if (Constant *C = Vals.lookup(I)) return C; 8529 8530 // An instruction inside the loop depends on a value outside the loop that we 8531 // weren't given a mapping for, or a value such as a call inside the loop. 8532 if (!canConstantEvolve(I, L)) return nullptr; 8533 8534 // An unmapped PHI can be due to a branch or another loop inside this loop, 8535 // or due to this not being the initial iteration through a loop where we 8536 // couldn't compute the evolution of this particular PHI last time. 8537 if (isa<PHINode>(I)) return nullptr; 8538 8539 std::vector<Constant*> Operands(I->getNumOperands()); 8540 8541 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8542 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8543 if (!Operand) { 8544 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8545 if (!Operands[i]) return nullptr; 8546 continue; 8547 } 8548 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8549 Vals[Operand] = C; 8550 if (!C) return nullptr; 8551 Operands[i] = C; 8552 } 8553 8554 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8555 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8556 Operands[1], DL, TLI); 8557 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8558 if (!LI->isVolatile()) 8559 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8560 } 8561 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8562 } 8563 8564 8565 // If every incoming value to PN except the one for BB is a specific Constant, 8566 // return that, else return nullptr. 8567 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8568 Constant *IncomingVal = nullptr; 8569 8570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8571 if (PN->getIncomingBlock(i) == BB) 8572 continue; 8573 8574 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8575 if (!CurrentVal) 8576 return nullptr; 8577 8578 if (IncomingVal != CurrentVal) { 8579 if (IncomingVal) 8580 return nullptr; 8581 IncomingVal = CurrentVal; 8582 } 8583 } 8584 8585 return IncomingVal; 8586 } 8587 8588 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8589 /// in the header of its containing loop, we know the loop executes a 8590 /// constant number of times, and the PHI node is just a recurrence 8591 /// involving constants, fold it. 8592 Constant * 8593 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8594 const APInt &BEs, 8595 const Loop *L) { 8596 auto I = ConstantEvolutionLoopExitValue.find(PN); 8597 if (I != ConstantEvolutionLoopExitValue.end()) 8598 return I->second; 8599 8600 if (BEs.ugt(MaxBruteForceIterations)) 8601 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8602 8603 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8604 8605 DenseMap<Instruction *, Constant *> CurrentIterVals; 8606 BasicBlock *Header = L->getHeader(); 8607 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8608 8609 BasicBlock *Latch = L->getLoopLatch(); 8610 if (!Latch) 8611 return nullptr; 8612 8613 for (PHINode &PHI : Header->phis()) { 8614 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8615 CurrentIterVals[&PHI] = StartCST; 8616 } 8617 if (!CurrentIterVals.count(PN)) 8618 return RetVal = nullptr; 8619 8620 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8621 8622 // Execute the loop symbolically to determine the exit value. 8623 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8624 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8625 8626 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8627 unsigned IterationNum = 0; 8628 const DataLayout &DL = getDataLayout(); 8629 for (; ; ++IterationNum) { 8630 if (IterationNum == NumIterations) 8631 return RetVal = CurrentIterVals[PN]; // Got exit value! 8632 8633 // Compute the value of the PHIs for the next iteration. 8634 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8635 DenseMap<Instruction *, Constant *> NextIterVals; 8636 Constant *NextPHI = 8637 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8638 if (!NextPHI) 8639 return nullptr; // Couldn't evaluate! 8640 NextIterVals[PN] = NextPHI; 8641 8642 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8643 8644 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8645 // cease to be able to evaluate one of them or if they stop evolving, 8646 // because that doesn't necessarily prevent us from computing PN. 8647 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8648 for (const auto &I : CurrentIterVals) { 8649 PHINode *PHI = dyn_cast<PHINode>(I.first); 8650 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8651 PHIsToCompute.emplace_back(PHI, I.second); 8652 } 8653 // We use two distinct loops because EvaluateExpression may invalidate any 8654 // iterators into CurrentIterVals. 8655 for (const auto &I : PHIsToCompute) { 8656 PHINode *PHI = I.first; 8657 Constant *&NextPHI = NextIterVals[PHI]; 8658 if (!NextPHI) { // Not already computed. 8659 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8660 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8661 } 8662 if (NextPHI != I.second) 8663 StoppedEvolving = false; 8664 } 8665 8666 // If all entries in CurrentIterVals == NextIterVals then we can stop 8667 // iterating, the loop can't continue to change. 8668 if (StoppedEvolving) 8669 return RetVal = CurrentIterVals[PN]; 8670 8671 CurrentIterVals.swap(NextIterVals); 8672 } 8673 } 8674 8675 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8676 Value *Cond, 8677 bool ExitWhen) { 8678 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8679 if (!PN) return getCouldNotCompute(); 8680 8681 // If the loop is canonicalized, the PHI will have exactly two entries. 8682 // That's the only form we support here. 8683 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8684 8685 DenseMap<Instruction *, Constant *> CurrentIterVals; 8686 BasicBlock *Header = L->getHeader(); 8687 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8688 8689 BasicBlock *Latch = L->getLoopLatch(); 8690 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8691 8692 for (PHINode &PHI : Header->phis()) { 8693 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8694 CurrentIterVals[&PHI] = StartCST; 8695 } 8696 if (!CurrentIterVals.count(PN)) 8697 return getCouldNotCompute(); 8698 8699 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8700 // the loop symbolically to determine when the condition gets a value of 8701 // "ExitWhen". 8702 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8703 const DataLayout &DL = getDataLayout(); 8704 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8705 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8706 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8707 8708 // Couldn't symbolically evaluate. 8709 if (!CondVal) return getCouldNotCompute(); 8710 8711 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8712 ++NumBruteForceTripCountsComputed; 8713 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8714 } 8715 8716 // Update all the PHI nodes for the next iteration. 8717 DenseMap<Instruction *, Constant *> NextIterVals; 8718 8719 // Create a list of which PHIs we need to compute. We want to do this before 8720 // calling EvaluateExpression on them because that may invalidate iterators 8721 // into CurrentIterVals. 8722 SmallVector<PHINode *, 8> PHIsToCompute; 8723 for (const auto &I : CurrentIterVals) { 8724 PHINode *PHI = dyn_cast<PHINode>(I.first); 8725 if (!PHI || PHI->getParent() != Header) continue; 8726 PHIsToCompute.push_back(PHI); 8727 } 8728 for (PHINode *PHI : PHIsToCompute) { 8729 Constant *&NextPHI = NextIterVals[PHI]; 8730 if (NextPHI) continue; // Already computed! 8731 8732 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8733 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8734 } 8735 CurrentIterVals.swap(NextIterVals); 8736 } 8737 8738 // Too many iterations were needed to evaluate. 8739 return getCouldNotCompute(); 8740 } 8741 8742 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8743 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8744 ValuesAtScopes[V]; 8745 // Check to see if we've folded this expression at this loop before. 8746 for (auto &LS : Values) 8747 if (LS.first == L) 8748 return LS.second ? LS.second : V; 8749 8750 Values.emplace_back(L, nullptr); 8751 8752 // Otherwise compute it. 8753 const SCEV *C = computeSCEVAtScope(V, L); 8754 for (auto &LS : reverse(ValuesAtScopes[V])) 8755 if (LS.first == L) { 8756 LS.second = C; 8757 break; 8758 } 8759 return C; 8760 } 8761 8762 /// This builds up a Constant using the ConstantExpr interface. That way, we 8763 /// will return Constants for objects which aren't represented by a 8764 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8765 /// Returns NULL if the SCEV isn't representable as a Constant. 8766 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8767 switch (V->getSCEVType()) { 8768 case scCouldNotCompute: 8769 case scAddRecExpr: 8770 return nullptr; 8771 case scConstant: 8772 return cast<SCEVConstant>(V)->getValue(); 8773 case scUnknown: 8774 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8775 case scSignExtend: { 8776 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8777 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8778 return ConstantExpr::getSExt(CastOp, SS->getType()); 8779 return nullptr; 8780 } 8781 case scZeroExtend: { 8782 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8783 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8784 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8785 return nullptr; 8786 } 8787 case scPtrToInt: { 8788 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8789 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8790 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8791 8792 return nullptr; 8793 } 8794 case scTruncate: { 8795 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8796 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8797 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8798 return nullptr; 8799 } 8800 case scAddExpr: { 8801 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8802 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8803 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8804 unsigned AS = PTy->getAddressSpace(); 8805 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8806 C = ConstantExpr::getBitCast(C, DestPtrTy); 8807 } 8808 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8809 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8810 if (!C2) 8811 return nullptr; 8812 8813 // First pointer! 8814 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8815 unsigned AS = C2->getType()->getPointerAddressSpace(); 8816 std::swap(C, C2); 8817 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8818 // The offsets have been converted to bytes. We can add bytes to an 8819 // i8* by GEP with the byte count in the first index. 8820 C = ConstantExpr::getBitCast(C, DestPtrTy); 8821 } 8822 8823 // Don't bother trying to sum two pointers. We probably can't 8824 // statically compute a load that results from it anyway. 8825 if (C2->getType()->isPointerTy()) 8826 return nullptr; 8827 8828 if (C->getType()->isPointerTy()) { 8829 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 8830 C, C2); 8831 } else { 8832 C = ConstantExpr::getAdd(C, C2); 8833 } 8834 } 8835 return C; 8836 } 8837 return nullptr; 8838 } 8839 case scMulExpr: { 8840 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8841 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8842 // Don't bother with pointers at all. 8843 if (C->getType()->isPointerTy()) 8844 return nullptr; 8845 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8846 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8847 if (!C2 || C2->getType()->isPointerTy()) 8848 return nullptr; 8849 C = ConstantExpr::getMul(C, C2); 8850 } 8851 return C; 8852 } 8853 return nullptr; 8854 } 8855 case scUDivExpr: { 8856 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8857 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8858 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8859 if (LHS->getType() == RHS->getType()) 8860 return ConstantExpr::getUDiv(LHS, RHS); 8861 return nullptr; 8862 } 8863 case scSMaxExpr: 8864 case scUMaxExpr: 8865 case scSMinExpr: 8866 case scUMinExpr: 8867 return nullptr; // TODO: smax, umax, smin, umax. 8868 } 8869 llvm_unreachable("Unknown SCEV kind!"); 8870 } 8871 8872 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8873 if (isa<SCEVConstant>(V)) return V; 8874 8875 // If this instruction is evolved from a constant-evolving PHI, compute the 8876 // exit value from the loop without using SCEVs. 8877 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8878 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8879 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8880 const Loop *CurrLoop = this->LI[I->getParent()]; 8881 // Looking for loop exit value. 8882 if (CurrLoop && CurrLoop->getParentLoop() == L && 8883 PN->getParent() == CurrLoop->getHeader()) { 8884 // Okay, there is no closed form solution for the PHI node. Check 8885 // to see if the loop that contains it has a known backedge-taken 8886 // count. If so, we may be able to force computation of the exit 8887 // value. 8888 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8889 // This trivial case can show up in some degenerate cases where 8890 // the incoming IR has not yet been fully simplified. 8891 if (BackedgeTakenCount->isZero()) { 8892 Value *InitValue = nullptr; 8893 bool MultipleInitValues = false; 8894 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8895 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8896 if (!InitValue) 8897 InitValue = PN->getIncomingValue(i); 8898 else if (InitValue != PN->getIncomingValue(i)) { 8899 MultipleInitValues = true; 8900 break; 8901 } 8902 } 8903 } 8904 if (!MultipleInitValues && InitValue) 8905 return getSCEV(InitValue); 8906 } 8907 // Do we have a loop invariant value flowing around the backedge 8908 // for a loop which must execute the backedge? 8909 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8910 isKnownPositive(BackedgeTakenCount) && 8911 PN->getNumIncomingValues() == 2) { 8912 8913 unsigned InLoopPred = 8914 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8915 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8916 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8917 return getSCEV(BackedgeVal); 8918 } 8919 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8920 // Okay, we know how many times the containing loop executes. If 8921 // this is a constant evolving PHI node, get the final value at 8922 // the specified iteration number. 8923 Constant *RV = getConstantEvolutionLoopExitValue( 8924 PN, BTCC->getAPInt(), CurrLoop); 8925 if (RV) return getSCEV(RV); 8926 } 8927 } 8928 8929 // If there is a single-input Phi, evaluate it at our scope. If we can 8930 // prove that this replacement does not break LCSSA form, use new value. 8931 if (PN->getNumOperands() == 1) { 8932 const SCEV *Input = getSCEV(PN->getOperand(0)); 8933 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8934 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8935 // for the simplest case just support constants. 8936 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8937 } 8938 } 8939 8940 // Okay, this is an expression that we cannot symbolically evaluate 8941 // into a SCEV. Check to see if it's possible to symbolically evaluate 8942 // the arguments into constants, and if so, try to constant propagate the 8943 // result. This is particularly useful for computing loop exit values. 8944 if (CanConstantFold(I)) { 8945 SmallVector<Constant *, 4> Operands; 8946 bool MadeImprovement = false; 8947 for (Value *Op : I->operands()) { 8948 if (Constant *C = dyn_cast<Constant>(Op)) { 8949 Operands.push_back(C); 8950 continue; 8951 } 8952 8953 // If any of the operands is non-constant and if they are 8954 // non-integer and non-pointer, don't even try to analyze them 8955 // with scev techniques. 8956 if (!isSCEVable(Op->getType())) 8957 return V; 8958 8959 const SCEV *OrigV = getSCEV(Op); 8960 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8961 MadeImprovement |= OrigV != OpV; 8962 8963 Constant *C = BuildConstantFromSCEV(OpV); 8964 if (!C) return V; 8965 if (C->getType() != Op->getType()) 8966 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8967 Op->getType(), 8968 false), 8969 C, Op->getType()); 8970 Operands.push_back(C); 8971 } 8972 8973 // Check to see if getSCEVAtScope actually made an improvement. 8974 if (MadeImprovement) { 8975 Constant *C = nullptr; 8976 const DataLayout &DL = getDataLayout(); 8977 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8978 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8979 Operands[1], DL, &TLI); 8980 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8981 if (!Load->isVolatile()) 8982 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8983 DL); 8984 } else 8985 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8986 if (!C) return V; 8987 return getSCEV(C); 8988 } 8989 } 8990 } 8991 8992 // This is some other type of SCEVUnknown, just return it. 8993 return V; 8994 } 8995 8996 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8997 // Avoid performing the look-up in the common case where the specified 8998 // expression has no loop-variant portions. 8999 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9000 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9001 if (OpAtScope != Comm->getOperand(i)) { 9002 // Okay, at least one of these operands is loop variant but might be 9003 // foldable. Build a new instance of the folded commutative expression. 9004 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9005 Comm->op_begin()+i); 9006 NewOps.push_back(OpAtScope); 9007 9008 for (++i; i != e; ++i) { 9009 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9010 NewOps.push_back(OpAtScope); 9011 } 9012 if (isa<SCEVAddExpr>(Comm)) 9013 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9014 if (isa<SCEVMulExpr>(Comm)) 9015 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9016 if (isa<SCEVMinMaxExpr>(Comm)) 9017 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9018 llvm_unreachable("Unknown commutative SCEV type!"); 9019 } 9020 } 9021 // If we got here, all operands are loop invariant. 9022 return Comm; 9023 } 9024 9025 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9026 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9027 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9028 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9029 return Div; // must be loop invariant 9030 return getUDivExpr(LHS, RHS); 9031 } 9032 9033 // If this is a loop recurrence for a loop that does not contain L, then we 9034 // are dealing with the final value computed by the loop. 9035 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9036 // First, attempt to evaluate each operand. 9037 // Avoid performing the look-up in the common case where the specified 9038 // expression has no loop-variant portions. 9039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9040 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9041 if (OpAtScope == AddRec->getOperand(i)) 9042 continue; 9043 9044 // Okay, at least one of these operands is loop variant but might be 9045 // foldable. Build a new instance of the folded commutative expression. 9046 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9047 AddRec->op_begin()+i); 9048 NewOps.push_back(OpAtScope); 9049 for (++i; i != e; ++i) 9050 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9051 9052 const SCEV *FoldedRec = 9053 getAddRecExpr(NewOps, AddRec->getLoop(), 9054 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9055 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9056 // The addrec may be folded to a nonrecurrence, for example, if the 9057 // induction variable is multiplied by zero after constant folding. Go 9058 // ahead and return the folded value. 9059 if (!AddRec) 9060 return FoldedRec; 9061 break; 9062 } 9063 9064 // If the scope is outside the addrec's loop, evaluate it by using the 9065 // loop exit value of the addrec. 9066 if (!AddRec->getLoop()->contains(L)) { 9067 // To evaluate this recurrence, we need to know how many times the AddRec 9068 // loop iterates. Compute this now. 9069 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9070 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9071 9072 // Then, evaluate the AddRec. 9073 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9074 } 9075 9076 return AddRec; 9077 } 9078 9079 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 9080 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9081 if (Op == Cast->getOperand()) 9082 return Cast; // must be loop invariant 9083 return getZeroExtendExpr(Op, Cast->getType()); 9084 } 9085 9086 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 9087 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9088 if (Op == Cast->getOperand()) 9089 return Cast; // must be loop invariant 9090 return getSignExtendExpr(Op, Cast->getType()); 9091 } 9092 9093 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 9094 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9095 if (Op == Cast->getOperand()) 9096 return Cast; // must be loop invariant 9097 return getTruncateExpr(Op, Cast->getType()); 9098 } 9099 9100 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 9101 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9102 if (Op == Cast->getOperand()) 9103 return Cast; // must be loop invariant 9104 return getPtrToIntExpr(Op, Cast->getType()); 9105 } 9106 9107 llvm_unreachable("Unknown SCEV type!"); 9108 } 9109 9110 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9111 return getSCEVAtScope(getSCEV(V), L); 9112 } 9113 9114 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9115 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9116 return stripInjectiveFunctions(ZExt->getOperand()); 9117 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9118 return stripInjectiveFunctions(SExt->getOperand()); 9119 return S; 9120 } 9121 9122 /// Finds the minimum unsigned root of the following equation: 9123 /// 9124 /// A * X = B (mod N) 9125 /// 9126 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9127 /// A and B isn't important. 9128 /// 9129 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9130 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9131 ScalarEvolution &SE) { 9132 uint32_t BW = A.getBitWidth(); 9133 assert(BW == SE.getTypeSizeInBits(B->getType())); 9134 assert(A != 0 && "A must be non-zero."); 9135 9136 // 1. D = gcd(A, N) 9137 // 9138 // The gcd of A and N may have only one prime factor: 2. The number of 9139 // trailing zeros in A is its multiplicity 9140 uint32_t Mult2 = A.countTrailingZeros(); 9141 // D = 2^Mult2 9142 9143 // 2. Check if B is divisible by D. 9144 // 9145 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9146 // is not less than multiplicity of this prime factor for D. 9147 if (SE.GetMinTrailingZeros(B) < Mult2) 9148 return SE.getCouldNotCompute(); 9149 9150 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9151 // modulo (N / D). 9152 // 9153 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9154 // (N / D) in general. The inverse itself always fits into BW bits, though, 9155 // so we immediately truncate it. 9156 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9157 APInt Mod(BW + 1, 0); 9158 Mod.setBit(BW - Mult2); // Mod = N / D 9159 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9160 9161 // 4. Compute the minimum unsigned root of the equation: 9162 // I * (B / D) mod (N / D) 9163 // To simplify the computation, we factor out the divide by D: 9164 // (I * B mod N) / D 9165 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9166 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9167 } 9168 9169 /// For a given quadratic addrec, generate coefficients of the corresponding 9170 /// quadratic equation, multiplied by a common value to ensure that they are 9171 /// integers. 9172 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9173 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9174 /// were multiplied by, and BitWidth is the bit width of the original addrec 9175 /// coefficients. 9176 /// This function returns None if the addrec coefficients are not compile- 9177 /// time constants. 9178 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9179 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9180 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9181 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9182 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9183 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9184 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9185 << *AddRec << '\n'); 9186 9187 // We currently can only solve this if the coefficients are constants. 9188 if (!LC || !MC || !NC) { 9189 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9190 return None; 9191 } 9192 9193 APInt L = LC->getAPInt(); 9194 APInt M = MC->getAPInt(); 9195 APInt N = NC->getAPInt(); 9196 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9197 9198 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9199 unsigned NewWidth = BitWidth + 1; 9200 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9201 << BitWidth << '\n'); 9202 // The sign-extension (as opposed to a zero-extension) here matches the 9203 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9204 N = N.sext(NewWidth); 9205 M = M.sext(NewWidth); 9206 L = L.sext(NewWidth); 9207 9208 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9209 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9210 // L+M, L+2M+N, L+3M+3N, ... 9211 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9212 // 9213 // The equation Acc = 0 is then 9214 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9215 // In a quadratic form it becomes: 9216 // N n^2 + (2M-N) n + 2L = 0. 9217 9218 APInt A = N; 9219 APInt B = 2 * M - A; 9220 APInt C = 2 * L; 9221 APInt T = APInt(NewWidth, 2); 9222 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9223 << "x + " << C << ", coeff bw: " << NewWidth 9224 << ", multiplied by " << T << '\n'); 9225 return std::make_tuple(A, B, C, T, BitWidth); 9226 } 9227 9228 /// Helper function to compare optional APInts: 9229 /// (a) if X and Y both exist, return min(X, Y), 9230 /// (b) if neither X nor Y exist, return None, 9231 /// (c) if exactly one of X and Y exists, return that value. 9232 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9233 if (X.hasValue() && Y.hasValue()) { 9234 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9235 APInt XW = X->sextOrSelf(W); 9236 APInt YW = Y->sextOrSelf(W); 9237 return XW.slt(YW) ? *X : *Y; 9238 } 9239 if (!X.hasValue() && !Y.hasValue()) 9240 return None; 9241 return X.hasValue() ? *X : *Y; 9242 } 9243 9244 /// Helper function to truncate an optional APInt to a given BitWidth. 9245 /// When solving addrec-related equations, it is preferable to return a value 9246 /// that has the same bit width as the original addrec's coefficients. If the 9247 /// solution fits in the original bit width, truncate it (except for i1). 9248 /// Returning a value of a different bit width may inhibit some optimizations. 9249 /// 9250 /// In general, a solution to a quadratic equation generated from an addrec 9251 /// may require BW+1 bits, where BW is the bit width of the addrec's 9252 /// coefficients. The reason is that the coefficients of the quadratic 9253 /// equation are BW+1 bits wide (to avoid truncation when converting from 9254 /// the addrec to the equation). 9255 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9256 if (!X.hasValue()) 9257 return None; 9258 unsigned W = X->getBitWidth(); 9259 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9260 return X->trunc(BitWidth); 9261 return X; 9262 } 9263 9264 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9265 /// iterations. The values L, M, N are assumed to be signed, and they 9266 /// should all have the same bit widths. 9267 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9268 /// where BW is the bit width of the addrec's coefficients. 9269 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9270 /// returned as such, otherwise the bit width of the returned value may 9271 /// be greater than BW. 9272 /// 9273 /// This function returns None if 9274 /// (a) the addrec coefficients are not constant, or 9275 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9276 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9277 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9278 static Optional<APInt> 9279 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9280 APInt A, B, C, M; 9281 unsigned BitWidth; 9282 auto T = GetQuadraticEquation(AddRec); 9283 if (!T.hasValue()) 9284 return None; 9285 9286 std::tie(A, B, C, M, BitWidth) = *T; 9287 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9288 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9289 if (!X.hasValue()) 9290 return None; 9291 9292 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9293 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9294 if (!V->isZero()) 9295 return None; 9296 9297 return TruncIfPossible(X, BitWidth); 9298 } 9299 9300 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9301 /// iterations. The values M, N are assumed to be signed, and they 9302 /// should all have the same bit widths. 9303 /// Find the least n such that c(n) does not belong to the given range, 9304 /// while c(n-1) does. 9305 /// 9306 /// This function returns None if 9307 /// (a) the addrec coefficients are not constant, or 9308 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9309 /// bounds of the range. 9310 static Optional<APInt> 9311 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9312 const ConstantRange &Range, ScalarEvolution &SE) { 9313 assert(AddRec->getOperand(0)->isZero() && 9314 "Starting value of addrec should be 0"); 9315 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9316 << Range << ", addrec " << *AddRec << '\n'); 9317 // This case is handled in getNumIterationsInRange. Here we can assume that 9318 // we start in the range. 9319 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9320 "Addrec's initial value should be in range"); 9321 9322 APInt A, B, C, M; 9323 unsigned BitWidth; 9324 auto T = GetQuadraticEquation(AddRec); 9325 if (!T.hasValue()) 9326 return None; 9327 9328 // Be careful about the return value: there can be two reasons for not 9329 // returning an actual number. First, if no solutions to the equations 9330 // were found, and second, if the solutions don't leave the given range. 9331 // The first case means that the actual solution is "unknown", the second 9332 // means that it's known, but not valid. If the solution is unknown, we 9333 // cannot make any conclusions. 9334 // Return a pair: the optional solution and a flag indicating if the 9335 // solution was found. 9336 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9337 // Solve for signed overflow and unsigned overflow, pick the lower 9338 // solution. 9339 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9340 << Bound << " (before multiplying by " << M << ")\n"); 9341 Bound *= M; // The quadratic equation multiplier. 9342 9343 Optional<APInt> SO = None; 9344 if (BitWidth > 1) { 9345 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9346 "signed overflow\n"); 9347 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9348 } 9349 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9350 "unsigned overflow\n"); 9351 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9352 BitWidth+1); 9353 9354 auto LeavesRange = [&] (const APInt &X) { 9355 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9356 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9357 if (Range.contains(V0->getValue())) 9358 return false; 9359 // X should be at least 1, so X-1 is non-negative. 9360 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9361 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9362 if (Range.contains(V1->getValue())) 9363 return true; 9364 return false; 9365 }; 9366 9367 // If SolveQuadraticEquationWrap returns None, it means that there can 9368 // be a solution, but the function failed to find it. We cannot treat it 9369 // as "no solution". 9370 if (!SO.hasValue() || !UO.hasValue()) 9371 return { None, false }; 9372 9373 // Check the smaller value first to see if it leaves the range. 9374 // At this point, both SO and UO must have values. 9375 Optional<APInt> Min = MinOptional(SO, UO); 9376 if (LeavesRange(*Min)) 9377 return { Min, true }; 9378 Optional<APInt> Max = Min == SO ? UO : SO; 9379 if (LeavesRange(*Max)) 9380 return { Max, true }; 9381 9382 // Solutions were found, but were eliminated, hence the "true". 9383 return { None, true }; 9384 }; 9385 9386 std::tie(A, B, C, M, BitWidth) = *T; 9387 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9388 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9389 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9390 auto SL = SolveForBoundary(Lower); 9391 auto SU = SolveForBoundary(Upper); 9392 // If any of the solutions was unknown, no meaninigful conclusions can 9393 // be made. 9394 if (!SL.second || !SU.second) 9395 return None; 9396 9397 // Claim: The correct solution is not some value between Min and Max. 9398 // 9399 // Justification: Assuming that Min and Max are different values, one of 9400 // them is when the first signed overflow happens, the other is when the 9401 // first unsigned overflow happens. Crossing the range boundary is only 9402 // possible via an overflow (treating 0 as a special case of it, modeling 9403 // an overflow as crossing k*2^W for some k). 9404 // 9405 // The interesting case here is when Min was eliminated as an invalid 9406 // solution, but Max was not. The argument is that if there was another 9407 // overflow between Min and Max, it would also have been eliminated if 9408 // it was considered. 9409 // 9410 // For a given boundary, it is possible to have two overflows of the same 9411 // type (signed/unsigned) without having the other type in between: this 9412 // can happen when the vertex of the parabola is between the iterations 9413 // corresponding to the overflows. This is only possible when the two 9414 // overflows cross k*2^W for the same k. In such case, if the second one 9415 // left the range (and was the first one to do so), the first overflow 9416 // would have to enter the range, which would mean that either we had left 9417 // the range before or that we started outside of it. Both of these cases 9418 // are contradictions. 9419 // 9420 // Claim: In the case where SolveForBoundary returns None, the correct 9421 // solution is not some value between the Max for this boundary and the 9422 // Min of the other boundary. 9423 // 9424 // Justification: Assume that we had such Max_A and Min_B corresponding 9425 // to range boundaries A and B and such that Max_A < Min_B. If there was 9426 // a solution between Max_A and Min_B, it would have to be caused by an 9427 // overflow corresponding to either A or B. It cannot correspond to B, 9428 // since Min_B is the first occurrence of such an overflow. If it 9429 // corresponded to A, it would have to be either a signed or an unsigned 9430 // overflow that is larger than both eliminated overflows for A. But 9431 // between the eliminated overflows and this overflow, the values would 9432 // cover the entire value space, thus crossing the other boundary, which 9433 // is a contradiction. 9434 9435 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9436 } 9437 9438 ScalarEvolution::ExitLimit 9439 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9440 bool AllowPredicates) { 9441 9442 // This is only used for loops with a "x != y" exit test. The exit condition 9443 // is now expressed as a single expression, V = x-y. So the exit test is 9444 // effectively V != 0. We know and take advantage of the fact that this 9445 // expression only being used in a comparison by zero context. 9446 9447 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9448 // If the value is a constant 9449 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9450 // If the value is already zero, the branch will execute zero times. 9451 if (C->getValue()->isZero()) return C; 9452 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9453 } 9454 9455 const SCEVAddRecExpr *AddRec = 9456 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9457 9458 if (!AddRec && AllowPredicates) 9459 // Try to make this an AddRec using runtime tests, in the first X 9460 // iterations of this loop, where X is the SCEV expression found by the 9461 // algorithm below. 9462 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9463 9464 if (!AddRec || AddRec->getLoop() != L) 9465 return getCouldNotCompute(); 9466 9467 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9468 // the quadratic equation to solve it. 9469 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9470 // We can only use this value if the chrec ends up with an exact zero 9471 // value at this index. When solving for "X*X != 5", for example, we 9472 // should not accept a root of 2. 9473 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9474 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9475 return ExitLimit(R, R, false, Predicates); 9476 } 9477 return getCouldNotCompute(); 9478 } 9479 9480 // Otherwise we can only handle this if it is affine. 9481 if (!AddRec->isAffine()) 9482 return getCouldNotCompute(); 9483 9484 // If this is an affine expression, the execution count of this branch is 9485 // the minimum unsigned root of the following equation: 9486 // 9487 // Start + Step*N = 0 (mod 2^BW) 9488 // 9489 // equivalent to: 9490 // 9491 // Step*N = -Start (mod 2^BW) 9492 // 9493 // where BW is the common bit width of Start and Step. 9494 9495 // Get the initial value for the loop. 9496 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9497 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9498 9499 // For now we handle only constant steps. 9500 // 9501 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9502 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9503 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9504 // We have not yet seen any such cases. 9505 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9506 if (!StepC || StepC->getValue()->isZero()) 9507 return getCouldNotCompute(); 9508 9509 // For positive steps (counting up until unsigned overflow): 9510 // N = -Start/Step (as unsigned) 9511 // For negative steps (counting down to zero): 9512 // N = Start/-Step 9513 // First compute the unsigned distance from zero in the direction of Step. 9514 bool CountDown = StepC->getAPInt().isNegative(); 9515 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9516 9517 // Handle unitary steps, which cannot wraparound. 9518 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9519 // N = Distance (as unsigned) 9520 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9521 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9522 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9523 if (MaxBECountBase.ult(MaxBECount)) 9524 MaxBECount = MaxBECountBase; 9525 9526 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9527 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9528 // case, and see if we can improve the bound. 9529 // 9530 // Explicitly handling this here is necessary because getUnsignedRange 9531 // isn't context-sensitive; it doesn't know that we only care about the 9532 // range inside the loop. 9533 const SCEV *Zero = getZero(Distance->getType()); 9534 const SCEV *One = getOne(Distance->getType()); 9535 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9536 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9537 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9538 // as "unsigned_max(Distance + 1) - 1". 9539 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9540 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9541 } 9542 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9543 } 9544 9545 // If the condition controls loop exit (the loop exits only if the expression 9546 // is true) and the addition is no-wrap we can use unsigned divide to 9547 // compute the backedge count. In this case, the step may not divide the 9548 // distance, but we don't care because if the condition is "missed" the loop 9549 // will have undefined behavior due to wrapping. 9550 if (ControlsExit && AddRec->hasNoSelfWrap() && 9551 loopHasNoAbnormalExits(AddRec->getLoop())) { 9552 const SCEV *Exact = 9553 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9554 const SCEV *Max = getCouldNotCompute(); 9555 if (Exact != getCouldNotCompute()) { 9556 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9557 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9558 if (BaseMaxInt.ult(MaxInt)) 9559 Max = getConstant(BaseMaxInt); 9560 else 9561 Max = getConstant(MaxInt); 9562 } 9563 return ExitLimit(Exact, Max, false, Predicates); 9564 } 9565 9566 // Solve the general equation. 9567 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9568 getNegativeSCEV(Start), *this); 9569 const SCEV *M = E == getCouldNotCompute() 9570 ? E 9571 : getConstant(getUnsignedRangeMax(E)); 9572 return ExitLimit(E, M, false, Predicates); 9573 } 9574 9575 ScalarEvolution::ExitLimit 9576 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9577 // Loops that look like: while (X == 0) are very strange indeed. We don't 9578 // handle them yet except for the trivial case. This could be expanded in the 9579 // future as needed. 9580 9581 // If the value is a constant, check to see if it is known to be non-zero 9582 // already. If so, the backedge will execute zero times. 9583 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9584 if (!C->getValue()->isZero()) 9585 return getZero(C->getType()); 9586 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9587 } 9588 9589 // We could implement others, but I really doubt anyone writes loops like 9590 // this, and if they did, they would already be constant folded. 9591 return getCouldNotCompute(); 9592 } 9593 9594 std::pair<const BasicBlock *, const BasicBlock *> 9595 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9596 const { 9597 // If the block has a unique predecessor, then there is no path from the 9598 // predecessor to the block that does not go through the direct edge 9599 // from the predecessor to the block. 9600 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9601 return {Pred, BB}; 9602 9603 // A loop's header is defined to be a block that dominates the loop. 9604 // If the header has a unique predecessor outside the loop, it must be 9605 // a block that has exactly one successor that can reach the loop. 9606 if (const Loop *L = LI.getLoopFor(BB)) 9607 return {L->getLoopPredecessor(), L->getHeader()}; 9608 9609 return {nullptr, nullptr}; 9610 } 9611 9612 /// SCEV structural equivalence is usually sufficient for testing whether two 9613 /// expressions are equal, however for the purposes of looking for a condition 9614 /// guarding a loop, it can be useful to be a little more general, since a 9615 /// front-end may have replicated the controlling expression. 9616 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9617 // Quick check to see if they are the same SCEV. 9618 if (A == B) return true; 9619 9620 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9621 // Not all instructions that are "identical" compute the same value. For 9622 // instance, two distinct alloca instructions allocating the same type are 9623 // identical and do not read memory; but compute distinct values. 9624 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9625 }; 9626 9627 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9628 // two different instructions with the same value. Check for this case. 9629 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9630 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9631 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9632 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9633 if (ComputesEqualValues(AI, BI)) 9634 return true; 9635 9636 // Otherwise assume they may have a different value. 9637 return false; 9638 } 9639 9640 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9641 const SCEV *&LHS, const SCEV *&RHS, 9642 unsigned Depth) { 9643 bool Changed = false; 9644 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9645 // '0 != 0'. 9646 auto TrivialCase = [&](bool TriviallyTrue) { 9647 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9648 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9649 return true; 9650 }; 9651 // If we hit the max recursion limit bail out. 9652 if (Depth >= 3) 9653 return false; 9654 9655 // Canonicalize a constant to the right side. 9656 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9657 // Check for both operands constant. 9658 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9659 if (ConstantExpr::getICmp(Pred, 9660 LHSC->getValue(), 9661 RHSC->getValue())->isNullValue()) 9662 return TrivialCase(false); 9663 else 9664 return TrivialCase(true); 9665 } 9666 // Otherwise swap the operands to put the constant on the right. 9667 std::swap(LHS, RHS); 9668 Pred = ICmpInst::getSwappedPredicate(Pred); 9669 Changed = true; 9670 } 9671 9672 // If we're comparing an addrec with a value which is loop-invariant in the 9673 // addrec's loop, put the addrec on the left. Also make a dominance check, 9674 // as both operands could be addrecs loop-invariant in each other's loop. 9675 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9676 const Loop *L = AR->getLoop(); 9677 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9678 std::swap(LHS, RHS); 9679 Pred = ICmpInst::getSwappedPredicate(Pred); 9680 Changed = true; 9681 } 9682 } 9683 9684 // If there's a constant operand, canonicalize comparisons with boundary 9685 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9686 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9687 const APInt &RA = RC->getAPInt(); 9688 9689 bool SimplifiedByConstantRange = false; 9690 9691 if (!ICmpInst::isEquality(Pred)) { 9692 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9693 if (ExactCR.isFullSet()) 9694 return TrivialCase(true); 9695 else if (ExactCR.isEmptySet()) 9696 return TrivialCase(false); 9697 9698 APInt NewRHS; 9699 CmpInst::Predicate NewPred; 9700 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9701 ICmpInst::isEquality(NewPred)) { 9702 // We were able to convert an inequality to an equality. 9703 Pred = NewPred; 9704 RHS = getConstant(NewRHS); 9705 Changed = SimplifiedByConstantRange = true; 9706 } 9707 } 9708 9709 if (!SimplifiedByConstantRange) { 9710 switch (Pred) { 9711 default: 9712 break; 9713 case ICmpInst::ICMP_EQ: 9714 case ICmpInst::ICMP_NE: 9715 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9716 if (!RA) 9717 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9718 if (const SCEVMulExpr *ME = 9719 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9720 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9721 ME->getOperand(0)->isAllOnesValue()) { 9722 RHS = AE->getOperand(1); 9723 LHS = ME->getOperand(1); 9724 Changed = true; 9725 } 9726 break; 9727 9728 9729 // The "Should have been caught earlier!" messages refer to the fact 9730 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9731 // should have fired on the corresponding cases, and canonicalized the 9732 // check to trivial case. 9733 9734 case ICmpInst::ICMP_UGE: 9735 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9736 Pred = ICmpInst::ICMP_UGT; 9737 RHS = getConstant(RA - 1); 9738 Changed = true; 9739 break; 9740 case ICmpInst::ICMP_ULE: 9741 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9742 Pred = ICmpInst::ICMP_ULT; 9743 RHS = getConstant(RA + 1); 9744 Changed = true; 9745 break; 9746 case ICmpInst::ICMP_SGE: 9747 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9748 Pred = ICmpInst::ICMP_SGT; 9749 RHS = getConstant(RA - 1); 9750 Changed = true; 9751 break; 9752 case ICmpInst::ICMP_SLE: 9753 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9754 Pred = ICmpInst::ICMP_SLT; 9755 RHS = getConstant(RA + 1); 9756 Changed = true; 9757 break; 9758 } 9759 } 9760 } 9761 9762 // Check for obvious equality. 9763 if (HasSameValue(LHS, RHS)) { 9764 if (ICmpInst::isTrueWhenEqual(Pred)) 9765 return TrivialCase(true); 9766 if (ICmpInst::isFalseWhenEqual(Pred)) 9767 return TrivialCase(false); 9768 } 9769 9770 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9771 // adding or subtracting 1 from one of the operands. 9772 switch (Pred) { 9773 case ICmpInst::ICMP_SLE: 9774 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9775 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9776 SCEV::FlagNSW); 9777 Pred = ICmpInst::ICMP_SLT; 9778 Changed = true; 9779 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9780 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9781 SCEV::FlagNSW); 9782 Pred = ICmpInst::ICMP_SLT; 9783 Changed = true; 9784 } 9785 break; 9786 case ICmpInst::ICMP_SGE: 9787 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9788 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9789 SCEV::FlagNSW); 9790 Pred = ICmpInst::ICMP_SGT; 9791 Changed = true; 9792 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9793 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9794 SCEV::FlagNSW); 9795 Pred = ICmpInst::ICMP_SGT; 9796 Changed = true; 9797 } 9798 break; 9799 case ICmpInst::ICMP_ULE: 9800 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9801 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9802 SCEV::FlagNUW); 9803 Pred = ICmpInst::ICMP_ULT; 9804 Changed = true; 9805 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9806 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9807 Pred = ICmpInst::ICMP_ULT; 9808 Changed = true; 9809 } 9810 break; 9811 case ICmpInst::ICMP_UGE: 9812 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9813 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9814 Pred = ICmpInst::ICMP_UGT; 9815 Changed = true; 9816 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9817 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9818 SCEV::FlagNUW); 9819 Pred = ICmpInst::ICMP_UGT; 9820 Changed = true; 9821 } 9822 break; 9823 default: 9824 break; 9825 } 9826 9827 // TODO: More simplifications are possible here. 9828 9829 // Recursively simplify until we either hit a recursion limit or nothing 9830 // changes. 9831 if (Changed) 9832 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9833 9834 return Changed; 9835 } 9836 9837 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9838 return getSignedRangeMax(S).isNegative(); 9839 } 9840 9841 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9842 return getSignedRangeMin(S).isStrictlyPositive(); 9843 } 9844 9845 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9846 return !getSignedRangeMin(S).isNegative(); 9847 } 9848 9849 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9850 return !getSignedRangeMax(S).isStrictlyPositive(); 9851 } 9852 9853 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9854 return getUnsignedRangeMin(S) != 0; 9855 } 9856 9857 std::pair<const SCEV *, const SCEV *> 9858 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9859 // Compute SCEV on entry of loop L. 9860 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9861 if (Start == getCouldNotCompute()) 9862 return { Start, Start }; 9863 // Compute post increment SCEV for loop L. 9864 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9865 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9866 return { Start, PostInc }; 9867 } 9868 9869 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9870 const SCEV *LHS, const SCEV *RHS) { 9871 // First collect all loops. 9872 SmallPtrSet<const Loop *, 8> LoopsUsed; 9873 getUsedLoops(LHS, LoopsUsed); 9874 getUsedLoops(RHS, LoopsUsed); 9875 9876 if (LoopsUsed.empty()) 9877 return false; 9878 9879 // Domination relationship must be a linear order on collected loops. 9880 #ifndef NDEBUG 9881 for (auto *L1 : LoopsUsed) 9882 for (auto *L2 : LoopsUsed) 9883 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9884 DT.dominates(L2->getHeader(), L1->getHeader())) && 9885 "Domination relationship is not a linear order"); 9886 #endif 9887 9888 const Loop *MDL = 9889 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9890 [&](const Loop *L1, const Loop *L2) { 9891 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9892 }); 9893 9894 // Get init and post increment value for LHS. 9895 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9896 // if LHS contains unknown non-invariant SCEV then bail out. 9897 if (SplitLHS.first == getCouldNotCompute()) 9898 return false; 9899 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9900 // Get init and post increment value for RHS. 9901 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9902 // if RHS contains unknown non-invariant SCEV then bail out. 9903 if (SplitRHS.first == getCouldNotCompute()) 9904 return false; 9905 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9906 // It is possible that init SCEV contains an invariant load but it does 9907 // not dominate MDL and is not available at MDL loop entry, so we should 9908 // check it here. 9909 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9910 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9911 return false; 9912 9913 // It seems backedge guard check is faster than entry one so in some cases 9914 // it can speed up whole estimation by short circuit 9915 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9916 SplitRHS.second) && 9917 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9918 } 9919 9920 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9921 const SCEV *LHS, const SCEV *RHS) { 9922 // Canonicalize the inputs first. 9923 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9924 9925 if (isKnownViaInduction(Pred, LHS, RHS)) 9926 return true; 9927 9928 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9929 return true; 9930 9931 // Otherwise see what can be done with some simple reasoning. 9932 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9933 } 9934 9935 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9936 const SCEV *LHS, 9937 const SCEV *RHS) { 9938 if (isKnownPredicate(Pred, LHS, RHS)) 9939 return true; 9940 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9941 return false; 9942 return None; 9943 } 9944 9945 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9946 const SCEV *LHS, const SCEV *RHS, 9947 const Instruction *CtxI) { 9948 // TODO: Analyze guards and assumes from Context's block. 9949 return isKnownPredicate(Pred, LHS, RHS) || 9950 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 9951 } 9952 9953 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 9954 const SCEV *LHS, 9955 const SCEV *RHS, 9956 const Instruction *CtxI) { 9957 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9958 if (KnownWithoutContext) 9959 return KnownWithoutContext; 9960 9961 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 9962 return true; 9963 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 9964 ICmpInst::getInversePredicate(Pred), 9965 LHS, RHS)) 9966 return false; 9967 return None; 9968 } 9969 9970 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9971 const SCEVAddRecExpr *LHS, 9972 const SCEV *RHS) { 9973 const Loop *L = LHS->getLoop(); 9974 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9975 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9976 } 9977 9978 Optional<ScalarEvolution::MonotonicPredicateType> 9979 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9980 ICmpInst::Predicate Pred) { 9981 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9982 9983 #ifndef NDEBUG 9984 // Verify an invariant: inverting the predicate should turn a monotonically 9985 // increasing change to a monotonically decreasing one, and vice versa. 9986 if (Result) { 9987 auto ResultSwapped = 9988 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9989 9990 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9991 assert(ResultSwapped.getValue() != Result.getValue() && 9992 "monotonicity should flip as we flip the predicate"); 9993 } 9994 #endif 9995 9996 return Result; 9997 } 9998 9999 Optional<ScalarEvolution::MonotonicPredicateType> 10000 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10001 ICmpInst::Predicate Pred) { 10002 // A zero step value for LHS means the induction variable is essentially a 10003 // loop invariant value. We don't really depend on the predicate actually 10004 // flipping from false to true (for increasing predicates, and the other way 10005 // around for decreasing predicates), all we care about is that *if* the 10006 // predicate changes then it only changes from false to true. 10007 // 10008 // A zero step value in itself is not very useful, but there may be places 10009 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10010 // as general as possible. 10011 10012 // Only handle LE/LT/GE/GT predicates. 10013 if (!ICmpInst::isRelational(Pred)) 10014 return None; 10015 10016 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10017 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10018 "Should be greater or less!"); 10019 10020 // Check that AR does not wrap. 10021 if (ICmpInst::isUnsigned(Pred)) { 10022 if (!LHS->hasNoUnsignedWrap()) 10023 return None; 10024 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10025 } else { 10026 assert(ICmpInst::isSigned(Pred) && 10027 "Relational predicate is either signed or unsigned!"); 10028 if (!LHS->hasNoSignedWrap()) 10029 return None; 10030 10031 const SCEV *Step = LHS->getStepRecurrence(*this); 10032 10033 if (isKnownNonNegative(Step)) 10034 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10035 10036 if (isKnownNonPositive(Step)) 10037 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10038 10039 return None; 10040 } 10041 } 10042 10043 Optional<ScalarEvolution::LoopInvariantPredicate> 10044 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10045 const SCEV *LHS, const SCEV *RHS, 10046 const Loop *L) { 10047 10048 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10049 if (!isLoopInvariant(RHS, L)) { 10050 if (!isLoopInvariant(LHS, L)) 10051 return None; 10052 10053 std::swap(LHS, RHS); 10054 Pred = ICmpInst::getSwappedPredicate(Pred); 10055 } 10056 10057 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10058 if (!ArLHS || ArLHS->getLoop() != L) 10059 return None; 10060 10061 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10062 if (!MonotonicType) 10063 return None; 10064 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10065 // true as the loop iterates, and the backedge is control dependent on 10066 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10067 // 10068 // * if the predicate was false in the first iteration then the predicate 10069 // is never evaluated again, since the loop exits without taking the 10070 // backedge. 10071 // * if the predicate was true in the first iteration then it will 10072 // continue to be true for all future iterations since it is 10073 // monotonically increasing. 10074 // 10075 // For both the above possibilities, we can replace the loop varying 10076 // predicate with its value on the first iteration of the loop (which is 10077 // loop invariant). 10078 // 10079 // A similar reasoning applies for a monotonically decreasing predicate, by 10080 // replacing true with false and false with true in the above two bullets. 10081 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10082 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10083 10084 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10085 return None; 10086 10087 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10088 } 10089 10090 Optional<ScalarEvolution::LoopInvariantPredicate> 10091 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10092 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10093 const Instruction *CtxI, const SCEV *MaxIter) { 10094 // Try to prove the following set of facts: 10095 // - The predicate is monotonic in the iteration space. 10096 // - If the check does not fail on the 1st iteration: 10097 // - No overflow will happen during first MaxIter iterations; 10098 // - It will not fail on the MaxIter'th iteration. 10099 // If the check does fail on the 1st iteration, we leave the loop and no 10100 // other checks matter. 10101 10102 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10103 if (!isLoopInvariant(RHS, L)) { 10104 if (!isLoopInvariant(LHS, L)) 10105 return None; 10106 10107 std::swap(LHS, RHS); 10108 Pred = ICmpInst::getSwappedPredicate(Pred); 10109 } 10110 10111 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10112 if (!AR || AR->getLoop() != L) 10113 return None; 10114 10115 // The predicate must be relational (i.e. <, <=, >=, >). 10116 if (!ICmpInst::isRelational(Pred)) 10117 return None; 10118 10119 // TODO: Support steps other than +/- 1. 10120 const SCEV *Step = AR->getStepRecurrence(*this); 10121 auto *One = getOne(Step->getType()); 10122 auto *MinusOne = getNegativeSCEV(One); 10123 if (Step != One && Step != MinusOne) 10124 return None; 10125 10126 // Type mismatch here means that MaxIter is potentially larger than max 10127 // unsigned value in start type, which mean we cannot prove no wrap for the 10128 // indvar. 10129 if (AR->getType() != MaxIter->getType()) 10130 return None; 10131 10132 // Value of IV on suggested last iteration. 10133 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10134 // Does it still meet the requirement? 10135 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10136 return None; 10137 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10138 // not exceed max unsigned value of this type), this effectively proves 10139 // that there is no wrap during the iteration. To prove that there is no 10140 // signed/unsigned wrap, we need to check that 10141 // Start <= Last for step = 1 or Start >= Last for step = -1. 10142 ICmpInst::Predicate NoOverflowPred = 10143 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10144 if (Step == MinusOne) 10145 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10146 const SCEV *Start = AR->getStart(); 10147 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10148 return None; 10149 10150 // Everything is fine. 10151 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10152 } 10153 10154 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10155 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10156 if (HasSameValue(LHS, RHS)) 10157 return ICmpInst::isTrueWhenEqual(Pred); 10158 10159 // This code is split out from isKnownPredicate because it is called from 10160 // within isLoopEntryGuardedByCond. 10161 10162 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10163 const ConstantRange &RangeRHS) { 10164 return RangeLHS.icmp(Pred, RangeRHS); 10165 }; 10166 10167 // The check at the top of the function catches the case where the values are 10168 // known to be equal. 10169 if (Pred == CmpInst::ICMP_EQ) 10170 return false; 10171 10172 if (Pred == CmpInst::ICMP_NE) { 10173 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10174 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10175 return true; 10176 auto *Diff = getMinusSCEV(LHS, RHS); 10177 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10178 } 10179 10180 if (CmpInst::isSigned(Pred)) 10181 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10182 10183 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10184 } 10185 10186 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10187 const SCEV *LHS, 10188 const SCEV *RHS) { 10189 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10190 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10191 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10192 // OutC1 and OutC2. 10193 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10194 APInt &OutC1, APInt &OutC2, 10195 SCEV::NoWrapFlags ExpectedFlags) { 10196 const SCEV *XNonConstOp, *XConstOp; 10197 const SCEV *YNonConstOp, *YConstOp; 10198 SCEV::NoWrapFlags XFlagsPresent; 10199 SCEV::NoWrapFlags YFlagsPresent; 10200 10201 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10202 XConstOp = getZero(X->getType()); 10203 XNonConstOp = X; 10204 XFlagsPresent = ExpectedFlags; 10205 } 10206 if (!isa<SCEVConstant>(XConstOp) || 10207 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10208 return false; 10209 10210 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10211 YConstOp = getZero(Y->getType()); 10212 YNonConstOp = Y; 10213 YFlagsPresent = ExpectedFlags; 10214 } 10215 10216 if (!isa<SCEVConstant>(YConstOp) || 10217 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10218 return false; 10219 10220 if (YNonConstOp != XNonConstOp) 10221 return false; 10222 10223 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10224 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10225 10226 return true; 10227 }; 10228 10229 APInt C1; 10230 APInt C2; 10231 10232 switch (Pred) { 10233 default: 10234 break; 10235 10236 case ICmpInst::ICMP_SGE: 10237 std::swap(LHS, RHS); 10238 LLVM_FALLTHROUGH; 10239 case ICmpInst::ICMP_SLE: 10240 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10241 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10242 return true; 10243 10244 break; 10245 10246 case ICmpInst::ICMP_SGT: 10247 std::swap(LHS, RHS); 10248 LLVM_FALLTHROUGH; 10249 case ICmpInst::ICMP_SLT: 10250 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10251 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10252 return true; 10253 10254 break; 10255 10256 case ICmpInst::ICMP_UGE: 10257 std::swap(LHS, RHS); 10258 LLVM_FALLTHROUGH; 10259 case ICmpInst::ICMP_ULE: 10260 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10261 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10262 return true; 10263 10264 break; 10265 10266 case ICmpInst::ICMP_UGT: 10267 std::swap(LHS, RHS); 10268 LLVM_FALLTHROUGH; 10269 case ICmpInst::ICMP_ULT: 10270 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10271 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10272 return true; 10273 break; 10274 } 10275 10276 return false; 10277 } 10278 10279 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10280 const SCEV *LHS, 10281 const SCEV *RHS) { 10282 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10283 return false; 10284 10285 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10286 // the stack can result in exponential time complexity. 10287 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10288 10289 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10290 // 10291 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10292 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10293 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10294 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10295 // use isKnownPredicate later if needed. 10296 return isKnownNonNegative(RHS) && 10297 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10298 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10299 } 10300 10301 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10302 ICmpInst::Predicate Pred, 10303 const SCEV *LHS, const SCEV *RHS) { 10304 // No need to even try if we know the module has no guards. 10305 if (!HasGuards) 10306 return false; 10307 10308 return any_of(*BB, [&](const Instruction &I) { 10309 using namespace llvm::PatternMatch; 10310 10311 Value *Condition; 10312 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10313 m_Value(Condition))) && 10314 isImpliedCond(Pred, LHS, RHS, Condition, false); 10315 }); 10316 } 10317 10318 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10319 /// protected by a conditional between LHS and RHS. This is used to 10320 /// to eliminate casts. 10321 bool 10322 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10323 ICmpInst::Predicate Pred, 10324 const SCEV *LHS, const SCEV *RHS) { 10325 // Interpret a null as meaning no loop, where there is obviously no guard 10326 // (interprocedural conditions notwithstanding). 10327 if (!L) return true; 10328 10329 if (VerifyIR) 10330 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10331 "This cannot be done on broken IR!"); 10332 10333 10334 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10335 return true; 10336 10337 BasicBlock *Latch = L->getLoopLatch(); 10338 if (!Latch) 10339 return false; 10340 10341 BranchInst *LoopContinuePredicate = 10342 dyn_cast<BranchInst>(Latch->getTerminator()); 10343 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10344 isImpliedCond(Pred, LHS, RHS, 10345 LoopContinuePredicate->getCondition(), 10346 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10347 return true; 10348 10349 // We don't want more than one activation of the following loops on the stack 10350 // -- that can lead to O(n!) time complexity. 10351 if (WalkingBEDominatingConds) 10352 return false; 10353 10354 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10355 10356 // See if we can exploit a trip count to prove the predicate. 10357 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10358 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10359 if (LatchBECount != getCouldNotCompute()) { 10360 // We know that Latch branches back to the loop header exactly 10361 // LatchBECount times. This means the backdege condition at Latch is 10362 // equivalent to "{0,+,1} u< LatchBECount". 10363 Type *Ty = LatchBECount->getType(); 10364 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10365 const SCEV *LoopCounter = 10366 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10367 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10368 LatchBECount)) 10369 return true; 10370 } 10371 10372 // Check conditions due to any @llvm.assume intrinsics. 10373 for (auto &AssumeVH : AC.assumptions()) { 10374 if (!AssumeVH) 10375 continue; 10376 auto *CI = cast<CallInst>(AssumeVH); 10377 if (!DT.dominates(CI, Latch->getTerminator())) 10378 continue; 10379 10380 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10381 return true; 10382 } 10383 10384 // If the loop is not reachable from the entry block, we risk running into an 10385 // infinite loop as we walk up into the dom tree. These loops do not matter 10386 // anyway, so we just return a conservative answer when we see them. 10387 if (!DT.isReachableFromEntry(L->getHeader())) 10388 return false; 10389 10390 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10391 return true; 10392 10393 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10394 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10395 assert(DTN && "should reach the loop header before reaching the root!"); 10396 10397 BasicBlock *BB = DTN->getBlock(); 10398 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10399 return true; 10400 10401 BasicBlock *PBB = BB->getSinglePredecessor(); 10402 if (!PBB) 10403 continue; 10404 10405 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10406 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10407 continue; 10408 10409 Value *Condition = ContinuePredicate->getCondition(); 10410 10411 // If we have an edge `E` within the loop body that dominates the only 10412 // latch, the condition guarding `E` also guards the backedge. This 10413 // reasoning works only for loops with a single latch. 10414 10415 BasicBlockEdge DominatingEdge(PBB, BB); 10416 if (DominatingEdge.isSingleEdge()) { 10417 // We're constructively (and conservatively) enumerating edges within the 10418 // loop body that dominate the latch. The dominator tree better agree 10419 // with us on this: 10420 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10421 10422 if (isImpliedCond(Pred, LHS, RHS, Condition, 10423 BB != ContinuePredicate->getSuccessor(0))) 10424 return true; 10425 } 10426 } 10427 10428 return false; 10429 } 10430 10431 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10432 ICmpInst::Predicate Pred, 10433 const SCEV *LHS, 10434 const SCEV *RHS) { 10435 if (VerifyIR) 10436 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10437 "This cannot be done on broken IR!"); 10438 10439 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10440 // the facts (a >= b && a != b) separately. A typical situation is when the 10441 // non-strict comparison is known from ranges and non-equality is known from 10442 // dominating predicates. If we are proving strict comparison, we always try 10443 // to prove non-equality and non-strict comparison separately. 10444 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10445 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10446 bool ProvedNonStrictComparison = false; 10447 bool ProvedNonEquality = false; 10448 10449 auto SplitAndProve = 10450 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10451 if (!ProvedNonStrictComparison) 10452 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10453 if (!ProvedNonEquality) 10454 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10455 if (ProvedNonStrictComparison && ProvedNonEquality) 10456 return true; 10457 return false; 10458 }; 10459 10460 if (ProvingStrictComparison) { 10461 auto ProofFn = [&](ICmpInst::Predicate P) { 10462 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10463 }; 10464 if (SplitAndProve(ProofFn)) 10465 return true; 10466 } 10467 10468 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10469 auto ProveViaGuard = [&](const BasicBlock *Block) { 10470 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10471 return true; 10472 if (ProvingStrictComparison) { 10473 auto ProofFn = [&](ICmpInst::Predicate P) { 10474 return isImpliedViaGuard(Block, P, LHS, RHS); 10475 }; 10476 if (SplitAndProve(ProofFn)) 10477 return true; 10478 } 10479 return false; 10480 }; 10481 10482 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10483 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10484 const Instruction *CtxI = &BB->front(); 10485 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10486 return true; 10487 if (ProvingStrictComparison) { 10488 auto ProofFn = [&](ICmpInst::Predicate P) { 10489 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10490 }; 10491 if (SplitAndProve(ProofFn)) 10492 return true; 10493 } 10494 return false; 10495 }; 10496 10497 // Starting at the block's predecessor, climb up the predecessor chain, as long 10498 // as there are predecessors that can be found that have unique successors 10499 // leading to the original block. 10500 const Loop *ContainingLoop = LI.getLoopFor(BB); 10501 const BasicBlock *PredBB; 10502 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10503 PredBB = ContainingLoop->getLoopPredecessor(); 10504 else 10505 PredBB = BB->getSinglePredecessor(); 10506 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10507 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10508 if (ProveViaGuard(Pair.first)) 10509 return true; 10510 10511 const BranchInst *LoopEntryPredicate = 10512 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10513 if (!LoopEntryPredicate || 10514 LoopEntryPredicate->isUnconditional()) 10515 continue; 10516 10517 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10518 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10519 return true; 10520 } 10521 10522 // Check conditions due to any @llvm.assume intrinsics. 10523 for (auto &AssumeVH : AC.assumptions()) { 10524 if (!AssumeVH) 10525 continue; 10526 auto *CI = cast<CallInst>(AssumeVH); 10527 if (!DT.dominates(CI, BB)) 10528 continue; 10529 10530 if (ProveViaCond(CI->getArgOperand(0), false)) 10531 return true; 10532 } 10533 10534 return false; 10535 } 10536 10537 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10538 ICmpInst::Predicate Pred, 10539 const SCEV *LHS, 10540 const SCEV *RHS) { 10541 // Interpret a null as meaning no loop, where there is obviously no guard 10542 // (interprocedural conditions notwithstanding). 10543 if (!L) 10544 return false; 10545 10546 // Both LHS and RHS must be available at loop entry. 10547 assert(isAvailableAtLoopEntry(LHS, L) && 10548 "LHS is not available at Loop Entry"); 10549 assert(isAvailableAtLoopEntry(RHS, L) && 10550 "RHS is not available at Loop Entry"); 10551 10552 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10553 return true; 10554 10555 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10556 } 10557 10558 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10559 const SCEV *RHS, 10560 const Value *FoundCondValue, bool Inverse, 10561 const Instruction *CtxI) { 10562 // False conditions implies anything. Do not bother analyzing it further. 10563 if (FoundCondValue == 10564 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10565 return true; 10566 10567 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10568 return false; 10569 10570 auto ClearOnExit = 10571 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10572 10573 // Recursively handle And and Or conditions. 10574 const Value *Op0, *Op1; 10575 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10576 if (!Inverse) 10577 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10578 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10579 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10580 if (Inverse) 10581 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10582 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10583 } 10584 10585 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10586 if (!ICI) return false; 10587 10588 // Now that we found a conditional branch that dominates the loop or controls 10589 // the loop latch. Check to see if it is the comparison we are looking for. 10590 ICmpInst::Predicate FoundPred; 10591 if (Inverse) 10592 FoundPred = ICI->getInversePredicate(); 10593 else 10594 FoundPred = ICI->getPredicate(); 10595 10596 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10597 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10598 10599 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10600 } 10601 10602 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10603 const SCEV *RHS, 10604 ICmpInst::Predicate FoundPred, 10605 const SCEV *FoundLHS, const SCEV *FoundRHS, 10606 const Instruction *CtxI) { 10607 // Balance the types. 10608 if (getTypeSizeInBits(LHS->getType()) < 10609 getTypeSizeInBits(FoundLHS->getType())) { 10610 // For unsigned and equality predicates, try to prove that both found 10611 // operands fit into narrow unsigned range. If so, try to prove facts in 10612 // narrow types. 10613 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy()) { 10614 auto *NarrowType = LHS->getType(); 10615 auto *WideType = FoundLHS->getType(); 10616 auto BitWidth = getTypeSizeInBits(NarrowType); 10617 const SCEV *MaxValue = getZeroExtendExpr( 10618 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10619 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10620 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10621 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10622 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10623 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10624 TruncFoundRHS, CtxI)) 10625 return true; 10626 } 10627 } 10628 10629 if (LHS->getType()->isPointerTy()) 10630 return false; 10631 if (CmpInst::isSigned(Pred)) { 10632 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10633 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10634 } else { 10635 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10636 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10637 } 10638 } else if (getTypeSizeInBits(LHS->getType()) > 10639 getTypeSizeInBits(FoundLHS->getType())) { 10640 if (FoundLHS->getType()->isPointerTy()) 10641 return false; 10642 if (CmpInst::isSigned(FoundPred)) { 10643 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10644 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10645 } else { 10646 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10647 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10648 } 10649 } 10650 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10651 FoundRHS, CtxI); 10652 } 10653 10654 bool ScalarEvolution::isImpliedCondBalancedTypes( 10655 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10656 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10657 const Instruction *CtxI) { 10658 assert(getTypeSizeInBits(LHS->getType()) == 10659 getTypeSizeInBits(FoundLHS->getType()) && 10660 "Types should be balanced!"); 10661 // Canonicalize the query to match the way instcombine will have 10662 // canonicalized the comparison. 10663 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10664 if (LHS == RHS) 10665 return CmpInst::isTrueWhenEqual(Pred); 10666 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10667 if (FoundLHS == FoundRHS) 10668 return CmpInst::isFalseWhenEqual(FoundPred); 10669 10670 // Check to see if we can make the LHS or RHS match. 10671 if (LHS == FoundRHS || RHS == FoundLHS) { 10672 if (isa<SCEVConstant>(RHS)) { 10673 std::swap(FoundLHS, FoundRHS); 10674 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10675 } else { 10676 std::swap(LHS, RHS); 10677 Pred = ICmpInst::getSwappedPredicate(Pred); 10678 } 10679 } 10680 10681 // Check whether the found predicate is the same as the desired predicate. 10682 if (FoundPred == Pred) 10683 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10684 10685 // Check whether swapping the found predicate makes it the same as the 10686 // desired predicate. 10687 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10688 // We can write the implication 10689 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10690 // using one of the following ways: 10691 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10692 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10693 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10694 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10695 // Forms 1. and 2. require swapping the operands of one condition. Don't 10696 // do this if it would break canonical constant/addrec ordering. 10697 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10698 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10699 CtxI); 10700 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10701 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 10702 10703 // There's no clear preference between forms 3. and 4., try both. Avoid 10704 // forming getNotSCEV of pointer values as the resulting subtract is 10705 // not legal. 10706 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 10707 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10708 FoundLHS, FoundRHS, CtxI)) 10709 return true; 10710 10711 if (!FoundLHS->getType()->isPointerTy() && 10712 !FoundRHS->getType()->isPointerTy() && 10713 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10714 getNotSCEV(FoundRHS), CtxI)) 10715 return true; 10716 10717 return false; 10718 } 10719 10720 // Unsigned comparison is the same as signed comparison when both the operands 10721 // are non-negative or negative. 10722 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 10723 CmpInst::Predicate P2) { 10724 assert(P1 != P2 && "Handled earlier!"); 10725 return CmpInst::isRelational(P2) && 10726 P1 == CmpInst::getFlippedSignednessPredicate(P2); 10727 }; 10728 if (IsSignFlippedPredicate(Pred, FoundPred) && 10729 ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 10730 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))) 10731 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10732 10733 // Check if we can make progress by sharpening ranges. 10734 if (FoundPred == ICmpInst::ICMP_NE && 10735 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10736 10737 const SCEVConstant *C = nullptr; 10738 const SCEV *V = nullptr; 10739 10740 if (isa<SCEVConstant>(FoundLHS)) { 10741 C = cast<SCEVConstant>(FoundLHS); 10742 V = FoundRHS; 10743 } else { 10744 C = cast<SCEVConstant>(FoundRHS); 10745 V = FoundLHS; 10746 } 10747 10748 // The guarding predicate tells us that C != V. If the known range 10749 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10750 // range we consider has to correspond to same signedness as the 10751 // predicate we're interested in folding. 10752 10753 APInt Min = ICmpInst::isSigned(Pred) ? 10754 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10755 10756 if (Min == C->getAPInt()) { 10757 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10758 // This is true even if (Min + 1) wraps around -- in case of 10759 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10760 10761 APInt SharperMin = Min + 1; 10762 10763 switch (Pred) { 10764 case ICmpInst::ICMP_SGE: 10765 case ICmpInst::ICMP_UGE: 10766 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10767 // RHS, we're done. 10768 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10769 CtxI)) 10770 return true; 10771 LLVM_FALLTHROUGH; 10772 10773 case ICmpInst::ICMP_SGT: 10774 case ICmpInst::ICMP_UGT: 10775 // We know from the range information that (V `Pred` Min || 10776 // V == Min). We know from the guarding condition that !(V 10777 // == Min). This gives us 10778 // 10779 // V `Pred` Min || V == Min && !(V == Min) 10780 // => V `Pred` Min 10781 // 10782 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10783 10784 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 10785 return true; 10786 break; 10787 10788 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10789 case ICmpInst::ICMP_SLE: 10790 case ICmpInst::ICMP_ULE: 10791 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10792 LHS, V, getConstant(SharperMin), CtxI)) 10793 return true; 10794 LLVM_FALLTHROUGH; 10795 10796 case ICmpInst::ICMP_SLT: 10797 case ICmpInst::ICMP_ULT: 10798 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10799 LHS, V, getConstant(Min), CtxI)) 10800 return true; 10801 break; 10802 10803 default: 10804 // No change 10805 break; 10806 } 10807 } 10808 } 10809 10810 // Check whether the actual condition is beyond sufficient. 10811 if (FoundPred == ICmpInst::ICMP_EQ) 10812 if (ICmpInst::isTrueWhenEqual(Pred)) 10813 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10814 return true; 10815 if (Pred == ICmpInst::ICMP_NE) 10816 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10817 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 10818 return true; 10819 10820 // Otherwise assume the worst. 10821 return false; 10822 } 10823 10824 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10825 const SCEV *&L, const SCEV *&R, 10826 SCEV::NoWrapFlags &Flags) { 10827 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10828 if (!AE || AE->getNumOperands() != 2) 10829 return false; 10830 10831 L = AE->getOperand(0); 10832 R = AE->getOperand(1); 10833 Flags = AE->getNoWrapFlags(); 10834 return true; 10835 } 10836 10837 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10838 const SCEV *Less) { 10839 // We avoid subtracting expressions here because this function is usually 10840 // fairly deep in the call stack (i.e. is called many times). 10841 10842 // X - X = 0. 10843 if (More == Less) 10844 return APInt(getTypeSizeInBits(More->getType()), 0); 10845 10846 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10847 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10848 const auto *MAR = cast<SCEVAddRecExpr>(More); 10849 10850 if (LAR->getLoop() != MAR->getLoop()) 10851 return None; 10852 10853 // We look at affine expressions only; not for correctness but to keep 10854 // getStepRecurrence cheap. 10855 if (!LAR->isAffine() || !MAR->isAffine()) 10856 return None; 10857 10858 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10859 return None; 10860 10861 Less = LAR->getStart(); 10862 More = MAR->getStart(); 10863 10864 // fall through 10865 } 10866 10867 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10868 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10869 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10870 return M - L; 10871 } 10872 10873 SCEV::NoWrapFlags Flags; 10874 const SCEV *LLess = nullptr, *RLess = nullptr; 10875 const SCEV *LMore = nullptr, *RMore = nullptr; 10876 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10877 // Compare (X + C1) vs X. 10878 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10879 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10880 if (RLess == More) 10881 return -(C1->getAPInt()); 10882 10883 // Compare X vs (X + C2). 10884 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10885 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10886 if (RMore == Less) 10887 return C2->getAPInt(); 10888 10889 // Compare (X + C1) vs (X + C2). 10890 if (C1 && C2 && RLess == RMore) 10891 return C2->getAPInt() - C1->getAPInt(); 10892 10893 return None; 10894 } 10895 10896 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10897 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10898 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 10899 // Try to recognize the following pattern: 10900 // 10901 // FoundRHS = ... 10902 // ... 10903 // loop: 10904 // FoundLHS = {Start,+,W} 10905 // context_bb: // Basic block from the same loop 10906 // known(Pred, FoundLHS, FoundRHS) 10907 // 10908 // If some predicate is known in the context of a loop, it is also known on 10909 // each iteration of this loop, including the first iteration. Therefore, in 10910 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10911 // prove the original pred using this fact. 10912 if (!CtxI) 10913 return false; 10914 const BasicBlock *ContextBB = CtxI->getParent(); 10915 // Make sure AR varies in the context block. 10916 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10917 const Loop *L = AR->getLoop(); 10918 // Make sure that context belongs to the loop and executes on 1st iteration 10919 // (if it ever executes at all). 10920 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10921 return false; 10922 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10923 return false; 10924 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10925 } 10926 10927 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10928 const Loop *L = AR->getLoop(); 10929 // Make sure that context belongs to the loop and executes on 1st iteration 10930 // (if it ever executes at all). 10931 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10932 return false; 10933 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10934 return false; 10935 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10936 } 10937 10938 return false; 10939 } 10940 10941 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10942 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10943 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10944 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10945 return false; 10946 10947 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10948 if (!AddRecLHS) 10949 return false; 10950 10951 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10952 if (!AddRecFoundLHS) 10953 return false; 10954 10955 // We'd like to let SCEV reason about control dependencies, so we constrain 10956 // both the inequalities to be about add recurrences on the same loop. This 10957 // way we can use isLoopEntryGuardedByCond later. 10958 10959 const Loop *L = AddRecFoundLHS->getLoop(); 10960 if (L != AddRecLHS->getLoop()) 10961 return false; 10962 10963 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10964 // 10965 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10966 // ... (2) 10967 // 10968 // Informal proof for (2), assuming (1) [*]: 10969 // 10970 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10971 // 10972 // Then 10973 // 10974 // FoundLHS s< FoundRHS s< INT_MIN - C 10975 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10976 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10977 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10978 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10979 // <=> FoundLHS + C s< FoundRHS + C 10980 // 10981 // [*]: (1) can be proved by ruling out overflow. 10982 // 10983 // [**]: This can be proved by analyzing all the four possibilities: 10984 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10985 // (A s>= 0, B s>= 0). 10986 // 10987 // Note: 10988 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10989 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10990 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10991 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10992 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10993 // C)". 10994 10995 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10996 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10997 if (!LDiff || !RDiff || *LDiff != *RDiff) 10998 return false; 10999 11000 if (LDiff->isMinValue()) 11001 return true; 11002 11003 APInt FoundRHSLimit; 11004 11005 if (Pred == CmpInst::ICMP_ULT) { 11006 FoundRHSLimit = -(*RDiff); 11007 } else { 11008 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11009 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11010 } 11011 11012 // Try to prove (1) or (2), as needed. 11013 return isAvailableAtLoopEntry(FoundRHS, L) && 11014 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11015 getConstant(FoundRHSLimit)); 11016 } 11017 11018 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11019 const SCEV *LHS, const SCEV *RHS, 11020 const SCEV *FoundLHS, 11021 const SCEV *FoundRHS, unsigned Depth) { 11022 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11023 11024 auto ClearOnExit = make_scope_exit([&]() { 11025 if (LPhi) { 11026 bool Erased = PendingMerges.erase(LPhi); 11027 assert(Erased && "Failed to erase LPhi!"); 11028 (void)Erased; 11029 } 11030 if (RPhi) { 11031 bool Erased = PendingMerges.erase(RPhi); 11032 assert(Erased && "Failed to erase RPhi!"); 11033 (void)Erased; 11034 } 11035 }); 11036 11037 // Find respective Phis and check that they are not being pending. 11038 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11039 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11040 if (!PendingMerges.insert(Phi).second) 11041 return false; 11042 LPhi = Phi; 11043 } 11044 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11045 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11046 // If we detect a loop of Phi nodes being processed by this method, for 11047 // example: 11048 // 11049 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11050 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11051 // 11052 // we don't want to deal with a case that complex, so return conservative 11053 // answer false. 11054 if (!PendingMerges.insert(Phi).second) 11055 return false; 11056 RPhi = Phi; 11057 } 11058 11059 // If none of LHS, RHS is a Phi, nothing to do here. 11060 if (!LPhi && !RPhi) 11061 return false; 11062 11063 // If there is a SCEVUnknown Phi we are interested in, make it left. 11064 if (!LPhi) { 11065 std::swap(LHS, RHS); 11066 std::swap(FoundLHS, FoundRHS); 11067 std::swap(LPhi, RPhi); 11068 Pred = ICmpInst::getSwappedPredicate(Pred); 11069 } 11070 11071 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11072 const BasicBlock *LBB = LPhi->getParent(); 11073 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11074 11075 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11076 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11077 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11078 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11079 }; 11080 11081 if (RPhi && RPhi->getParent() == LBB) { 11082 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11083 // If we compare two Phis from the same block, and for each entry block 11084 // the predicate is true for incoming values from this block, then the 11085 // predicate is also true for the Phis. 11086 for (const BasicBlock *IncBB : predecessors(LBB)) { 11087 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11088 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11089 if (!ProvedEasily(L, R)) 11090 return false; 11091 } 11092 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11093 // Case two: RHS is also a Phi from the same basic block, and it is an 11094 // AddRec. It means that there is a loop which has both AddRec and Unknown 11095 // PHIs, for it we can compare incoming values of AddRec from above the loop 11096 // and latch with their respective incoming values of LPhi. 11097 // TODO: Generalize to handle loops with many inputs in a header. 11098 if (LPhi->getNumIncomingValues() != 2) return false; 11099 11100 auto *RLoop = RAR->getLoop(); 11101 auto *Predecessor = RLoop->getLoopPredecessor(); 11102 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11103 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11104 if (!ProvedEasily(L1, RAR->getStart())) 11105 return false; 11106 auto *Latch = RLoop->getLoopLatch(); 11107 assert(Latch && "Loop with AddRec with no latch?"); 11108 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11109 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11110 return false; 11111 } else { 11112 // In all other cases go over inputs of LHS and compare each of them to RHS, 11113 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11114 // At this point RHS is either a non-Phi, or it is a Phi from some block 11115 // different from LBB. 11116 for (const BasicBlock *IncBB : predecessors(LBB)) { 11117 // Check that RHS is available in this block. 11118 if (!dominates(RHS, IncBB)) 11119 return false; 11120 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11121 // Make sure L does not refer to a value from a potentially previous 11122 // iteration of a loop. 11123 if (!properlyDominates(L, IncBB)) 11124 return false; 11125 if (!ProvedEasily(L, RHS)) 11126 return false; 11127 } 11128 } 11129 return true; 11130 } 11131 11132 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11133 const SCEV *LHS, const SCEV *RHS, 11134 const SCEV *FoundLHS, 11135 const SCEV *FoundRHS, 11136 const Instruction *CtxI) { 11137 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11138 return true; 11139 11140 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11141 return true; 11142 11143 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11144 CtxI)) 11145 return true; 11146 11147 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11148 FoundLHS, FoundRHS); 11149 } 11150 11151 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11152 template <typename MinMaxExprType> 11153 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11154 const SCEV *Candidate) { 11155 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11156 if (!MinMaxExpr) 11157 return false; 11158 11159 return is_contained(MinMaxExpr->operands(), Candidate); 11160 } 11161 11162 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11163 ICmpInst::Predicate Pred, 11164 const SCEV *LHS, const SCEV *RHS) { 11165 // If both sides are affine addrecs for the same loop, with equal 11166 // steps, and we know the recurrences don't wrap, then we only 11167 // need to check the predicate on the starting values. 11168 11169 if (!ICmpInst::isRelational(Pred)) 11170 return false; 11171 11172 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11173 if (!LAR) 11174 return false; 11175 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11176 if (!RAR) 11177 return false; 11178 if (LAR->getLoop() != RAR->getLoop()) 11179 return false; 11180 if (!LAR->isAffine() || !RAR->isAffine()) 11181 return false; 11182 11183 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11184 return false; 11185 11186 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11187 SCEV::FlagNSW : SCEV::FlagNUW; 11188 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11189 return false; 11190 11191 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11192 } 11193 11194 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11195 /// expression? 11196 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11197 ICmpInst::Predicate Pred, 11198 const SCEV *LHS, const SCEV *RHS) { 11199 switch (Pred) { 11200 default: 11201 return false; 11202 11203 case ICmpInst::ICMP_SGE: 11204 std::swap(LHS, RHS); 11205 LLVM_FALLTHROUGH; 11206 case ICmpInst::ICMP_SLE: 11207 return 11208 // min(A, ...) <= A 11209 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11210 // A <= max(A, ...) 11211 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11212 11213 case ICmpInst::ICMP_UGE: 11214 std::swap(LHS, RHS); 11215 LLVM_FALLTHROUGH; 11216 case ICmpInst::ICMP_ULE: 11217 return 11218 // min(A, ...) <= A 11219 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11220 // A <= max(A, ...) 11221 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11222 } 11223 11224 llvm_unreachable("covered switch fell through?!"); 11225 } 11226 11227 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11228 const SCEV *LHS, const SCEV *RHS, 11229 const SCEV *FoundLHS, 11230 const SCEV *FoundRHS, 11231 unsigned Depth) { 11232 assert(getTypeSizeInBits(LHS->getType()) == 11233 getTypeSizeInBits(RHS->getType()) && 11234 "LHS and RHS have different sizes?"); 11235 assert(getTypeSizeInBits(FoundLHS->getType()) == 11236 getTypeSizeInBits(FoundRHS->getType()) && 11237 "FoundLHS and FoundRHS have different sizes?"); 11238 // We want to avoid hurting the compile time with analysis of too big trees. 11239 if (Depth > MaxSCEVOperationsImplicationDepth) 11240 return false; 11241 11242 // We only want to work with GT comparison so far. 11243 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11244 Pred = CmpInst::getSwappedPredicate(Pred); 11245 std::swap(LHS, RHS); 11246 std::swap(FoundLHS, FoundRHS); 11247 } 11248 11249 // For unsigned, try to reduce it to corresponding signed comparison. 11250 if (Pred == ICmpInst::ICMP_UGT) 11251 // We can replace unsigned predicate with its signed counterpart if all 11252 // involved values are non-negative. 11253 // TODO: We could have better support for unsigned. 11254 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11255 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11256 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11257 // use this fact to prove that LHS and RHS are non-negative. 11258 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11259 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11260 FoundRHS) && 11261 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11262 FoundRHS)) 11263 Pred = ICmpInst::ICMP_SGT; 11264 } 11265 11266 if (Pred != ICmpInst::ICMP_SGT) 11267 return false; 11268 11269 auto GetOpFromSExt = [&](const SCEV *S) { 11270 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11271 return Ext->getOperand(); 11272 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11273 // the constant in some cases. 11274 return S; 11275 }; 11276 11277 // Acquire values from extensions. 11278 auto *OrigLHS = LHS; 11279 auto *OrigFoundLHS = FoundLHS; 11280 LHS = GetOpFromSExt(LHS); 11281 FoundLHS = GetOpFromSExt(FoundLHS); 11282 11283 // Is the SGT predicate can be proved trivially or using the found context. 11284 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11285 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11286 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11287 FoundRHS, Depth + 1); 11288 }; 11289 11290 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11291 // We want to avoid creation of any new non-constant SCEV. Since we are 11292 // going to compare the operands to RHS, we should be certain that we don't 11293 // need any size extensions for this. So let's decline all cases when the 11294 // sizes of types of LHS and RHS do not match. 11295 // TODO: Maybe try to get RHS from sext to catch more cases? 11296 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11297 return false; 11298 11299 // Should not overflow. 11300 if (!LHSAddExpr->hasNoSignedWrap()) 11301 return false; 11302 11303 auto *LL = LHSAddExpr->getOperand(0); 11304 auto *LR = LHSAddExpr->getOperand(1); 11305 auto *MinusOne = getMinusOne(RHS->getType()); 11306 11307 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11308 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11309 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11310 }; 11311 // Try to prove the following rule: 11312 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11313 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11314 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11315 return true; 11316 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11317 Value *LL, *LR; 11318 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11319 11320 using namespace llvm::PatternMatch; 11321 11322 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11323 // Rules for division. 11324 // We are going to perform some comparisons with Denominator and its 11325 // derivative expressions. In general case, creating a SCEV for it may 11326 // lead to a complex analysis of the entire graph, and in particular it 11327 // can request trip count recalculation for the same loop. This would 11328 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11329 // this, we only want to create SCEVs that are constants in this section. 11330 // So we bail if Denominator is not a constant. 11331 if (!isa<ConstantInt>(LR)) 11332 return false; 11333 11334 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11335 11336 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11337 // then a SCEV for the numerator already exists and matches with FoundLHS. 11338 auto *Numerator = getExistingSCEV(LL); 11339 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11340 return false; 11341 11342 // Make sure that the numerator matches with FoundLHS and the denominator 11343 // is positive. 11344 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11345 return false; 11346 11347 auto *DTy = Denominator->getType(); 11348 auto *FRHSTy = FoundRHS->getType(); 11349 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11350 // One of types is a pointer and another one is not. We cannot extend 11351 // them properly to a wider type, so let us just reject this case. 11352 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11353 // to avoid this check. 11354 return false; 11355 11356 // Given that: 11357 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11358 auto *WTy = getWiderType(DTy, FRHSTy); 11359 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11360 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11361 11362 // Try to prove the following rule: 11363 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11364 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11365 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11366 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11367 if (isKnownNonPositive(RHS) && 11368 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11369 return true; 11370 11371 // Try to prove the following rule: 11372 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11373 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11374 // If we divide it by Denominator > 2, then: 11375 // 1. If FoundLHS is negative, then the result is 0. 11376 // 2. If FoundLHS is non-negative, then the result is non-negative. 11377 // Anyways, the result is non-negative. 11378 auto *MinusOne = getMinusOne(WTy); 11379 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11380 if (isKnownNegative(RHS) && 11381 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11382 return true; 11383 } 11384 } 11385 11386 // If our expression contained SCEVUnknown Phis, and we split it down and now 11387 // need to prove something for them, try to prove the predicate for every 11388 // possible incoming values of those Phis. 11389 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11390 return true; 11391 11392 return false; 11393 } 11394 11395 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11396 const SCEV *LHS, const SCEV *RHS) { 11397 // zext x u<= sext x, sext x s<= zext x 11398 switch (Pred) { 11399 case ICmpInst::ICMP_SGE: 11400 std::swap(LHS, RHS); 11401 LLVM_FALLTHROUGH; 11402 case ICmpInst::ICMP_SLE: { 11403 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11404 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11405 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11406 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11407 return true; 11408 break; 11409 } 11410 case ICmpInst::ICMP_UGE: 11411 std::swap(LHS, RHS); 11412 LLVM_FALLTHROUGH; 11413 case ICmpInst::ICMP_ULE: { 11414 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11415 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11416 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11417 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11418 return true; 11419 break; 11420 } 11421 default: 11422 break; 11423 }; 11424 return false; 11425 } 11426 11427 bool 11428 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11429 const SCEV *LHS, const SCEV *RHS) { 11430 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11431 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11432 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11433 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11434 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11435 } 11436 11437 bool 11438 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11439 const SCEV *LHS, const SCEV *RHS, 11440 const SCEV *FoundLHS, 11441 const SCEV *FoundRHS) { 11442 switch (Pred) { 11443 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11444 case ICmpInst::ICMP_EQ: 11445 case ICmpInst::ICMP_NE: 11446 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11447 return true; 11448 break; 11449 case ICmpInst::ICMP_SLT: 11450 case ICmpInst::ICMP_SLE: 11451 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11452 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11453 return true; 11454 break; 11455 case ICmpInst::ICMP_SGT: 11456 case ICmpInst::ICMP_SGE: 11457 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11458 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11459 return true; 11460 break; 11461 case ICmpInst::ICMP_ULT: 11462 case ICmpInst::ICMP_ULE: 11463 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11464 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11465 return true; 11466 break; 11467 case ICmpInst::ICMP_UGT: 11468 case ICmpInst::ICMP_UGE: 11469 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11470 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11471 return true; 11472 break; 11473 } 11474 11475 // Maybe it can be proved via operations? 11476 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11477 return true; 11478 11479 return false; 11480 } 11481 11482 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11483 const SCEV *LHS, 11484 const SCEV *RHS, 11485 const SCEV *FoundLHS, 11486 const SCEV *FoundRHS) { 11487 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11488 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11489 // reduce the compile time impact of this optimization. 11490 return false; 11491 11492 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11493 if (!Addend) 11494 return false; 11495 11496 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11497 11498 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11499 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11500 ConstantRange FoundLHSRange = 11501 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11502 11503 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11504 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11505 11506 // We can also compute the range of values for `LHS` that satisfy the 11507 // consequent, "`LHS` `Pred` `RHS`": 11508 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11509 // The antecedent implies the consequent if every value of `LHS` that 11510 // satisfies the antecedent also satisfies the consequent. 11511 return LHSRange.icmp(Pred, ConstRHS); 11512 } 11513 11514 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11515 bool IsSigned) { 11516 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11517 11518 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11519 const SCEV *One = getOne(Stride->getType()); 11520 11521 if (IsSigned) { 11522 APInt MaxRHS = getSignedRangeMax(RHS); 11523 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11524 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11525 11526 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11527 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11528 } 11529 11530 APInt MaxRHS = getUnsignedRangeMax(RHS); 11531 APInt MaxValue = APInt::getMaxValue(BitWidth); 11532 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11533 11534 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11535 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11536 } 11537 11538 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11539 bool IsSigned) { 11540 11541 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11542 const SCEV *One = getOne(Stride->getType()); 11543 11544 if (IsSigned) { 11545 APInt MinRHS = getSignedRangeMin(RHS); 11546 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11547 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11548 11549 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11550 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11551 } 11552 11553 APInt MinRHS = getUnsignedRangeMin(RHS); 11554 APInt MinValue = APInt::getMinValue(BitWidth); 11555 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11556 11557 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11558 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11559 } 11560 11561 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11562 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11563 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11564 // expression fixes the case of N=0. 11565 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11566 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11567 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11568 } 11569 11570 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11571 const SCEV *Stride, 11572 const SCEV *End, 11573 unsigned BitWidth, 11574 bool IsSigned) { 11575 // The logic in this function assumes we can represent a positive stride. 11576 // If we can't, the backedge-taken count must be zero. 11577 if (IsSigned && BitWidth == 1) 11578 return getZero(Stride->getType()); 11579 11580 // This code has only been closely audited for negative strides in the 11581 // unsigned comparison case, it may be correct for signed comparison, but 11582 // that needs to be established. 11583 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11584 "Stride is expected strictly positive for signed case!"); 11585 11586 // Calculate the maximum backedge count based on the range of values 11587 // permitted by Start, End, and Stride. 11588 APInt MinStart = 11589 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11590 11591 APInt MinStride = 11592 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11593 11594 // We assume either the stride is positive, or the backedge-taken count 11595 // is zero. So force StrideForMaxBECount to be at least one. 11596 APInt One(BitWidth, 1); 11597 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11598 : APIntOps::umax(One, MinStride); 11599 11600 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11601 : APInt::getMaxValue(BitWidth); 11602 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11603 11604 // Although End can be a MAX expression we estimate MaxEnd considering only 11605 // the case End = RHS of the loop termination condition. This is safe because 11606 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11607 // taken count. 11608 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11609 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11610 11611 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 11612 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 11613 : APIntOps::umax(MaxEnd, MinStart); 11614 11615 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 11616 getConstant(StrideForMaxBECount) /* Step */); 11617 } 11618 11619 ScalarEvolution::ExitLimit 11620 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11621 const Loop *L, bool IsSigned, 11622 bool ControlsExit, bool AllowPredicates) { 11623 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11624 11625 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11626 bool PredicatedIV = false; 11627 11628 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 11629 // Can we prove this loop *must* be UB if overflow of IV occurs? 11630 // Reasoning goes as follows: 11631 // * Suppose the IV did self wrap. 11632 // * If Stride evenly divides the iteration space, then once wrap 11633 // occurs, the loop must revisit the same values. 11634 // * We know that RHS is invariant, and that none of those values 11635 // caused this exit to be taken previously. Thus, this exit is 11636 // dynamically dead. 11637 // * If this is the sole exit, then a dead exit implies the loop 11638 // must be infinite if there are no abnormal exits. 11639 // * If the loop were infinite, then it must either not be mustprogress 11640 // or have side effects. Otherwise, it must be UB. 11641 // * It can't (by assumption), be UB so we have contradicted our 11642 // premise and can conclude the IV did not in fact self-wrap. 11643 if (!isLoopInvariant(RHS, L)) 11644 return false; 11645 11646 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 11647 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11648 return false; 11649 11650 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11651 return false; 11652 11653 return loopIsFiniteByAssumption(L); 11654 }; 11655 11656 if (!IV) { 11657 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 11658 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 11659 if (AR && AR->getLoop() == L && AR->isAffine()) { 11660 auto Flags = AR->getNoWrapFlags(); 11661 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) { 11662 Flags = setFlags(Flags, SCEV::FlagNW); 11663 11664 SmallVector<const SCEV*> Operands{AR->operands()}; 11665 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 11666 11667 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 11668 } 11669 if (AR->hasNoUnsignedWrap()) { 11670 // Emulate what getZeroExtendExpr would have done during construction 11671 // if we'd been able to infer the fact just above at that time. 11672 const SCEV *Step = AR->getStepRecurrence(*this); 11673 Type *Ty = ZExt->getType(); 11674 auto *S = getAddRecExpr( 11675 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 11676 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 11677 IV = dyn_cast<SCEVAddRecExpr>(S); 11678 } 11679 } 11680 } 11681 } 11682 11683 11684 if (!IV && AllowPredicates) { 11685 // Try to make this an AddRec using runtime tests, in the first X 11686 // iterations of this loop, where X is the SCEV expression found by the 11687 // algorithm below. 11688 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11689 PredicatedIV = true; 11690 } 11691 11692 // Avoid weird loops 11693 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11694 return getCouldNotCompute(); 11695 11696 // A precondition of this method is that the condition being analyzed 11697 // reaches an exiting branch which dominates the latch. Given that, we can 11698 // assume that an increment which violates the nowrap specification and 11699 // produces poison must cause undefined behavior when the resulting poison 11700 // value is branched upon and thus we can conclude that the backedge is 11701 // taken no more often than would be required to produce that poison value. 11702 // Note that a well defined loop can exit on the iteration which violates 11703 // the nowrap specification if there is another exit (either explicit or 11704 // implicit/exceptional) which causes the loop to execute before the 11705 // exiting instruction we're analyzing would trigger UB. 11706 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 11707 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 11708 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 11709 11710 const SCEV *Stride = IV->getStepRecurrence(*this); 11711 11712 bool PositiveStride = isKnownPositive(Stride); 11713 11714 // Avoid negative or zero stride values. 11715 if (!PositiveStride) { 11716 // We can compute the correct backedge taken count for loops with unknown 11717 // strides if we can prove that the loop is not an infinite loop with side 11718 // effects. Here's the loop structure we are trying to handle - 11719 // 11720 // i = start 11721 // do { 11722 // A[i] = i; 11723 // i += s; 11724 // } while (i < end); 11725 // 11726 // The backedge taken count for such loops is evaluated as - 11727 // (max(end, start + stride) - start - 1) /u stride 11728 // 11729 // The additional preconditions that we need to check to prove correctness 11730 // of the above formula is as follows - 11731 // 11732 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11733 // NoWrap flag). 11734 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 11735 // no side effects within the loop) 11736 // c) loop has a single static exit (with no abnormal exits) 11737 // 11738 // Precondition a) implies that if the stride is negative, this is a single 11739 // trip loop. The backedge taken count formula reduces to zero in this case. 11740 // 11741 // Precondition b) and c) combine to imply that if rhs is invariant in L, 11742 // then a zero stride means the backedge can't be taken without executing 11743 // undefined behavior. 11744 // 11745 // The positive stride case is the same as isKnownPositive(Stride) returning 11746 // true (original behavior of the function). 11747 // 11748 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 11749 !loopHasNoAbnormalExits(L)) 11750 return getCouldNotCompute(); 11751 11752 // This bailout is protecting the logic in computeMaxBECountForLT which 11753 // has not yet been sufficiently auditted or tested with negative strides. 11754 // We used to filter out all known-non-positive cases here, we're in the 11755 // process of being less restrictive bit by bit. 11756 if (IsSigned && isKnownNonPositive(Stride)) 11757 return getCouldNotCompute(); 11758 11759 if (!isKnownNonZero(Stride)) { 11760 // If we have a step of zero, and RHS isn't invariant in L, we don't know 11761 // if it might eventually be greater than start and if so, on which 11762 // iteration. We can't even produce a useful upper bound. 11763 if (!isLoopInvariant(RHS, L)) 11764 return getCouldNotCompute(); 11765 11766 // We allow a potentially zero stride, but we need to divide by stride 11767 // below. Since the loop can't be infinite and this check must control 11768 // the sole exit, we can infer the exit must be taken on the first 11769 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 11770 // we know the numerator in the divides below must be zero, so we can 11771 // pick an arbitrary non-zero value for the denominator (e.g. stride) 11772 // and produce the right result. 11773 // FIXME: Handle the case where Stride is poison? 11774 auto wouldZeroStrideBeUB = [&]() { 11775 // Proof by contradiction. Suppose the stride were zero. If we can 11776 // prove that the backedge *is* taken on the first iteration, then since 11777 // we know this condition controls the sole exit, we must have an 11778 // infinite loop. We can't have a (well defined) infinite loop per 11779 // check just above. 11780 // Note: The (Start - Stride) term is used to get the start' term from 11781 // (start' + stride,+,stride). Remember that we only care about the 11782 // result of this expression when stride == 0 at runtime. 11783 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 11784 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 11785 }; 11786 if (!wouldZeroStrideBeUB()) { 11787 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 11788 } 11789 } 11790 } else if (!Stride->isOne() && !NoWrap) { 11791 auto isUBOnWrap = [&]() { 11792 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11793 // follows trivially from the fact that every (un)signed-wrapped, but 11794 // not self-wrapped value must be LT than the last value before 11795 // (un)signed wrap. Since we know that last value didn't exit, nor 11796 // will any smaller one. 11797 return canAssumeNoSelfWrap(IV); 11798 }; 11799 11800 // Avoid proven overflow cases: this will ensure that the backedge taken 11801 // count will not generate any unsigned overflow. Relaxed no-overflow 11802 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11803 // undefined behaviors like the case of C language. 11804 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11805 return getCouldNotCompute(); 11806 } 11807 11808 // On all paths just preceeding, we established the following invariant: 11809 // IV can be assumed not to overflow up to and including the exiting 11810 // iteration. We proved this in one of two ways: 11811 // 1) We can show overflow doesn't occur before the exiting iteration 11812 // 1a) canIVOverflowOnLT, and b) step of one 11813 // 2) We can show that if overflow occurs, the loop must execute UB 11814 // before any possible exit. 11815 // Note that we have not yet proved RHS invariant (in general). 11816 11817 const SCEV *Start = IV->getStart(); 11818 11819 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 11820 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 11821 // Use integer-typed versions for actual computation; we can't subtract 11822 // pointers in general. 11823 const SCEV *OrigStart = Start; 11824 const SCEV *OrigRHS = RHS; 11825 if (Start->getType()->isPointerTy()) { 11826 Start = getLosslessPtrToIntExpr(Start); 11827 if (isa<SCEVCouldNotCompute>(Start)) 11828 return Start; 11829 } 11830 if (RHS->getType()->isPointerTy()) { 11831 RHS = getLosslessPtrToIntExpr(RHS); 11832 if (isa<SCEVCouldNotCompute>(RHS)) 11833 return RHS; 11834 } 11835 11836 // When the RHS is not invariant, we do not know the end bound of the loop and 11837 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11838 // calculate the MaxBECount, given the start, stride and max value for the end 11839 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11840 // checked above). 11841 if (!isLoopInvariant(RHS, L)) { 11842 const SCEV *MaxBECount = computeMaxBECountForLT( 11843 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11844 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11845 false /*MaxOrZero*/, Predicates); 11846 } 11847 11848 // We use the expression (max(End,Start)-Start)/Stride to describe the 11849 // backedge count, as if the backedge is taken at least once max(End,Start) 11850 // is End and so the result is as above, and if not max(End,Start) is Start 11851 // so we get a backedge count of zero. 11852 const SCEV *BECount = nullptr; 11853 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 11854 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 11855 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 11856 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 11857 // Can we prove (max(RHS,Start) > Start - Stride? 11858 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 11859 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 11860 // In this case, we can use a refined formula for computing backedge taken 11861 // count. The general formula remains: 11862 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 11863 // We want to use the alternate formula: 11864 // "((End - 1) - (Start - Stride)) /u Stride" 11865 // Let's do a quick case analysis to show these are equivalent under 11866 // our precondition that max(RHS,Start) > Start - Stride. 11867 // * For RHS <= Start, the backedge-taken count must be zero. 11868 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11869 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 11870 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 11871 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 11872 // this to the stride of 1 case. 11873 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 11874 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 11875 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 11876 // "((RHS - (Start - Stride) - 1) /u Stride". 11877 // Our preconditions trivially imply no overflow in that form. 11878 const SCEV *MinusOne = getMinusOne(Stride->getType()); 11879 const SCEV *Numerator = 11880 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 11881 BECount = getUDivExpr(Numerator, Stride); 11882 } 11883 11884 const SCEV *BECountIfBackedgeTaken = nullptr; 11885 if (!BECount) { 11886 auto canProveRHSGreaterThanEqualStart = [&]() { 11887 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 11888 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 11889 return true; 11890 11891 // (RHS > Start - 1) implies RHS >= Start. 11892 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 11893 // "Start - 1" doesn't overflow. 11894 // * For signed comparison, if Start - 1 does overflow, it's equal 11895 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 11896 // * For unsigned comparison, if Start - 1 does overflow, it's equal 11897 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 11898 // 11899 // FIXME: Should isLoopEntryGuardedByCond do this for us? 11900 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 11901 auto *StartMinusOne = getAddExpr(OrigStart, 11902 getMinusOne(OrigStart->getType())); 11903 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 11904 }; 11905 11906 // If we know that RHS >= Start in the context of loop, then we know that 11907 // max(RHS, Start) = RHS at this point. 11908 const SCEV *End; 11909 if (canProveRHSGreaterThanEqualStart()) { 11910 End = RHS; 11911 } else { 11912 // If RHS < Start, the backedge will be taken zero times. So in 11913 // general, we can write the backedge-taken count as: 11914 // 11915 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 11916 // 11917 // We convert it to the following to make it more convenient for SCEV: 11918 // 11919 // ceil(max(RHS, Start) - Start) / Stride 11920 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11921 11922 // See what would happen if we assume the backedge is taken. This is 11923 // used to compute MaxBECount. 11924 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 11925 } 11926 11927 // At this point, we know: 11928 // 11929 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 11930 // 2. The index variable doesn't overflow. 11931 // 11932 // Therefore, we know N exists such that 11933 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 11934 // doesn't overflow. 11935 // 11936 // Using this information, try to prove whether the addition in 11937 // "(Start - End) + (Stride - 1)" has unsigned overflow. 11938 const SCEV *One = getOne(Stride->getType()); 11939 bool MayAddOverflow = [&] { 11940 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 11941 if (StrideC->getAPInt().isPowerOf2()) { 11942 // Suppose Stride is a power of two, and Start/End are unsigned 11943 // integers. Let UMAX be the largest representable unsigned 11944 // integer. 11945 // 11946 // By the preconditions of this function, we know 11947 // "(Start + Stride * N) >= End", and this doesn't overflow. 11948 // As a formula: 11949 // 11950 // End <= (Start + Stride * N) <= UMAX 11951 // 11952 // Subtracting Start from all the terms: 11953 // 11954 // End - Start <= Stride * N <= UMAX - Start 11955 // 11956 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 11957 // 11958 // End - Start <= Stride * N <= UMAX 11959 // 11960 // Stride * N is a multiple of Stride. Therefore, 11961 // 11962 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 11963 // 11964 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 11965 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 11966 // 11967 // End - Start <= Stride * N <= UMAX - Stride - 1 11968 // 11969 // Dropping the middle term: 11970 // 11971 // End - Start <= UMAX - Stride - 1 11972 // 11973 // Adding Stride - 1 to both sides: 11974 // 11975 // (End - Start) + (Stride - 1) <= UMAX 11976 // 11977 // In other words, the addition doesn't have unsigned overflow. 11978 // 11979 // A similar proof works if we treat Start/End as signed values. 11980 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 11981 // use signed max instead of unsigned max. Note that we're trying 11982 // to prove a lack of unsigned overflow in either case. 11983 return false; 11984 } 11985 } 11986 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 11987 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 11988 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 11989 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 11990 // 11991 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 11992 return false; 11993 } 11994 return true; 11995 }(); 11996 11997 const SCEV *Delta = getMinusSCEV(End, Start); 11998 if (!MayAddOverflow) { 11999 // floor((D + (S - 1)) / S) 12000 // We prefer this formulation if it's legal because it's fewer operations. 12001 BECount = 12002 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12003 } else { 12004 BECount = getUDivCeilSCEV(Delta, Stride); 12005 } 12006 } 12007 12008 const SCEV *MaxBECount; 12009 bool MaxOrZero = false; 12010 if (isa<SCEVConstant>(BECount)) { 12011 MaxBECount = BECount; 12012 } else if (BECountIfBackedgeTaken && 12013 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12014 // If we know exactly how many times the backedge will be taken if it's 12015 // taken at least once, then the backedge count will either be that or 12016 // zero. 12017 MaxBECount = BECountIfBackedgeTaken; 12018 MaxOrZero = true; 12019 } else { 12020 MaxBECount = computeMaxBECountForLT( 12021 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12022 } 12023 12024 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12025 !isa<SCEVCouldNotCompute>(BECount)) 12026 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12027 12028 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12029 } 12030 12031 ScalarEvolution::ExitLimit 12032 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12033 const Loop *L, bool IsSigned, 12034 bool ControlsExit, bool AllowPredicates) { 12035 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12036 // We handle only IV > Invariant 12037 if (!isLoopInvariant(RHS, L)) 12038 return getCouldNotCompute(); 12039 12040 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12041 if (!IV && AllowPredicates) 12042 // Try to make this an AddRec using runtime tests, in the first X 12043 // iterations of this loop, where X is the SCEV expression found by the 12044 // algorithm below. 12045 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12046 12047 // Avoid weird loops 12048 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12049 return getCouldNotCompute(); 12050 12051 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12052 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12053 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12054 12055 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12056 12057 // Avoid negative or zero stride values 12058 if (!isKnownPositive(Stride)) 12059 return getCouldNotCompute(); 12060 12061 // Avoid proven overflow cases: this will ensure that the backedge taken count 12062 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12063 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12064 // behaviors like the case of C language. 12065 if (!Stride->isOne() && !NoWrap) 12066 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12067 return getCouldNotCompute(); 12068 12069 const SCEV *Start = IV->getStart(); 12070 const SCEV *End = RHS; 12071 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12072 // If we know that Start >= RHS in the context of loop, then we know that 12073 // min(RHS, Start) = RHS at this point. 12074 if (isLoopEntryGuardedByCond( 12075 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12076 End = RHS; 12077 else 12078 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12079 } 12080 12081 if (Start->getType()->isPointerTy()) { 12082 Start = getLosslessPtrToIntExpr(Start); 12083 if (isa<SCEVCouldNotCompute>(Start)) 12084 return Start; 12085 } 12086 if (End->getType()->isPointerTy()) { 12087 End = getLosslessPtrToIntExpr(End); 12088 if (isa<SCEVCouldNotCompute>(End)) 12089 return End; 12090 } 12091 12092 // Compute ((Start - End) + (Stride - 1)) / Stride. 12093 // FIXME: This can overflow. Holding off on fixing this for now; 12094 // howManyGreaterThans will hopefully be gone soon. 12095 const SCEV *One = getOne(Stride->getType()); 12096 const SCEV *BECount = getUDivExpr( 12097 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12098 12099 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12100 : getUnsignedRangeMax(Start); 12101 12102 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12103 : getUnsignedRangeMin(Stride); 12104 12105 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12106 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12107 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12108 12109 // Although End can be a MIN expression we estimate MinEnd considering only 12110 // the case End = RHS. This is safe because in the other case (Start - End) 12111 // is zero, leading to a zero maximum backedge taken count. 12112 APInt MinEnd = 12113 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12114 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12115 12116 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12117 ? BECount 12118 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12119 getConstant(MinStride)); 12120 12121 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12122 MaxBECount = BECount; 12123 12124 return ExitLimit(BECount, MaxBECount, false, Predicates); 12125 } 12126 12127 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12128 ScalarEvolution &SE) const { 12129 if (Range.isFullSet()) // Infinite loop. 12130 return SE.getCouldNotCompute(); 12131 12132 // If the start is a non-zero constant, shift the range to simplify things. 12133 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12134 if (!SC->getValue()->isZero()) { 12135 SmallVector<const SCEV *, 4> Operands(operands()); 12136 Operands[0] = SE.getZero(SC->getType()); 12137 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12138 getNoWrapFlags(FlagNW)); 12139 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12140 return ShiftedAddRec->getNumIterationsInRange( 12141 Range.subtract(SC->getAPInt()), SE); 12142 // This is strange and shouldn't happen. 12143 return SE.getCouldNotCompute(); 12144 } 12145 12146 // The only time we can solve this is when we have all constant indices. 12147 // Otherwise, we cannot determine the overflow conditions. 12148 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12149 return SE.getCouldNotCompute(); 12150 12151 // Okay at this point we know that all elements of the chrec are constants and 12152 // that the start element is zero. 12153 12154 // First check to see if the range contains zero. If not, the first 12155 // iteration exits. 12156 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12157 if (!Range.contains(APInt(BitWidth, 0))) 12158 return SE.getZero(getType()); 12159 12160 if (isAffine()) { 12161 // If this is an affine expression then we have this situation: 12162 // Solve {0,+,A} in Range === Ax in Range 12163 12164 // We know that zero is in the range. If A is positive then we know that 12165 // the upper value of the range must be the first possible exit value. 12166 // If A is negative then the lower of the range is the last possible loop 12167 // value. Also note that we already checked for a full range. 12168 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12169 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12170 12171 // The exit value should be (End+A)/A. 12172 APInt ExitVal = (End + A).udiv(A); 12173 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12174 12175 // Evaluate at the exit value. If we really did fall out of the valid 12176 // range, then we computed our trip count, otherwise wrap around or other 12177 // things must have happened. 12178 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12179 if (Range.contains(Val->getValue())) 12180 return SE.getCouldNotCompute(); // Something strange happened 12181 12182 // Ensure that the previous value is in the range. This is a sanity check. 12183 assert(Range.contains( 12184 EvaluateConstantChrecAtConstant(this, 12185 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12186 "Linear scev computation is off in a bad way!"); 12187 return SE.getConstant(ExitValue); 12188 } 12189 12190 if (isQuadratic()) { 12191 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12192 return SE.getConstant(S.getValue()); 12193 } 12194 12195 return SE.getCouldNotCompute(); 12196 } 12197 12198 const SCEVAddRecExpr * 12199 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12200 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12201 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12202 // but in this case we cannot guarantee that the value returned will be an 12203 // AddRec because SCEV does not have a fixed point where it stops 12204 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12205 // may happen if we reach arithmetic depth limit while simplifying. So we 12206 // construct the returned value explicitly. 12207 SmallVector<const SCEV *, 3> Ops; 12208 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12209 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12210 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12211 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12212 // We know that the last operand is not a constant zero (otherwise it would 12213 // have been popped out earlier). This guarantees us that if the result has 12214 // the same last operand, then it will also not be popped out, meaning that 12215 // the returned value will be an AddRec. 12216 const SCEV *Last = getOperand(getNumOperands() - 1); 12217 assert(!Last->isZero() && "Recurrency with zero step?"); 12218 Ops.push_back(Last); 12219 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12220 SCEV::FlagAnyWrap)); 12221 } 12222 12223 // Return true when S contains at least an undef value. 12224 static inline bool containsUndefs(const SCEV *S) { 12225 return SCEVExprContains(S, [](const SCEV *S) { 12226 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12227 return isa<UndefValue>(SU->getValue()); 12228 return false; 12229 }); 12230 } 12231 12232 /// Return the size of an element read or written by Inst. 12233 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12234 Type *Ty; 12235 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12236 Ty = Store->getValueOperand()->getType(); 12237 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12238 Ty = Load->getType(); 12239 else 12240 return nullptr; 12241 12242 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12243 return getSizeOfExpr(ETy, Ty); 12244 } 12245 12246 //===----------------------------------------------------------------------===// 12247 // SCEVCallbackVH Class Implementation 12248 //===----------------------------------------------------------------------===// 12249 12250 void ScalarEvolution::SCEVCallbackVH::deleted() { 12251 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12252 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12253 SE->ConstantEvolutionLoopExitValue.erase(PN); 12254 SE->eraseValueFromMap(getValPtr()); 12255 // this now dangles! 12256 } 12257 12258 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12259 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12260 12261 // Forget all the expressions associated with users of the old value, 12262 // so that future queries will recompute the expressions using the new 12263 // value. 12264 Value *Old = getValPtr(); 12265 SmallVector<User *, 16> Worklist(Old->users()); 12266 SmallPtrSet<User *, 8> Visited; 12267 while (!Worklist.empty()) { 12268 User *U = Worklist.pop_back_val(); 12269 // Deleting the Old value will cause this to dangle. Postpone 12270 // that until everything else is done. 12271 if (U == Old) 12272 continue; 12273 if (!Visited.insert(U).second) 12274 continue; 12275 if (PHINode *PN = dyn_cast<PHINode>(U)) 12276 SE->ConstantEvolutionLoopExitValue.erase(PN); 12277 SE->eraseValueFromMap(U); 12278 llvm::append_range(Worklist, U->users()); 12279 } 12280 // Delete the Old value. 12281 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12282 SE->ConstantEvolutionLoopExitValue.erase(PN); 12283 SE->eraseValueFromMap(Old); 12284 // this now dangles! 12285 } 12286 12287 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12288 : CallbackVH(V), SE(se) {} 12289 12290 //===----------------------------------------------------------------------===// 12291 // ScalarEvolution Class Implementation 12292 //===----------------------------------------------------------------------===// 12293 12294 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12295 AssumptionCache &AC, DominatorTree &DT, 12296 LoopInfo &LI) 12297 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12298 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12299 LoopDispositions(64), BlockDispositions(64) { 12300 // To use guards for proving predicates, we need to scan every instruction in 12301 // relevant basic blocks, and not just terminators. Doing this is a waste of 12302 // time if the IR does not actually contain any calls to 12303 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12304 // 12305 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12306 // to _add_ guards to the module when there weren't any before, and wants 12307 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12308 // efficient in lieu of being smart in that rather obscure case. 12309 12310 auto *GuardDecl = F.getParent()->getFunction( 12311 Intrinsic::getName(Intrinsic::experimental_guard)); 12312 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12313 } 12314 12315 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12316 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12317 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12318 ValueExprMap(std::move(Arg.ValueExprMap)), 12319 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12320 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12321 PendingMerges(std::move(Arg.PendingMerges)), 12322 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12323 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12324 PredicatedBackedgeTakenCounts( 12325 std::move(Arg.PredicatedBackedgeTakenCounts)), 12326 ConstantEvolutionLoopExitValue( 12327 std::move(Arg.ConstantEvolutionLoopExitValue)), 12328 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12329 LoopDispositions(std::move(Arg.LoopDispositions)), 12330 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12331 BlockDispositions(std::move(Arg.BlockDispositions)), 12332 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12333 SignedRanges(std::move(Arg.SignedRanges)), 12334 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12335 UniquePreds(std::move(Arg.UniquePreds)), 12336 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12337 LoopUsers(std::move(Arg.LoopUsers)), 12338 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12339 FirstUnknown(Arg.FirstUnknown) { 12340 Arg.FirstUnknown = nullptr; 12341 } 12342 12343 ScalarEvolution::~ScalarEvolution() { 12344 // Iterate through all the SCEVUnknown instances and call their 12345 // destructors, so that they release their references to their values. 12346 for (SCEVUnknown *U = FirstUnknown; U;) { 12347 SCEVUnknown *Tmp = U; 12348 U = U->Next; 12349 Tmp->~SCEVUnknown(); 12350 } 12351 FirstUnknown = nullptr; 12352 12353 ExprValueMap.clear(); 12354 ValueExprMap.clear(); 12355 HasRecMap.clear(); 12356 BackedgeTakenCounts.clear(); 12357 PredicatedBackedgeTakenCounts.clear(); 12358 12359 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12360 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12361 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12362 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12363 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12364 } 12365 12366 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12367 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12368 } 12369 12370 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12371 const Loop *L) { 12372 // Print all inner loops first 12373 for (Loop *I : *L) 12374 PrintLoopInfo(OS, SE, I); 12375 12376 OS << "Loop "; 12377 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12378 OS << ": "; 12379 12380 SmallVector<BasicBlock *, 8> ExitingBlocks; 12381 L->getExitingBlocks(ExitingBlocks); 12382 if (ExitingBlocks.size() != 1) 12383 OS << "<multiple exits> "; 12384 12385 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12386 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12387 else 12388 OS << "Unpredictable backedge-taken count.\n"; 12389 12390 if (ExitingBlocks.size() > 1) 12391 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12392 OS << " exit count for " << ExitingBlock->getName() << ": " 12393 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12394 } 12395 12396 OS << "Loop "; 12397 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12398 OS << ": "; 12399 12400 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12401 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12402 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12403 OS << ", actual taken count either this or zero."; 12404 } else { 12405 OS << "Unpredictable max backedge-taken count. "; 12406 } 12407 12408 OS << "\n" 12409 "Loop "; 12410 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12411 OS << ": "; 12412 12413 SCEVUnionPredicate Pred; 12414 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12415 if (!isa<SCEVCouldNotCompute>(PBT)) { 12416 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12417 OS << " Predicates:\n"; 12418 Pred.print(OS, 4); 12419 } else { 12420 OS << "Unpredictable predicated backedge-taken count. "; 12421 } 12422 OS << "\n"; 12423 12424 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12425 OS << "Loop "; 12426 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12427 OS << ": "; 12428 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12429 } 12430 } 12431 12432 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12433 switch (LD) { 12434 case ScalarEvolution::LoopVariant: 12435 return "Variant"; 12436 case ScalarEvolution::LoopInvariant: 12437 return "Invariant"; 12438 case ScalarEvolution::LoopComputable: 12439 return "Computable"; 12440 } 12441 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12442 } 12443 12444 void ScalarEvolution::print(raw_ostream &OS) const { 12445 // ScalarEvolution's implementation of the print method is to print 12446 // out SCEV values of all instructions that are interesting. Doing 12447 // this potentially causes it to create new SCEV objects though, 12448 // which technically conflicts with the const qualifier. This isn't 12449 // observable from outside the class though, so casting away the 12450 // const isn't dangerous. 12451 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12452 12453 if (ClassifyExpressions) { 12454 OS << "Classifying expressions for: "; 12455 F.printAsOperand(OS, /*PrintType=*/false); 12456 OS << "\n"; 12457 for (Instruction &I : instructions(F)) 12458 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12459 OS << I << '\n'; 12460 OS << " --> "; 12461 const SCEV *SV = SE.getSCEV(&I); 12462 SV->print(OS); 12463 if (!isa<SCEVCouldNotCompute>(SV)) { 12464 OS << " U: "; 12465 SE.getUnsignedRange(SV).print(OS); 12466 OS << " S: "; 12467 SE.getSignedRange(SV).print(OS); 12468 } 12469 12470 const Loop *L = LI.getLoopFor(I.getParent()); 12471 12472 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12473 if (AtUse != SV) { 12474 OS << " --> "; 12475 AtUse->print(OS); 12476 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12477 OS << " U: "; 12478 SE.getUnsignedRange(AtUse).print(OS); 12479 OS << " S: "; 12480 SE.getSignedRange(AtUse).print(OS); 12481 } 12482 } 12483 12484 if (L) { 12485 OS << "\t\t" "Exits: "; 12486 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12487 if (!SE.isLoopInvariant(ExitValue, L)) { 12488 OS << "<<Unknown>>"; 12489 } else { 12490 OS << *ExitValue; 12491 } 12492 12493 bool First = true; 12494 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12495 if (First) { 12496 OS << "\t\t" "LoopDispositions: { "; 12497 First = false; 12498 } else { 12499 OS << ", "; 12500 } 12501 12502 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12503 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12504 } 12505 12506 for (auto *InnerL : depth_first(L)) { 12507 if (InnerL == L) 12508 continue; 12509 if (First) { 12510 OS << "\t\t" "LoopDispositions: { "; 12511 First = false; 12512 } else { 12513 OS << ", "; 12514 } 12515 12516 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12517 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12518 } 12519 12520 OS << " }"; 12521 } 12522 12523 OS << "\n"; 12524 } 12525 } 12526 12527 OS << "Determining loop execution counts for: "; 12528 F.printAsOperand(OS, /*PrintType=*/false); 12529 OS << "\n"; 12530 for (Loop *I : LI) 12531 PrintLoopInfo(OS, &SE, I); 12532 } 12533 12534 ScalarEvolution::LoopDisposition 12535 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12536 auto &Values = LoopDispositions[S]; 12537 for (auto &V : Values) { 12538 if (V.getPointer() == L) 12539 return V.getInt(); 12540 } 12541 Values.emplace_back(L, LoopVariant); 12542 LoopDisposition D = computeLoopDisposition(S, L); 12543 auto &Values2 = LoopDispositions[S]; 12544 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12545 if (V.getPointer() == L) { 12546 V.setInt(D); 12547 break; 12548 } 12549 } 12550 return D; 12551 } 12552 12553 ScalarEvolution::LoopDisposition 12554 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12555 switch (S->getSCEVType()) { 12556 case scConstant: 12557 return LoopInvariant; 12558 case scPtrToInt: 12559 case scTruncate: 12560 case scZeroExtend: 12561 case scSignExtend: 12562 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12563 case scAddRecExpr: { 12564 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12565 12566 // If L is the addrec's loop, it's computable. 12567 if (AR->getLoop() == L) 12568 return LoopComputable; 12569 12570 // Add recurrences are never invariant in the function-body (null loop). 12571 if (!L) 12572 return LoopVariant; 12573 12574 // Everything that is not defined at loop entry is variant. 12575 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12576 return LoopVariant; 12577 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12578 " dominate the contained loop's header?"); 12579 12580 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12581 if (AR->getLoop()->contains(L)) 12582 return LoopInvariant; 12583 12584 // This recurrence is variant w.r.t. L if any of its operands 12585 // are variant. 12586 for (auto *Op : AR->operands()) 12587 if (!isLoopInvariant(Op, L)) 12588 return LoopVariant; 12589 12590 // Otherwise it's loop-invariant. 12591 return LoopInvariant; 12592 } 12593 case scAddExpr: 12594 case scMulExpr: 12595 case scUMaxExpr: 12596 case scSMaxExpr: 12597 case scUMinExpr: 12598 case scSMinExpr: { 12599 bool HasVarying = false; 12600 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12601 LoopDisposition D = getLoopDisposition(Op, L); 12602 if (D == LoopVariant) 12603 return LoopVariant; 12604 if (D == LoopComputable) 12605 HasVarying = true; 12606 } 12607 return HasVarying ? LoopComputable : LoopInvariant; 12608 } 12609 case scUDivExpr: { 12610 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12611 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12612 if (LD == LoopVariant) 12613 return LoopVariant; 12614 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12615 if (RD == LoopVariant) 12616 return LoopVariant; 12617 return (LD == LoopInvariant && RD == LoopInvariant) ? 12618 LoopInvariant : LoopComputable; 12619 } 12620 case scUnknown: 12621 // All non-instruction values are loop invariant. All instructions are loop 12622 // invariant if they are not contained in the specified loop. 12623 // Instructions are never considered invariant in the function body 12624 // (null loop) because they are defined within the "loop". 12625 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12626 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12627 return LoopInvariant; 12628 case scCouldNotCompute: 12629 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12630 } 12631 llvm_unreachable("Unknown SCEV kind!"); 12632 } 12633 12634 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12635 return getLoopDisposition(S, L) == LoopInvariant; 12636 } 12637 12638 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12639 return getLoopDisposition(S, L) == LoopComputable; 12640 } 12641 12642 ScalarEvolution::BlockDisposition 12643 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12644 auto &Values = BlockDispositions[S]; 12645 for (auto &V : Values) { 12646 if (V.getPointer() == BB) 12647 return V.getInt(); 12648 } 12649 Values.emplace_back(BB, DoesNotDominateBlock); 12650 BlockDisposition D = computeBlockDisposition(S, BB); 12651 auto &Values2 = BlockDispositions[S]; 12652 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12653 if (V.getPointer() == BB) { 12654 V.setInt(D); 12655 break; 12656 } 12657 } 12658 return D; 12659 } 12660 12661 ScalarEvolution::BlockDisposition 12662 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12663 switch (S->getSCEVType()) { 12664 case scConstant: 12665 return ProperlyDominatesBlock; 12666 case scPtrToInt: 12667 case scTruncate: 12668 case scZeroExtend: 12669 case scSignExtend: 12670 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12671 case scAddRecExpr: { 12672 // This uses a "dominates" query instead of "properly dominates" query 12673 // to test for proper dominance too, because the instruction which 12674 // produces the addrec's value is a PHI, and a PHI effectively properly 12675 // dominates its entire containing block. 12676 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12677 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12678 return DoesNotDominateBlock; 12679 12680 // Fall through into SCEVNAryExpr handling. 12681 LLVM_FALLTHROUGH; 12682 } 12683 case scAddExpr: 12684 case scMulExpr: 12685 case scUMaxExpr: 12686 case scSMaxExpr: 12687 case scUMinExpr: 12688 case scSMinExpr: { 12689 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12690 bool Proper = true; 12691 for (const SCEV *NAryOp : NAry->operands()) { 12692 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12693 if (D == DoesNotDominateBlock) 12694 return DoesNotDominateBlock; 12695 if (D == DominatesBlock) 12696 Proper = false; 12697 } 12698 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12699 } 12700 case scUDivExpr: { 12701 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12702 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12703 BlockDisposition LD = getBlockDisposition(LHS, BB); 12704 if (LD == DoesNotDominateBlock) 12705 return DoesNotDominateBlock; 12706 BlockDisposition RD = getBlockDisposition(RHS, BB); 12707 if (RD == DoesNotDominateBlock) 12708 return DoesNotDominateBlock; 12709 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12710 ProperlyDominatesBlock : DominatesBlock; 12711 } 12712 case scUnknown: 12713 if (Instruction *I = 12714 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12715 if (I->getParent() == BB) 12716 return DominatesBlock; 12717 if (DT.properlyDominates(I->getParent(), BB)) 12718 return ProperlyDominatesBlock; 12719 return DoesNotDominateBlock; 12720 } 12721 return ProperlyDominatesBlock; 12722 case scCouldNotCompute: 12723 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12724 } 12725 llvm_unreachable("Unknown SCEV kind!"); 12726 } 12727 12728 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12729 return getBlockDisposition(S, BB) >= DominatesBlock; 12730 } 12731 12732 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12733 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12734 } 12735 12736 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12737 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12738 } 12739 12740 void 12741 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12742 ValuesAtScopes.erase(S); 12743 LoopDispositions.erase(S); 12744 BlockDispositions.erase(S); 12745 UnsignedRanges.erase(S); 12746 SignedRanges.erase(S); 12747 ExprValueMap.erase(S); 12748 HasRecMap.erase(S); 12749 MinTrailingZerosCache.erase(S); 12750 12751 for (auto I = PredicatedSCEVRewrites.begin(); 12752 I != PredicatedSCEVRewrites.end();) { 12753 std::pair<const SCEV *, const Loop *> Entry = I->first; 12754 if (Entry.first == S) 12755 PredicatedSCEVRewrites.erase(I++); 12756 else 12757 ++I; 12758 } 12759 12760 auto RemoveSCEVFromBackedgeMap = 12761 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12762 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12763 BackedgeTakenInfo &BEInfo = I->second; 12764 if (BEInfo.hasOperand(S)) 12765 Map.erase(I++); 12766 else 12767 ++I; 12768 } 12769 }; 12770 12771 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12772 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12773 } 12774 12775 void 12776 ScalarEvolution::getUsedLoops(const SCEV *S, 12777 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12778 struct FindUsedLoops { 12779 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12780 : LoopsUsed(LoopsUsed) {} 12781 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12782 bool follow(const SCEV *S) { 12783 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12784 LoopsUsed.insert(AR->getLoop()); 12785 return true; 12786 } 12787 12788 bool isDone() const { return false; } 12789 }; 12790 12791 FindUsedLoops F(LoopsUsed); 12792 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12793 } 12794 12795 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12796 SmallPtrSet<const Loop *, 8> LoopsUsed; 12797 getUsedLoops(S, LoopsUsed); 12798 for (auto *L : LoopsUsed) 12799 LoopUsers[L].push_back(S); 12800 } 12801 12802 void ScalarEvolution::verify() const { 12803 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12804 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12805 12806 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12807 12808 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12809 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12810 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12811 12812 const SCEV *visitConstant(const SCEVConstant *Constant) { 12813 return SE.getConstant(Constant->getAPInt()); 12814 } 12815 12816 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12817 return SE.getUnknown(Expr->getValue()); 12818 } 12819 12820 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12821 return SE.getCouldNotCompute(); 12822 } 12823 }; 12824 12825 SCEVMapper SCM(SE2); 12826 12827 while (!LoopStack.empty()) { 12828 auto *L = LoopStack.pop_back_val(); 12829 llvm::append_range(LoopStack, *L); 12830 12831 auto *CurBECount = SCM.visit( 12832 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12833 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12834 12835 if (CurBECount == SE2.getCouldNotCompute() || 12836 NewBECount == SE2.getCouldNotCompute()) { 12837 // NB! This situation is legal, but is very suspicious -- whatever pass 12838 // change the loop to make a trip count go from could not compute to 12839 // computable or vice-versa *should have* invalidated SCEV. However, we 12840 // choose not to assert here (for now) since we don't want false 12841 // positives. 12842 continue; 12843 } 12844 12845 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12846 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12847 // not propagate undef aggressively). This means we can (and do) fail 12848 // verification in cases where a transform makes the trip count of a loop 12849 // go from "undef" to "undef+1" (say). The transform is fine, since in 12850 // both cases the loop iterates "undef" times, but SCEV thinks we 12851 // increased the trip count of the loop by 1 incorrectly. 12852 continue; 12853 } 12854 12855 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12856 SE.getTypeSizeInBits(NewBECount->getType())) 12857 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12858 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12859 SE.getTypeSizeInBits(NewBECount->getType())) 12860 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12861 12862 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12863 12864 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12865 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12866 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12867 dbgs() << "Old: " << *CurBECount << "\n"; 12868 dbgs() << "New: " << *NewBECount << "\n"; 12869 dbgs() << "Delta: " << *Delta << "\n"; 12870 std::abort(); 12871 } 12872 } 12873 12874 // Collect all valid loops currently in LoopInfo. 12875 SmallPtrSet<Loop *, 32> ValidLoops; 12876 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12877 while (!Worklist.empty()) { 12878 Loop *L = Worklist.pop_back_val(); 12879 if (ValidLoops.contains(L)) 12880 continue; 12881 ValidLoops.insert(L); 12882 Worklist.append(L->begin(), L->end()); 12883 } 12884 // Check for SCEV expressions referencing invalid/deleted loops. 12885 for (auto &KV : ValueExprMap) { 12886 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12887 if (!AR) 12888 continue; 12889 assert(ValidLoops.contains(AR->getLoop()) && 12890 "AddRec references invalid loop"); 12891 } 12892 } 12893 12894 bool ScalarEvolution::invalidate( 12895 Function &F, const PreservedAnalyses &PA, 12896 FunctionAnalysisManager::Invalidator &Inv) { 12897 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12898 // of its dependencies is invalidated. 12899 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12900 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12901 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12902 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12903 Inv.invalidate<LoopAnalysis>(F, PA); 12904 } 12905 12906 AnalysisKey ScalarEvolutionAnalysis::Key; 12907 12908 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12909 FunctionAnalysisManager &AM) { 12910 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12911 AM.getResult<AssumptionAnalysis>(F), 12912 AM.getResult<DominatorTreeAnalysis>(F), 12913 AM.getResult<LoopAnalysis>(F)); 12914 } 12915 12916 PreservedAnalyses 12917 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12918 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12919 return PreservedAnalyses::all(); 12920 } 12921 12922 PreservedAnalyses 12923 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12924 // For compatibility with opt's -analyze feature under legacy pass manager 12925 // which was not ported to NPM. This keeps tests using 12926 // update_analyze_test_checks.py working. 12927 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12928 << F.getName() << "':\n"; 12929 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12930 return PreservedAnalyses::all(); 12931 } 12932 12933 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12934 "Scalar Evolution Analysis", false, true) 12935 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12936 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12937 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12938 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12939 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12940 "Scalar Evolution Analysis", false, true) 12941 12942 char ScalarEvolutionWrapperPass::ID = 0; 12943 12944 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12945 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12946 } 12947 12948 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12949 SE.reset(new ScalarEvolution( 12950 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12951 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12952 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12953 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12954 return false; 12955 } 12956 12957 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12958 12959 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12960 SE->print(OS); 12961 } 12962 12963 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12964 if (!VerifySCEV) 12965 return; 12966 12967 SE->verify(); 12968 } 12969 12970 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12971 AU.setPreservesAll(); 12972 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12973 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12974 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12975 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12976 } 12977 12978 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12979 const SCEV *RHS) { 12980 FoldingSetNodeID ID; 12981 assert(LHS->getType() == RHS->getType() && 12982 "Type mismatch between LHS and RHS"); 12983 // Unique this node based on the arguments 12984 ID.AddInteger(SCEVPredicate::P_Equal); 12985 ID.AddPointer(LHS); 12986 ID.AddPointer(RHS); 12987 void *IP = nullptr; 12988 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12989 return S; 12990 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12991 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12992 UniquePreds.InsertNode(Eq, IP); 12993 return Eq; 12994 } 12995 12996 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12997 const SCEVAddRecExpr *AR, 12998 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12999 FoldingSetNodeID ID; 13000 // Unique this node based on the arguments 13001 ID.AddInteger(SCEVPredicate::P_Wrap); 13002 ID.AddPointer(AR); 13003 ID.AddInteger(AddedFlags); 13004 void *IP = nullptr; 13005 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13006 return S; 13007 auto *OF = new (SCEVAllocator) 13008 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13009 UniquePreds.InsertNode(OF, IP); 13010 return OF; 13011 } 13012 13013 namespace { 13014 13015 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13016 public: 13017 13018 /// Rewrites \p S in the context of a loop L and the SCEV predication 13019 /// infrastructure. 13020 /// 13021 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13022 /// equivalences present in \p Pred. 13023 /// 13024 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13025 /// \p NewPreds such that the result will be an AddRecExpr. 13026 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13027 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13028 SCEVUnionPredicate *Pred) { 13029 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13030 return Rewriter.visit(S); 13031 } 13032 13033 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13034 if (Pred) { 13035 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13036 for (auto *Pred : ExprPreds) 13037 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13038 if (IPred->getLHS() == Expr) 13039 return IPred->getRHS(); 13040 } 13041 return convertToAddRecWithPreds(Expr); 13042 } 13043 13044 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13045 const SCEV *Operand = visit(Expr->getOperand()); 13046 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13047 if (AR && AR->getLoop() == L && AR->isAffine()) { 13048 // This couldn't be folded because the operand didn't have the nuw 13049 // flag. Add the nusw flag as an assumption that we could make. 13050 const SCEV *Step = AR->getStepRecurrence(SE); 13051 Type *Ty = Expr->getType(); 13052 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13053 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13054 SE.getSignExtendExpr(Step, Ty), L, 13055 AR->getNoWrapFlags()); 13056 } 13057 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13058 } 13059 13060 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13061 const SCEV *Operand = visit(Expr->getOperand()); 13062 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13063 if (AR && AR->getLoop() == L && AR->isAffine()) { 13064 // This couldn't be folded because the operand didn't have the nsw 13065 // flag. Add the nssw flag as an assumption that we could make. 13066 const SCEV *Step = AR->getStepRecurrence(SE); 13067 Type *Ty = Expr->getType(); 13068 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13069 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13070 SE.getSignExtendExpr(Step, Ty), L, 13071 AR->getNoWrapFlags()); 13072 } 13073 return SE.getSignExtendExpr(Operand, Expr->getType()); 13074 } 13075 13076 private: 13077 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13078 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13079 SCEVUnionPredicate *Pred) 13080 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13081 13082 bool addOverflowAssumption(const SCEVPredicate *P) { 13083 if (!NewPreds) { 13084 // Check if we've already made this assumption. 13085 return Pred && Pred->implies(P); 13086 } 13087 NewPreds->insert(P); 13088 return true; 13089 } 13090 13091 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13092 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13093 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13094 return addOverflowAssumption(A); 13095 } 13096 13097 // If \p Expr represents a PHINode, we try to see if it can be represented 13098 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13099 // to add this predicate as a runtime overflow check, we return the AddRec. 13100 // If \p Expr does not meet these conditions (is not a PHI node, or we 13101 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13102 // return \p Expr. 13103 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13104 if (!isa<PHINode>(Expr->getValue())) 13105 return Expr; 13106 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13107 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13108 if (!PredicatedRewrite) 13109 return Expr; 13110 for (auto *P : PredicatedRewrite->second){ 13111 // Wrap predicates from outer loops are not supported. 13112 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13113 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13114 if (L != AR->getLoop()) 13115 return Expr; 13116 } 13117 if (!addOverflowAssumption(P)) 13118 return Expr; 13119 } 13120 return PredicatedRewrite->first; 13121 } 13122 13123 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13124 SCEVUnionPredicate *Pred; 13125 const Loop *L; 13126 }; 13127 13128 } // end anonymous namespace 13129 13130 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13131 SCEVUnionPredicate &Preds) { 13132 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13133 } 13134 13135 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13136 const SCEV *S, const Loop *L, 13137 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13138 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13139 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13140 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13141 13142 if (!AddRec) 13143 return nullptr; 13144 13145 // Since the transformation was successful, we can now transfer the SCEV 13146 // predicates. 13147 for (auto *P : TransformPreds) 13148 Preds.insert(P); 13149 13150 return AddRec; 13151 } 13152 13153 /// SCEV predicates 13154 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13155 SCEVPredicateKind Kind) 13156 : FastID(ID), Kind(Kind) {} 13157 13158 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13159 const SCEV *LHS, const SCEV *RHS) 13160 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13161 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13162 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13163 } 13164 13165 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13166 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13167 13168 if (!Op) 13169 return false; 13170 13171 return Op->LHS == LHS && Op->RHS == RHS; 13172 } 13173 13174 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13175 13176 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13177 13178 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13179 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13180 } 13181 13182 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13183 const SCEVAddRecExpr *AR, 13184 IncrementWrapFlags Flags) 13185 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13186 13187 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13188 13189 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13190 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13191 13192 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13193 } 13194 13195 bool SCEVWrapPredicate::isAlwaysTrue() const { 13196 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13197 IncrementWrapFlags IFlags = Flags; 13198 13199 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13200 IFlags = clearFlags(IFlags, IncrementNSSW); 13201 13202 return IFlags == IncrementAnyWrap; 13203 } 13204 13205 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13206 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13207 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13208 OS << "<nusw>"; 13209 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13210 OS << "<nssw>"; 13211 OS << "\n"; 13212 } 13213 13214 SCEVWrapPredicate::IncrementWrapFlags 13215 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13216 ScalarEvolution &SE) { 13217 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13218 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13219 13220 // We can safely transfer the NSW flag as NSSW. 13221 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13222 ImpliedFlags = IncrementNSSW; 13223 13224 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13225 // If the increment is positive, the SCEV NUW flag will also imply the 13226 // WrapPredicate NUSW flag. 13227 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13228 if (Step->getValue()->getValue().isNonNegative()) 13229 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13230 } 13231 13232 return ImpliedFlags; 13233 } 13234 13235 /// Union predicates don't get cached so create a dummy set ID for it. 13236 SCEVUnionPredicate::SCEVUnionPredicate() 13237 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13238 13239 bool SCEVUnionPredicate::isAlwaysTrue() const { 13240 return all_of(Preds, 13241 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13242 } 13243 13244 ArrayRef<const SCEVPredicate *> 13245 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13246 auto I = SCEVToPreds.find(Expr); 13247 if (I == SCEVToPreds.end()) 13248 return ArrayRef<const SCEVPredicate *>(); 13249 return I->second; 13250 } 13251 13252 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13253 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13254 return all_of(Set->Preds, 13255 [this](const SCEVPredicate *I) { return this->implies(I); }); 13256 13257 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13258 if (ScevPredsIt == SCEVToPreds.end()) 13259 return false; 13260 auto &SCEVPreds = ScevPredsIt->second; 13261 13262 return any_of(SCEVPreds, 13263 [N](const SCEVPredicate *I) { return I->implies(N); }); 13264 } 13265 13266 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13267 13268 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13269 for (auto Pred : Preds) 13270 Pred->print(OS, Depth); 13271 } 13272 13273 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13274 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13275 for (auto Pred : Set->Preds) 13276 add(Pred); 13277 return; 13278 } 13279 13280 if (implies(N)) 13281 return; 13282 13283 const SCEV *Key = N->getExpr(); 13284 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13285 " associated expression!"); 13286 13287 SCEVToPreds[Key].push_back(N); 13288 Preds.push_back(N); 13289 } 13290 13291 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13292 Loop &L) 13293 : SE(SE), L(L) {} 13294 13295 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13296 const SCEV *Expr = SE.getSCEV(V); 13297 RewriteEntry &Entry = RewriteMap[Expr]; 13298 13299 // If we already have an entry and the version matches, return it. 13300 if (Entry.second && Generation == Entry.first) 13301 return Entry.second; 13302 13303 // We found an entry but it's stale. Rewrite the stale entry 13304 // according to the current predicate. 13305 if (Entry.second) 13306 Expr = Entry.second; 13307 13308 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13309 Entry = {Generation, NewSCEV}; 13310 13311 return NewSCEV; 13312 } 13313 13314 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13315 if (!BackedgeCount) { 13316 SCEVUnionPredicate BackedgePred; 13317 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13318 addPredicate(BackedgePred); 13319 } 13320 return BackedgeCount; 13321 } 13322 13323 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13324 if (Preds.implies(&Pred)) 13325 return; 13326 Preds.add(&Pred); 13327 updateGeneration(); 13328 } 13329 13330 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13331 return Preds; 13332 } 13333 13334 void PredicatedScalarEvolution::updateGeneration() { 13335 // If the generation number wrapped recompute everything. 13336 if (++Generation == 0) { 13337 for (auto &II : RewriteMap) { 13338 const SCEV *Rewritten = II.second.second; 13339 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13340 } 13341 } 13342 } 13343 13344 void PredicatedScalarEvolution::setNoOverflow( 13345 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13346 const SCEV *Expr = getSCEV(V); 13347 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13348 13349 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13350 13351 // Clear the statically implied flags. 13352 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13353 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13354 13355 auto II = FlagsMap.insert({V, Flags}); 13356 if (!II.second) 13357 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13358 } 13359 13360 bool PredicatedScalarEvolution::hasNoOverflow( 13361 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13362 const SCEV *Expr = getSCEV(V); 13363 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13364 13365 Flags = SCEVWrapPredicate::clearFlags( 13366 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13367 13368 auto II = FlagsMap.find(V); 13369 13370 if (II != FlagsMap.end()) 13371 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13372 13373 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13374 } 13375 13376 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13377 const SCEV *Expr = this->getSCEV(V); 13378 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13379 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13380 13381 if (!New) 13382 return nullptr; 13383 13384 for (auto *P : NewPreds) 13385 Preds.add(P); 13386 13387 updateGeneration(); 13388 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13389 return New; 13390 } 13391 13392 PredicatedScalarEvolution::PredicatedScalarEvolution( 13393 const PredicatedScalarEvolution &Init) 13394 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13395 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13396 for (auto I : Init.FlagsMap) 13397 FlagsMap.insert(I); 13398 } 13399 13400 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13401 // For each block. 13402 for (auto *BB : L.getBlocks()) 13403 for (auto &I : *BB) { 13404 if (!SE.isSCEVable(I.getType())) 13405 continue; 13406 13407 auto *Expr = SE.getSCEV(&I); 13408 auto II = RewriteMap.find(Expr); 13409 13410 if (II == RewriteMap.end()) 13411 continue; 13412 13413 // Don't print things that are not interesting. 13414 if (II->second.second == Expr) 13415 continue; 13416 13417 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13418 OS.indent(Depth + 2) << *Expr << "\n"; 13419 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13420 } 13421 } 13422 13423 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13424 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13425 // for URem with constant power-of-2 second operands. 13426 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13427 // 4, A / B becomes X / 8). 13428 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13429 const SCEV *&RHS) { 13430 // Try to match 'zext (trunc A to iB) to iY', which is used 13431 // for URem with constant power-of-2 second operands. Make sure the size of 13432 // the operand A matches the size of the whole expressions. 13433 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13434 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13435 LHS = Trunc->getOperand(); 13436 // Bail out if the type of the LHS is larger than the type of the 13437 // expression for now. 13438 if (getTypeSizeInBits(LHS->getType()) > 13439 getTypeSizeInBits(Expr->getType())) 13440 return false; 13441 if (LHS->getType() != Expr->getType()) 13442 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13443 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13444 << getTypeSizeInBits(Trunc->getType())); 13445 return true; 13446 } 13447 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13448 if (Add == nullptr || Add->getNumOperands() != 2) 13449 return false; 13450 13451 const SCEV *A = Add->getOperand(1); 13452 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13453 13454 if (Mul == nullptr) 13455 return false; 13456 13457 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13458 // (SomeExpr + (-(SomeExpr / B) * B)). 13459 if (Expr == getURemExpr(A, B)) { 13460 LHS = A; 13461 RHS = B; 13462 return true; 13463 } 13464 return false; 13465 }; 13466 13467 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13468 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13469 return MatchURemWithDivisor(Mul->getOperand(1)) || 13470 MatchURemWithDivisor(Mul->getOperand(2)); 13471 13472 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13473 if (Mul->getNumOperands() == 2) 13474 return MatchURemWithDivisor(Mul->getOperand(1)) || 13475 MatchURemWithDivisor(Mul->getOperand(0)) || 13476 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13477 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13478 return false; 13479 } 13480 13481 const SCEV * 13482 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13483 SmallVector<BasicBlock*, 16> ExitingBlocks; 13484 L->getExitingBlocks(ExitingBlocks); 13485 13486 // Form an expression for the maximum exit count possible for this loop. We 13487 // merge the max and exact information to approximate a version of 13488 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13489 SmallVector<const SCEV*, 4> ExitCounts; 13490 for (BasicBlock *ExitingBB : ExitingBlocks) { 13491 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13492 if (isa<SCEVCouldNotCompute>(ExitCount)) 13493 ExitCount = getExitCount(L, ExitingBB, 13494 ScalarEvolution::ConstantMaximum); 13495 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13496 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13497 "We should only have known counts for exiting blocks that " 13498 "dominate latch!"); 13499 ExitCounts.push_back(ExitCount); 13500 } 13501 } 13502 if (ExitCounts.empty()) 13503 return getCouldNotCompute(); 13504 return getUMinFromMismatchedTypes(ExitCounts); 13505 } 13506 13507 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13508 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13509 /// we cannot guarantee that the replacement is loop invariant in the loop of 13510 /// the AddRec. 13511 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13512 ValueToSCEVMapTy ⤅ 13513 13514 public: 13515 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13516 : SCEVRewriteVisitor(SE), Map(M) {} 13517 13518 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13519 13520 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13521 auto I = Map.find(Expr->getValue()); 13522 if (I == Map.end()) 13523 return Expr; 13524 return I->second; 13525 } 13526 }; 13527 13528 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13529 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13530 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13531 // WARNING: It is generally unsound to apply any wrap flags to the proposed 13532 // replacement SCEV which isn't directly implied by the structure of that 13533 // SCEV. In particular, using contextual facts to imply flags is *NOT* 13534 // legal. See the scoping rules for flags in the header to understand why. 13535 13536 // If we have LHS == 0, check if LHS is computing a property of some unknown 13537 // SCEV %v which we can rewrite %v to express explicitly. 13538 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13539 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13540 RHSC->getValue()->isNullValue()) { 13541 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13542 // explicitly express that. 13543 const SCEV *URemLHS = nullptr; 13544 const SCEV *URemRHS = nullptr; 13545 if (matchURem(LHS, URemLHS, URemRHS)) { 13546 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13547 Value *V = LHSUnknown->getValue(); 13548 RewriteMap[V] = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 13549 return; 13550 } 13551 } 13552 } 13553 13554 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 13555 std::swap(LHS, RHS); 13556 Predicate = CmpInst::getSwappedPredicate(Predicate); 13557 } 13558 13559 // Check for a condition of the form (-C1 + X < C2). InstCombine will 13560 // create this form when combining two checks of the form (X u< C2 + C1) and 13561 // (X >=u C1). 13562 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap]() { 13563 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 13564 if (!AddExpr || AddExpr->getNumOperands() != 2) 13565 return false; 13566 13567 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 13568 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 13569 auto *C2 = dyn_cast<SCEVConstant>(RHS); 13570 if (!C1 || !C2 || !LHSUnknown) 13571 return false; 13572 13573 auto ExactRegion = 13574 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 13575 .sub(C1->getAPInt()); 13576 13577 // Bail out, unless we have a non-wrapping, monotonic range. 13578 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 13579 return false; 13580 auto I = RewriteMap.find(LHSUnknown->getValue()); 13581 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 13582 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr( 13583 getConstant(ExactRegion.getUnsignedMin()), 13584 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 13585 return true; 13586 }; 13587 if (MatchRangeCheckIdiom()) 13588 return; 13589 13590 // For now, limit to conditions that provide information about unknown 13591 // expressions. RHS also cannot contain add recurrences. 13592 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13593 if (!LHSUnknown || containsAddRecurrence(RHS)) 13594 return; 13595 13596 // Check whether LHS has already been rewritten. In that case we want to 13597 // chain further rewrites onto the already rewritten value. 13598 auto I = RewriteMap.find(LHSUnknown->getValue()); 13599 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13600 const SCEV *RewrittenRHS = nullptr; 13601 switch (Predicate) { 13602 case CmpInst::ICMP_ULT: 13603 RewrittenRHS = 13604 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13605 break; 13606 case CmpInst::ICMP_SLT: 13607 RewrittenRHS = 13608 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13609 break; 13610 case CmpInst::ICMP_ULE: 13611 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 13612 break; 13613 case CmpInst::ICMP_SLE: 13614 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 13615 break; 13616 case CmpInst::ICMP_UGT: 13617 RewrittenRHS = 13618 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13619 break; 13620 case CmpInst::ICMP_SGT: 13621 RewrittenRHS = 13622 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13623 break; 13624 case CmpInst::ICMP_UGE: 13625 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 13626 break; 13627 case CmpInst::ICMP_SGE: 13628 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 13629 break; 13630 case CmpInst::ICMP_EQ: 13631 if (isa<SCEVConstant>(RHS)) 13632 RewrittenRHS = RHS; 13633 break; 13634 case CmpInst::ICMP_NE: 13635 if (isa<SCEVConstant>(RHS) && 13636 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13637 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13638 break; 13639 default: 13640 break; 13641 } 13642 13643 if (RewrittenRHS) 13644 RewriteMap[LHSUnknown->getValue()] = RewrittenRHS; 13645 }; 13646 // Starting at the loop predecessor, climb up the predecessor chain, as long 13647 // as there are predecessors that can be found that have unique successors 13648 // leading to the original header. 13649 // TODO: share this logic with isLoopEntryGuardedByCond. 13650 ValueToSCEVMapTy RewriteMap; 13651 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13652 L->getLoopPredecessor(), L->getHeader()); 13653 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13654 13655 const BranchInst *LoopEntryPredicate = 13656 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13657 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13658 continue; 13659 13660 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13661 SmallVector<Value *, 8> Worklist; 13662 SmallPtrSet<Value *, 8> Visited; 13663 Worklist.push_back(LoopEntryPredicate->getCondition()); 13664 while (!Worklist.empty()) { 13665 Value *Cond = Worklist.pop_back_val(); 13666 if (!Visited.insert(Cond).second) 13667 continue; 13668 13669 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13670 auto Predicate = 13671 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13672 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13673 getSCEV(Cmp->getOperand(1)), RewriteMap); 13674 continue; 13675 } 13676 13677 Value *L, *R; 13678 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13679 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13680 Worklist.push_back(L); 13681 Worklist.push_back(R); 13682 } 13683 } 13684 } 13685 13686 // Also collect information from assumptions dominating the loop. 13687 for (auto &AssumeVH : AC.assumptions()) { 13688 if (!AssumeVH) 13689 continue; 13690 auto *AssumeI = cast<CallInst>(AssumeVH); 13691 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13692 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13693 continue; 13694 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13695 getSCEV(Cmp->getOperand(1)), RewriteMap); 13696 } 13697 13698 if (RewriteMap.empty()) 13699 return Expr; 13700 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13701 return Rewriter.visit(Expr); 13702 } 13703