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 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 static cl::opt<bool> UseExpensiveRangeSharpening( 230 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 231 cl::init(false), 232 cl::desc("Use more powerful methods of sharpening expression ranges. May " 233 "be costly in terms of compile time")); 234 235 //===----------------------------------------------------------------------===// 236 // SCEV class definitions 237 //===----------------------------------------------------------------------===// 238 239 //===----------------------------------------------------------------------===// 240 // Implementation of the SCEV class. 241 // 242 243 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 244 LLVM_DUMP_METHOD void SCEV::dump() const { 245 print(dbgs()); 246 dbgs() << '\n'; 247 } 248 #endif 249 250 void SCEV::print(raw_ostream &OS) const { 251 switch (getSCEVType()) { 252 case scConstant: 253 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 254 return; 255 case scPtrToInt: { 256 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 257 const SCEV *Op = PtrToInt->getOperand(); 258 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 259 << *PtrToInt->getType() << ")"; 260 return; 261 } 262 case scTruncate: { 263 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 264 const SCEV *Op = Trunc->getOperand(); 265 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 266 << *Trunc->getType() << ")"; 267 return; 268 } 269 case scZeroExtend: { 270 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 271 const SCEV *Op = ZExt->getOperand(); 272 OS << "(zext " << *Op->getType() << " " << *Op << " to " 273 << *ZExt->getType() << ")"; 274 return; 275 } 276 case scSignExtend: { 277 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 278 const SCEV *Op = SExt->getOperand(); 279 OS << "(sext " << *Op->getType() << " " << *Op << " to " 280 << *SExt->getType() << ")"; 281 return; 282 } 283 case scAddRecExpr: { 284 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 285 OS << "{" << *AR->getOperand(0); 286 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 287 OS << ",+," << *AR->getOperand(i); 288 OS << "}<"; 289 if (AR->hasNoUnsignedWrap()) 290 OS << "nuw><"; 291 if (AR->hasNoSignedWrap()) 292 OS << "nsw><"; 293 if (AR->hasNoSelfWrap() && 294 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 295 OS << "nw><"; 296 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 297 OS << ">"; 298 return; 299 } 300 case scAddExpr: 301 case scMulExpr: 302 case scUMaxExpr: 303 case scSMaxExpr: 304 case scUMinExpr: 305 case scSMinExpr: { 306 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 307 const char *OpStr = nullptr; 308 switch (NAry->getSCEVType()) { 309 case scAddExpr: OpStr = " + "; break; 310 case scMulExpr: OpStr = " * "; break; 311 case scUMaxExpr: OpStr = " umax "; break; 312 case scSMaxExpr: OpStr = " smax "; break; 313 case scUMinExpr: 314 OpStr = " umin "; 315 break; 316 case scSMinExpr: 317 OpStr = " smin "; 318 break; 319 default: 320 llvm_unreachable("There are no other nary expression types."); 321 } 322 OS << "("; 323 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 324 I != E; ++I) { 325 OS << **I; 326 if (std::next(I) != E) 327 OS << OpStr; 328 } 329 OS << ")"; 330 switch (NAry->getSCEVType()) { 331 case scAddExpr: 332 case scMulExpr: 333 if (NAry->hasNoUnsignedWrap()) 334 OS << "<nuw>"; 335 if (NAry->hasNoSignedWrap()) 336 OS << "<nsw>"; 337 break; 338 default: 339 // Nothing to print for other nary expressions. 340 break; 341 } 342 return; 343 } 344 case scUDivExpr: { 345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 346 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 347 return; 348 } 349 case scUnknown: { 350 const SCEVUnknown *U = cast<SCEVUnknown>(this); 351 Type *AllocTy; 352 if (U->isSizeOf(AllocTy)) { 353 OS << "sizeof(" << *AllocTy << ")"; 354 return; 355 } 356 if (U->isAlignOf(AllocTy)) { 357 OS << "alignof(" << *AllocTy << ")"; 358 return; 359 } 360 361 Type *CTy; 362 Constant *FieldNo; 363 if (U->isOffsetOf(CTy, FieldNo)) { 364 OS << "offsetof(" << *CTy << ", "; 365 FieldNo->printAsOperand(OS, false); 366 OS << ")"; 367 return; 368 } 369 370 // Otherwise just print it normally. 371 U->getValue()->printAsOperand(OS, false); 372 return; 373 } 374 case scCouldNotCompute: 375 OS << "***COULDNOTCOMPUTE***"; 376 return; 377 } 378 llvm_unreachable("Unknown SCEV kind!"); 379 } 380 381 Type *SCEV::getType() const { 382 switch (getSCEVType()) { 383 case scConstant: 384 return cast<SCEVConstant>(this)->getType(); 385 case scPtrToInt: 386 case scTruncate: 387 case scZeroExtend: 388 case scSignExtend: 389 return cast<SCEVCastExpr>(this)->getType(); 390 case scAddRecExpr: 391 case scMulExpr: 392 case scUMaxExpr: 393 case scSMaxExpr: 394 case scUMinExpr: 395 case scSMinExpr: 396 return cast<SCEVNAryExpr>(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<PointerType>(CE->getOperand(0)->getType()) 537 ->getElementType(); 538 return true; 539 } 540 541 return false; 542 } 543 544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 545 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 546 if (VCE->getOpcode() == Instruction::PtrToInt) 547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 548 if (CE->getOpcode() == Instruction::GetElementPtr && 549 CE->getOperand(0)->isNullValue()) { 550 Type *Ty = 551 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 552 if (StructType *STy = dyn_cast<StructType>(Ty)) 553 if (!STy->isPacked() && 554 CE->getNumOperands() == 3 && 555 CE->getOperand(1)->isNullValue()) { 556 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 557 if (CI->isOne() && 558 STy->getNumElements() == 2 && 559 STy->getElementType(0)->isIntegerTy(1)) { 560 AllocTy = STy->getElementType(1); 561 return true; 562 } 563 } 564 } 565 566 return false; 567 } 568 569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 570 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 571 if (VCE->getOpcode() == Instruction::PtrToInt) 572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 573 if (CE->getOpcode() == Instruction::GetElementPtr && 574 CE->getNumOperands() == 3 && 575 CE->getOperand(0)->isNullValue() && 576 CE->getOperand(1)->isNullValue()) { 577 Type *Ty = 578 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 579 // Ignore vector types here so that ScalarEvolutionExpander doesn't 580 // emit getelementptrs that index into vectors. 581 if (Ty->isStructTy() || Ty->isArrayTy()) { 582 CTy = Ty; 583 FieldNo = CE->getOperand(2); 584 return true; 585 } 586 } 587 588 return false; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // SCEV Utilities 593 //===----------------------------------------------------------------------===// 594 595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 597 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 598 /// have been previously deemed to be "equally complex" by this routine. It is 599 /// intended to avoid exponential time complexity in cases like: 600 /// 601 /// %a = f(%x, %y) 602 /// %b = f(%a, %a) 603 /// %c = f(%b, %b) 604 /// 605 /// %d = f(%x, %y) 606 /// %e = f(%d, %d) 607 /// %f = f(%e, %e) 608 /// 609 /// CompareValueComplexity(%f, %c) 610 /// 611 /// Since we do not continue running this routine on expression trees once we 612 /// have seen unequal values, there is no need to track them in the cache. 613 static int 614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 615 const LoopInfo *const LI, Value *LV, Value *RV, 616 unsigned Depth) { 617 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 618 return 0; 619 620 // Order pointer values after integer values. This helps SCEVExpander form 621 // GEPs. 622 bool LIsPointer = LV->getType()->isPointerTy(), 623 RIsPointer = RV->getType()->isPointerTy(); 624 if (LIsPointer != RIsPointer) 625 return (int)LIsPointer - (int)RIsPointer; 626 627 // Compare getValueID values. 628 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 629 if (LID != RID) 630 return (int)LID - (int)RID; 631 632 // Sort arguments by their position. 633 if (const auto *LA = dyn_cast<Argument>(LV)) { 634 const auto *RA = cast<Argument>(RV); 635 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 636 return (int)LArgNo - (int)RArgNo; 637 } 638 639 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 640 const auto *RGV = cast<GlobalValue>(RV); 641 642 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 643 auto LT = GV->getLinkage(); 644 return !(GlobalValue::isPrivateLinkage(LT) || 645 GlobalValue::isInternalLinkage(LT)); 646 }; 647 648 // Use the names to distinguish the two values, but only if the 649 // names are semantically important. 650 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 651 return LGV->getName().compare(RGV->getName()); 652 } 653 654 // For instructions, compare their loop depth, and their operand count. This 655 // is pretty loose. 656 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 657 const auto *RInst = cast<Instruction>(RV); 658 659 // Compare loop depths. 660 const BasicBlock *LParent = LInst->getParent(), 661 *RParent = RInst->getParent(); 662 if (LParent != RParent) { 663 unsigned LDepth = LI->getLoopDepth(LParent), 664 RDepth = LI->getLoopDepth(RParent); 665 if (LDepth != RDepth) 666 return (int)LDepth - (int)RDepth; 667 } 668 669 // Compare the number of operands. 670 unsigned LNumOps = LInst->getNumOperands(), 671 RNumOps = RInst->getNumOperands(); 672 if (LNumOps != RNumOps) 673 return (int)LNumOps - (int)RNumOps; 674 675 for (unsigned Idx : seq(0u, LNumOps)) { 676 int Result = 677 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 678 RInst->getOperand(Idx), Depth + 1); 679 if (Result != 0) 680 return Result; 681 } 682 } 683 684 EqCacheValue.unionSets(LV, RV); 685 return 0; 686 } 687 688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 689 // than RHS, respectively. A three-way result allows recursive comparisons to be 690 // more efficient. 691 static int CompareSCEVComplexity( 692 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 693 EquivalenceClasses<const Value *> &EqCacheValue, 694 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 695 DominatorTree &DT, unsigned Depth = 0) { 696 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 697 if (LHS == RHS) 698 return 0; 699 700 // Primarily, sort the SCEVs by their getSCEVType(). 701 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 702 if (LType != RType) 703 return (int)LType - (int)RType; 704 705 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 706 return 0; 707 // Aside from the getSCEVType() ordering, the particular ordering 708 // isn't very important except that it's beneficial to be consistent, 709 // so that (a + b) and (b + a) don't end up as different expressions. 710 switch (LType) { 711 case scUnknown: { 712 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 713 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 714 715 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 716 RU->getValue(), Depth + 1); 717 if (X == 0) 718 EqCacheSCEV.unionSets(LHS, RHS); 719 return X; 720 } 721 722 case scConstant: { 723 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 724 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 725 726 // Compare constant values. 727 const APInt &LA = LC->getAPInt(); 728 const APInt &RA = RC->getAPInt(); 729 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 730 if (LBitWidth != RBitWidth) 731 return (int)LBitWidth - (int)RBitWidth; 732 return LA.ult(RA) ? -1 : 1; 733 } 734 735 case scAddRecExpr: { 736 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 737 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 738 739 // There is always a dominance between two recs that are used by one SCEV, 740 // so we can safely sort recs by loop header dominance. We require such 741 // order in getAddExpr. 742 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 743 if (LLoop != RLoop) { 744 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 745 assert(LHead != RHead && "Two loops share the same header?"); 746 if (DT.dominates(LHead, RHead)) 747 return 1; 748 else 749 assert(DT.dominates(RHead, LHead) && 750 "No dominance between recurrences used by one SCEV?"); 751 return -1; 752 } 753 754 // Addrec complexity grows with operand count. 755 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 756 if (LNumOps != RNumOps) 757 return (int)LNumOps - (int)RNumOps; 758 759 // Lexicographically compare. 760 for (unsigned i = 0; i != LNumOps; ++i) { 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 762 LA->getOperand(i), RA->getOperand(i), DT, 763 Depth + 1); 764 if (X != 0) 765 return X; 766 } 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return 0; 769 } 770 771 case scAddExpr: 772 case scMulExpr: 773 case scSMaxExpr: 774 case scUMaxExpr: 775 case scSMinExpr: 776 case scUMinExpr: { 777 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 778 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 779 780 // Lexicographically compare n-ary expressions. 781 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 782 if (LNumOps != RNumOps) 783 return (int)LNumOps - (int)RNumOps; 784 785 for (unsigned i = 0; i != LNumOps; ++i) { 786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 787 LC->getOperand(i), RC->getOperand(i), DT, 788 Depth + 1); 789 if (X != 0) 790 return X; 791 } 792 EqCacheSCEV.unionSets(LHS, RHS); 793 return 0; 794 } 795 796 case scUDivExpr: { 797 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 798 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 799 800 // Lexicographically compare udiv expressions. 801 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 802 RC->getLHS(), DT, Depth + 1); 803 if (X != 0) 804 return X; 805 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 806 RC->getRHS(), DT, Depth + 1); 807 if (X == 0) 808 EqCacheSCEV.unionSets(LHS, RHS); 809 return X; 810 } 811 812 case scPtrToInt: 813 case scTruncate: 814 case scZeroExtend: 815 case scSignExtend: { 816 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 817 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 818 819 // Compare cast expressions by operand. 820 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 821 LC->getOperand(), RC->getOperand(), DT, 822 Depth + 1); 823 if (X == 0) 824 EqCacheSCEV.unionSets(LHS, RHS); 825 return X; 826 } 827 828 case scCouldNotCompute: 829 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 830 } 831 llvm_unreachable("Unknown SCEV kind!"); 832 } 833 834 /// Given a list of SCEV objects, order them by their complexity, and group 835 /// objects of the same complexity together by value. When this routine is 836 /// finished, we know that any duplicates in the vector are consecutive and that 837 /// complexity is monotonically increasing. 838 /// 839 /// Note that we go take special precautions to ensure that we get deterministic 840 /// results from this routine. In other words, we don't want the results of 841 /// this to depend on where the addresses of various SCEV objects happened to 842 /// land in memory. 843 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 844 LoopInfo *LI, DominatorTree &DT) { 845 if (Ops.size() < 2) return; // Noop 846 847 EquivalenceClasses<const SCEV *> EqCacheSCEV; 848 EquivalenceClasses<const Value *> EqCacheValue; 849 if (Ops.size() == 2) { 850 // This is the common case, which also happens to be trivially simple. 851 // Special case it. 852 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 853 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 854 std::swap(LHS, RHS); 855 return; 856 } 857 858 // Do the rough sort by complexity. 859 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 860 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 861 0; 862 }); 863 864 // Now that we are sorted by complexity, group elements of the same 865 // complexity. Note that this is, at worst, N^2, but the vector is likely to 866 // be extremely short in practice. Note that we take this approach because we 867 // do not want to depend on the addresses of the objects we are grouping. 868 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 869 const SCEV *S = Ops[i]; 870 unsigned Complexity = S->getSCEVType(); 871 872 // If there are any objects of the same complexity and same value as this 873 // one, group them. 874 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 875 if (Ops[j] == S) { // Found a duplicate. 876 // Move it to immediately after i'th element. 877 std::swap(Ops[i+1], Ops[j]); 878 ++i; // no need to rescan it. 879 if (i == e-2) return; // Done! 880 } 881 } 882 } 883 } 884 885 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 886 /// least HugeExprThreshold nodes). 887 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 888 return any_of(Ops, [](const SCEV *S) { 889 return S->getExpressionSize() >= HugeExprThreshold; 890 }); 891 } 892 893 //===----------------------------------------------------------------------===// 894 // Simple SCEV method implementations 895 //===----------------------------------------------------------------------===// 896 897 /// Compute BC(It, K). The result has width W. Assume, K > 0. 898 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 899 ScalarEvolution &SE, 900 Type *ResultTy) { 901 // Handle the simplest case efficiently. 902 if (K == 1) 903 return SE.getTruncateOrZeroExtend(It, ResultTy); 904 905 // We are using the following formula for BC(It, K): 906 // 907 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 908 // 909 // Suppose, W is the bitwidth of the return value. We must be prepared for 910 // overflow. Hence, we must assure that the result of our computation is 911 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 912 // safe in modular arithmetic. 913 // 914 // However, this code doesn't use exactly that formula; the formula it uses 915 // is something like the following, where T is the number of factors of 2 in 916 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 917 // exponentiation: 918 // 919 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 920 // 921 // This formula is trivially equivalent to the previous formula. However, 922 // this formula can be implemented much more efficiently. The trick is that 923 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 924 // arithmetic. To do exact division in modular arithmetic, all we have 925 // to do is multiply by the inverse. Therefore, this step can be done at 926 // width W. 927 // 928 // The next issue is how to safely do the division by 2^T. The way this 929 // is done is by doing the multiplication step at a width of at least W + T 930 // bits. This way, the bottom W+T bits of the product are accurate. Then, 931 // when we perform the division by 2^T (which is equivalent to a right shift 932 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 933 // truncated out after the division by 2^T. 934 // 935 // In comparison to just directly using the first formula, this technique 936 // is much more efficient; using the first formula requires W * K bits, 937 // but this formula less than W + K bits. Also, the first formula requires 938 // a division step, whereas this formula only requires multiplies and shifts. 939 // 940 // It doesn't matter whether the subtraction step is done in the calculation 941 // width or the input iteration count's width; if the subtraction overflows, 942 // the result must be zero anyway. We prefer here to do it in the width of 943 // the induction variable because it helps a lot for certain cases; CodeGen 944 // isn't smart enough to ignore the overflow, which leads to much less 945 // efficient code if the width of the subtraction is wider than the native 946 // register width. 947 // 948 // (It's possible to not widen at all by pulling out factors of 2 before 949 // the multiplication; for example, K=2 can be calculated as 950 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 951 // extra arithmetic, so it's not an obvious win, and it gets 952 // much more complicated for K > 3.) 953 954 // Protection from insane SCEVs; this bound is conservative, 955 // but it probably doesn't matter. 956 if (K > 1000) 957 return SE.getCouldNotCompute(); 958 959 unsigned W = SE.getTypeSizeInBits(ResultTy); 960 961 // Calculate K! / 2^T and T; we divide out the factors of two before 962 // multiplying for calculating K! / 2^T to avoid overflow. 963 // Other overflow doesn't matter because we only care about the bottom 964 // W bits of the result. 965 APInt OddFactorial(W, 1); 966 unsigned T = 1; 967 for (unsigned i = 3; i <= K; ++i) { 968 APInt Mult(W, i); 969 unsigned TwoFactors = Mult.countTrailingZeros(); 970 T += TwoFactors; 971 Mult.lshrInPlace(TwoFactors); 972 OddFactorial *= Mult; 973 } 974 975 // We need at least W + T bits for the multiplication step 976 unsigned CalculationBits = W + T; 977 978 // Calculate 2^T, at width T+W. 979 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 980 981 // Calculate the multiplicative inverse of K! / 2^T; 982 // this multiplication factor will perform the exact division by 983 // K! / 2^T. 984 APInt Mod = APInt::getSignedMinValue(W+1); 985 APInt MultiplyFactor = OddFactorial.zext(W+1); 986 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 987 MultiplyFactor = MultiplyFactor.trunc(W); 988 989 // Calculate the product, at width T+W 990 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 991 CalculationBits); 992 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 993 for (unsigned i = 1; i != K; ++i) { 994 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 995 Dividend = SE.getMulExpr(Dividend, 996 SE.getTruncateOrZeroExtend(S, CalculationTy)); 997 } 998 999 // Divide by 2^T 1000 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1001 1002 // Truncate the result, and divide by K! / 2^T. 1003 1004 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1005 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1006 } 1007 1008 /// Return the value of this chain of recurrences at the specified iteration 1009 /// number. We can evaluate this recurrence by multiplying each element in the 1010 /// chain by the binomial coefficient corresponding to it. In other words, we 1011 /// can evaluate {A,+,B,+,C,+,D} as: 1012 /// 1013 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1014 /// 1015 /// where BC(It, k) stands for binomial coefficient. 1016 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1017 ScalarEvolution &SE) const { 1018 const SCEV *Result = getStart(); 1019 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1020 // The computation is correct in the face of overflow provided that the 1021 // multiplication is performed _after_ the evaluation of the binomial 1022 // coefficient. 1023 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1024 if (isa<SCEVCouldNotCompute>(Coeff)) 1025 return Coeff; 1026 1027 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1028 } 1029 return Result; 1030 } 1031 1032 //===----------------------------------------------------------------------===// 1033 // SCEV Expression folder implementations 1034 //===----------------------------------------------------------------------===// 1035 1036 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty, 1037 unsigned Depth) { 1038 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1039 assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once."); 1040 1041 // We could be called with an integer-typed operands during SCEV rewrites. 1042 // Since the operand is an integer already, just perform zext/trunc/self cast. 1043 if (!Op->getType()->isPointerTy()) 1044 return getTruncateOrZeroExtend(Op, Ty); 1045 1046 // What would be an ID for such a SCEV cast expression? 1047 FoldingSetNodeID ID; 1048 ID.AddInteger(scPtrToInt); 1049 ID.AddPointer(Op); 1050 1051 void *IP = nullptr; 1052 1053 // Is there already an expression for such a cast? 1054 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1055 return getTruncateOrZeroExtend(S, Ty); 1056 1057 // If not, is this expression something we can't reduce any further? 1058 if (isa<SCEVUnknown>(Op)) { 1059 // Create an explicit cast node. 1060 // We can reuse the existing insert position since if we get here, 1061 // we won't have made any changes which would invalidate it. 1062 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1063 assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( 1064 Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && 1065 "We can only model ptrtoint if SCEV's effective (integer) type is " 1066 "sufficiently wide to represent all possible pointer values."); 1067 SCEV *S = new (SCEVAllocator) 1068 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1069 UniqueSCEVs.InsertNode(S, IP); 1070 addToLoopUseLists(S); 1071 return getTruncateOrZeroExtend(S, Ty); 1072 } 1073 1074 assert(Depth == 0 && 1075 "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's."); 1076 1077 // Otherwise, we've got some expression that is more complex than just a 1078 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1079 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1080 // only, and the expressions must otherwise be integer-typed. 1081 // So sink the cast down to the SCEVUnknown's. 1082 1083 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1084 /// which computes a pointer-typed value, and rewrites the whole expression 1085 /// tree so that *all* the computations are done on integers, and the only 1086 /// pointer-typed operands in the expression are SCEVUnknown. 1087 class SCEVPtrToIntSinkingRewriter 1088 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1089 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1090 1091 public: 1092 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1093 1094 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1095 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1096 return Rewriter.visit(Scev); 1097 } 1098 1099 const SCEV *visit(const SCEV *S) { 1100 Type *STy = S->getType(); 1101 // If the expression is not pointer-typed, just keep it as-is. 1102 if (!STy->isPointerTy()) 1103 return S; 1104 // Else, recursively sink the cast down into it. 1105 return Base::visit(S); 1106 } 1107 1108 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1109 SmallVector<const SCEV *, 2> Operands; 1110 bool Changed = false; 1111 for (auto *Op : Expr->operands()) { 1112 Operands.push_back(visit(Op)); 1113 Changed |= Op != Operands.back(); 1114 } 1115 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1116 } 1117 1118 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1119 SmallVector<const SCEV *, 2> Operands; 1120 bool Changed = false; 1121 for (auto *Op : Expr->operands()) { 1122 Operands.push_back(visit(Op)); 1123 Changed |= Op != Operands.back(); 1124 } 1125 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1126 } 1127 1128 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1129 Type *ExprPtrTy = Expr->getType(); 1130 assert(ExprPtrTy->isPointerTy() && 1131 "Should only reach pointer-typed SCEVUnknown's."); 1132 Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy); 1133 return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1); 1134 } 1135 }; 1136 1137 // And actually perform the cast sinking. 1138 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1139 assert(IntOp->getType()->isIntegerTy() && 1140 "We must have succeeded in sinking the cast, " 1141 "and ending up with an integer-typed expression!"); 1142 return getTruncateOrZeroExtend(IntOp, Ty); 1143 } 1144 1145 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1146 unsigned Depth) { 1147 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1148 "This is not a truncating conversion!"); 1149 assert(isSCEVable(Ty) && 1150 "This is not a conversion to a SCEVable type!"); 1151 Ty = getEffectiveSCEVType(Ty); 1152 1153 FoldingSetNodeID ID; 1154 ID.AddInteger(scTruncate); 1155 ID.AddPointer(Op); 1156 ID.AddPointer(Ty); 1157 void *IP = nullptr; 1158 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1159 1160 // Fold if the operand is constant. 1161 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1162 return getConstant( 1163 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1164 1165 // trunc(trunc(x)) --> trunc(x) 1166 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1167 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1168 1169 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1170 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1171 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1172 1173 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1174 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1175 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1176 1177 if (Depth > MaxCastDepth) { 1178 SCEV *S = 1179 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1180 UniqueSCEVs.InsertNode(S, IP); 1181 addToLoopUseLists(S); 1182 return S; 1183 } 1184 1185 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1186 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1187 // if after transforming we have at most one truncate, not counting truncates 1188 // that replace other casts. 1189 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1190 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1191 SmallVector<const SCEV *, 4> Operands; 1192 unsigned numTruncs = 0; 1193 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1194 ++i) { 1195 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1196 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1197 isa<SCEVTruncateExpr>(S)) 1198 numTruncs++; 1199 Operands.push_back(S); 1200 } 1201 if (numTruncs < 2) { 1202 if (isa<SCEVAddExpr>(Op)) 1203 return getAddExpr(Operands); 1204 else if (isa<SCEVMulExpr>(Op)) 1205 return getMulExpr(Operands); 1206 else 1207 llvm_unreachable("Unexpected SCEV type for Op."); 1208 } 1209 // Although we checked in the beginning that ID is not in the cache, it is 1210 // possible that during recursion and different modification ID was inserted 1211 // into the cache. So if we find it, just return it. 1212 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1213 return S; 1214 } 1215 1216 // If the input value is a chrec scev, truncate the chrec's operands. 1217 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1218 SmallVector<const SCEV *, 4> Operands; 1219 for (const SCEV *Op : AddRec->operands()) 1220 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1221 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1222 } 1223 1224 // The cast wasn't folded; create an explicit cast node. We can reuse 1225 // the existing insert position since if we get here, we won't have 1226 // made any changes which would invalidate it. 1227 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1228 Op, Ty); 1229 UniqueSCEVs.InsertNode(S, IP); 1230 addToLoopUseLists(S); 1231 return S; 1232 } 1233 1234 // Get the limit of a recurrence such that incrementing by Step cannot cause 1235 // signed overflow as long as the value of the recurrence within the 1236 // loop does not exceed this limit before incrementing. 1237 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1238 ICmpInst::Predicate *Pred, 1239 ScalarEvolution *SE) { 1240 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1241 if (SE->isKnownPositive(Step)) { 1242 *Pred = ICmpInst::ICMP_SLT; 1243 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1244 SE->getSignedRangeMax(Step)); 1245 } 1246 if (SE->isKnownNegative(Step)) { 1247 *Pred = ICmpInst::ICMP_SGT; 1248 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1249 SE->getSignedRangeMin(Step)); 1250 } 1251 return nullptr; 1252 } 1253 1254 // Get the limit of a recurrence such that incrementing by Step cannot cause 1255 // unsigned overflow as long as the value of the recurrence within the loop does 1256 // not exceed this limit before incrementing. 1257 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1258 ICmpInst::Predicate *Pred, 1259 ScalarEvolution *SE) { 1260 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1261 *Pred = ICmpInst::ICMP_ULT; 1262 1263 return SE->getConstant(APInt::getMinValue(BitWidth) - 1264 SE->getUnsignedRangeMax(Step)); 1265 } 1266 1267 namespace { 1268 1269 struct ExtendOpTraitsBase { 1270 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1271 unsigned); 1272 }; 1273 1274 // Used to make code generic over signed and unsigned overflow. 1275 template <typename ExtendOp> struct ExtendOpTraits { 1276 // Members present: 1277 // 1278 // static const SCEV::NoWrapFlags WrapType; 1279 // 1280 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1281 // 1282 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1283 // ICmpInst::Predicate *Pred, 1284 // ScalarEvolution *SE); 1285 }; 1286 1287 template <> 1288 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1289 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1290 1291 static const GetExtendExprTy GetExtendExpr; 1292 1293 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1294 ICmpInst::Predicate *Pred, 1295 ScalarEvolution *SE) { 1296 return getSignedOverflowLimitForStep(Step, Pred, SE); 1297 } 1298 }; 1299 1300 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1301 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1302 1303 template <> 1304 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1306 1307 static const GetExtendExprTy GetExtendExpr; 1308 1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1310 ICmpInst::Predicate *Pred, 1311 ScalarEvolution *SE) { 1312 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1313 } 1314 }; 1315 1316 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1317 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1318 1319 } // end anonymous namespace 1320 1321 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1322 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1323 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1324 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1325 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1326 // expression "Step + sext/zext(PreIncAR)" is congruent with 1327 // "sext/zext(PostIncAR)" 1328 template <typename ExtendOpTy> 1329 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1330 ScalarEvolution *SE, unsigned Depth) { 1331 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1332 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1333 1334 const Loop *L = AR->getLoop(); 1335 const SCEV *Start = AR->getStart(); 1336 const SCEV *Step = AR->getStepRecurrence(*SE); 1337 1338 // Check for a simple looking step prior to loop entry. 1339 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1340 if (!SA) 1341 return nullptr; 1342 1343 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1344 // subtraction is expensive. For this purpose, perform a quick and dirty 1345 // difference, by checking for Step in the operand list. 1346 SmallVector<const SCEV *, 4> DiffOps; 1347 for (const SCEV *Op : SA->operands()) 1348 if (Op != Step) 1349 DiffOps.push_back(Op); 1350 1351 if (DiffOps.size() == SA->getNumOperands()) 1352 return nullptr; 1353 1354 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1355 // `Step`: 1356 1357 // 1. NSW/NUW flags on the step increment. 1358 auto PreStartFlags = 1359 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1360 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1361 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1362 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1363 1364 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1365 // "S+X does not sign/unsign-overflow". 1366 // 1367 1368 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1369 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1370 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1371 return PreStart; 1372 1373 // 2. Direct overflow check on the step operation's expression. 1374 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1375 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1376 const SCEV *OperandExtendedStart = 1377 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1378 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1379 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1380 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1381 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1382 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1383 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1384 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1385 } 1386 return PreStart; 1387 } 1388 1389 // 3. Loop precondition. 1390 ICmpInst::Predicate Pred; 1391 const SCEV *OverflowLimit = 1392 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1393 1394 if (OverflowLimit && 1395 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1396 return PreStart; 1397 1398 return nullptr; 1399 } 1400 1401 // Get the normalized zero or sign extended expression for this AddRec's Start. 1402 template <typename ExtendOpTy> 1403 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1404 ScalarEvolution *SE, 1405 unsigned Depth) { 1406 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1407 1408 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1409 if (!PreStart) 1410 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1411 1412 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1413 Depth), 1414 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1415 } 1416 1417 // Try to prove away overflow by looking at "nearby" add recurrences. A 1418 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1419 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1420 // 1421 // Formally: 1422 // 1423 // {S,+,X} == {S-T,+,X} + T 1424 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1425 // 1426 // If ({S-T,+,X} + T) does not overflow ... (1) 1427 // 1428 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1429 // 1430 // If {S-T,+,X} does not overflow ... (2) 1431 // 1432 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1433 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1434 // 1435 // If (S-T)+T does not overflow ... (3) 1436 // 1437 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1438 // == {Ext(S),+,Ext(X)} == LHS 1439 // 1440 // Thus, if (1), (2) and (3) are true for some T, then 1441 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1442 // 1443 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1444 // does not overflow" restricted to the 0th iteration. Therefore we only need 1445 // to check for (1) and (2). 1446 // 1447 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1448 // is `Delta` (defined below). 1449 template <typename ExtendOpTy> 1450 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1451 const SCEV *Step, 1452 const Loop *L) { 1453 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1454 1455 // We restrict `Start` to a constant to prevent SCEV from spending too much 1456 // time here. It is correct (but more expensive) to continue with a 1457 // non-constant `Start` and do a general SCEV subtraction to compute 1458 // `PreStart` below. 1459 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1460 if (!StartC) 1461 return false; 1462 1463 APInt StartAI = StartC->getAPInt(); 1464 1465 for (unsigned Delta : {-2, -1, 1, 2}) { 1466 const SCEV *PreStart = getConstant(StartAI - Delta); 1467 1468 FoldingSetNodeID ID; 1469 ID.AddInteger(scAddRecExpr); 1470 ID.AddPointer(PreStart); 1471 ID.AddPointer(Step); 1472 ID.AddPointer(L); 1473 void *IP = nullptr; 1474 const auto *PreAR = 1475 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1476 1477 // Give up if we don't already have the add recurrence we need because 1478 // actually constructing an add recurrence is relatively expensive. 1479 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1480 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1481 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1482 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1483 DeltaS, &Pred, this); 1484 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1485 return true; 1486 } 1487 } 1488 1489 return false; 1490 } 1491 1492 // Finds an integer D for an expression (C + x + y + ...) such that the top 1493 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1494 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1495 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1496 // the (C + x + y + ...) expression is \p WholeAddExpr. 1497 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1498 const SCEVConstant *ConstantTerm, 1499 const SCEVAddExpr *WholeAddExpr) { 1500 const APInt &C = ConstantTerm->getAPInt(); 1501 const unsigned BitWidth = C.getBitWidth(); 1502 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1503 uint32_t TZ = BitWidth; 1504 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1505 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1506 if (TZ) { 1507 // Set D to be as many least significant bits of C as possible while still 1508 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1509 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1510 } 1511 return APInt(BitWidth, 0); 1512 } 1513 1514 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1515 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1516 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1517 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1518 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1519 const APInt &ConstantStart, 1520 const SCEV *Step) { 1521 const unsigned BitWidth = ConstantStart.getBitWidth(); 1522 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1523 if (TZ) 1524 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1525 : ConstantStart; 1526 return APInt(BitWidth, 0); 1527 } 1528 1529 const SCEV * 1530 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1532 "This is not an extending conversion!"); 1533 assert(isSCEVable(Ty) && 1534 "This is not a conversion to a SCEVable type!"); 1535 Ty = getEffectiveSCEVType(Ty); 1536 1537 // Fold if the operand is constant. 1538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1539 return getConstant( 1540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1541 1542 // zext(zext(x)) --> zext(x) 1543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1544 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1545 1546 // Before doing any expensive analysis, check to see if we've already 1547 // computed a SCEV for this Op and Ty. 1548 FoldingSetNodeID ID; 1549 ID.AddInteger(scZeroExtend); 1550 ID.AddPointer(Op); 1551 ID.AddPointer(Ty); 1552 void *IP = nullptr; 1553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1554 if (Depth > MaxCastDepth) { 1555 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1556 Op, Ty); 1557 UniqueSCEVs.InsertNode(S, IP); 1558 addToLoopUseLists(S); 1559 return S; 1560 } 1561 1562 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1563 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1564 // It's possible the bits taken off by the truncate were all zero bits. If 1565 // so, we should be able to simplify this further. 1566 const SCEV *X = ST->getOperand(); 1567 ConstantRange CR = getUnsignedRange(X); 1568 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1569 unsigned NewBits = getTypeSizeInBits(Ty); 1570 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1571 CR.zextOrTrunc(NewBits))) 1572 return getTruncateOrZeroExtend(X, Ty, Depth); 1573 } 1574 1575 // If the input value is a chrec scev, and we can prove that the value 1576 // did not overflow the old, smaller, value, we can zero extend all of the 1577 // operands (often constants). This allows analysis of something like 1578 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1579 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1580 if (AR->isAffine()) { 1581 const SCEV *Start = AR->getStart(); 1582 const SCEV *Step = AR->getStepRecurrence(*this); 1583 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1584 const Loop *L = AR->getLoop(); 1585 1586 if (!AR->hasNoUnsignedWrap()) { 1587 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1588 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1589 } 1590 1591 // If we have special knowledge that this addrec won't overflow, 1592 // we don't need to do any further analysis. 1593 if (AR->hasNoUnsignedWrap()) 1594 return getAddRecExpr( 1595 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1596 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1597 1598 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1599 // Note that this serves two purposes: It filters out loops that are 1600 // simply not analyzable, and it covers the case where this code is 1601 // being called from within backedge-taken count analysis, such that 1602 // attempting to ask for the backedge-taken count would likely result 1603 // in infinite recursion. In the later case, the analysis code will 1604 // cope with a conservative value, and it will take care to purge 1605 // that value once it has finished. 1606 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1607 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1608 // Manually compute the final value for AR, checking for 1609 // overflow. 1610 1611 // Check whether the backedge-taken count can be losslessly casted to 1612 // the addrec's type. The count is always unsigned. 1613 const SCEV *CastedMaxBECount = 1614 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1615 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1616 CastedMaxBECount, MaxBECount->getType(), Depth); 1617 if (MaxBECount == RecastedMaxBECount) { 1618 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1619 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1620 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1621 SCEV::FlagAnyWrap, Depth + 1); 1622 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1623 SCEV::FlagAnyWrap, 1624 Depth + 1), 1625 WideTy, Depth + 1); 1626 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1627 const SCEV *WideMaxBECount = 1628 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1629 const SCEV *OperandExtendedAdd = 1630 getAddExpr(WideStart, 1631 getMulExpr(WideMaxBECount, 1632 getZeroExtendExpr(Step, WideTy, Depth + 1), 1633 SCEV::FlagAnyWrap, Depth + 1), 1634 SCEV::FlagAnyWrap, Depth + 1); 1635 if (ZAdd == OperandExtendedAdd) { 1636 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1637 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1638 // Return the expression with the addrec on the outside. 1639 return getAddRecExpr( 1640 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1641 Depth + 1), 1642 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1643 AR->getNoWrapFlags()); 1644 } 1645 // Similar to above, only this time treat the step value as signed. 1646 // This covers loops that count down. 1647 OperandExtendedAdd = 1648 getAddExpr(WideStart, 1649 getMulExpr(WideMaxBECount, 1650 getSignExtendExpr(Step, WideTy, Depth + 1), 1651 SCEV::FlagAnyWrap, Depth + 1), 1652 SCEV::FlagAnyWrap, Depth + 1); 1653 if (ZAdd == OperandExtendedAdd) { 1654 // Cache knowledge of AR NW, which is propagated to this AddRec. 1655 // Negative step causes unsigned wrap, but it still can't self-wrap. 1656 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1657 // Return the expression with the addrec on the outside. 1658 return getAddRecExpr( 1659 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1660 Depth + 1), 1661 getSignExtendExpr(Step, Ty, Depth + 1), L, 1662 AR->getNoWrapFlags()); 1663 } 1664 } 1665 } 1666 1667 // Normally, in the cases we can prove no-overflow via a 1668 // backedge guarding condition, we can also compute a backedge 1669 // taken count for the loop. The exceptions are assumptions and 1670 // guards present in the loop -- SCEV is not great at exploiting 1671 // these to compute max backedge taken counts, but can still use 1672 // these to prove lack of overflow. Use this fact to avoid 1673 // doing extra work that may not pay off. 1674 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1675 !AC.assumptions().empty()) { 1676 // If the backedge is guarded by a comparison with the pre-inc 1677 // value the addrec is safe. Also, if the entry is guarded by 1678 // a comparison with the start value and the backedge is 1679 // guarded by a comparison with the post-inc value, the addrec 1680 // is safe. 1681 if (isKnownPositive(Step)) { 1682 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1683 getUnsignedRangeMax(Step)); 1684 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1685 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1686 // Cache knowledge of AR NUW, which is propagated to this 1687 // AddRec. 1688 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1689 // Return the expression with the addrec on the outside. 1690 return getAddRecExpr( 1691 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1692 Depth + 1), 1693 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1694 AR->getNoWrapFlags()); 1695 } 1696 } else if (isKnownNegative(Step)) { 1697 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1698 getSignedRangeMin(Step)); 1699 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1700 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1701 // Cache knowledge of AR NW, which is propagated to this 1702 // AddRec. Negative step causes unsigned wrap, but it 1703 // still can't self-wrap. 1704 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1705 // Return the expression with the addrec on the outside. 1706 return getAddRecExpr( 1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1708 Depth + 1), 1709 getSignExtendExpr(Step, Ty, Depth + 1), L, 1710 AR->getNoWrapFlags()); 1711 } 1712 } 1713 } 1714 1715 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1716 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1717 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1718 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1719 const APInt &C = SC->getAPInt(); 1720 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1721 if (D != 0) { 1722 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1723 const SCEV *SResidual = 1724 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1725 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1726 return getAddExpr(SZExtD, SZExtR, 1727 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1728 Depth + 1); 1729 } 1730 } 1731 1732 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1733 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1734 return getAddRecExpr( 1735 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1736 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1737 } 1738 } 1739 1740 // zext(A % B) --> zext(A) % zext(B) 1741 { 1742 const SCEV *LHS; 1743 const SCEV *RHS; 1744 if (matchURem(Op, LHS, RHS)) 1745 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1746 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1747 } 1748 1749 // zext(A / B) --> zext(A) / zext(B). 1750 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1751 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1752 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1753 1754 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1755 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1756 if (SA->hasNoUnsignedWrap()) { 1757 // If the addition does not unsign overflow then we can, by definition, 1758 // commute the zero extension with the addition operation. 1759 SmallVector<const SCEV *, 4> Ops; 1760 for (const auto *Op : SA->operands()) 1761 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1762 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1763 } 1764 1765 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1766 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1767 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1768 // 1769 // Often address arithmetics contain expressions like 1770 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1771 // This transformation is useful while proving that such expressions are 1772 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1773 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1774 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1775 if (D != 0) { 1776 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1777 const SCEV *SResidual = 1778 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1779 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1780 return getAddExpr(SZExtD, SZExtR, 1781 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1782 Depth + 1); 1783 } 1784 } 1785 } 1786 1787 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1788 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1789 if (SM->hasNoUnsignedWrap()) { 1790 // If the multiply does not unsign overflow then we can, by definition, 1791 // commute the zero extension with the multiply operation. 1792 SmallVector<const SCEV *, 4> Ops; 1793 for (const auto *Op : SM->operands()) 1794 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1795 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1796 } 1797 1798 // zext(2^K * (trunc X to iN)) to iM -> 1799 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1800 // 1801 // Proof: 1802 // 1803 // zext(2^K * (trunc X to iN)) to iM 1804 // = zext((trunc X to iN) << K) to iM 1805 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1806 // (because shl removes the top K bits) 1807 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1808 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1809 // 1810 if (SM->getNumOperands() == 2) 1811 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1812 if (MulLHS->getAPInt().isPowerOf2()) 1813 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1814 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1815 MulLHS->getAPInt().logBase2(); 1816 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1817 return getMulExpr( 1818 getZeroExtendExpr(MulLHS, Ty), 1819 getZeroExtendExpr( 1820 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1821 SCEV::FlagNUW, Depth + 1); 1822 } 1823 } 1824 1825 // The cast wasn't folded; create an explicit cast node. 1826 // Recompute the insert position, as it may have been invalidated. 1827 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1828 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1829 Op, Ty); 1830 UniqueSCEVs.InsertNode(S, IP); 1831 addToLoopUseLists(S); 1832 return S; 1833 } 1834 1835 const SCEV * 1836 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1837 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1838 "This is not an extending conversion!"); 1839 assert(isSCEVable(Ty) && 1840 "This is not a conversion to a SCEVable type!"); 1841 Ty = getEffectiveSCEVType(Ty); 1842 1843 // Fold if the operand is constant. 1844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1845 return getConstant( 1846 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1847 1848 // sext(sext(x)) --> sext(x) 1849 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1850 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1851 1852 // sext(zext(x)) --> zext(x) 1853 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1854 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1855 1856 // Before doing any expensive analysis, check to see if we've already 1857 // computed a SCEV for this Op and Ty. 1858 FoldingSetNodeID ID; 1859 ID.AddInteger(scSignExtend); 1860 ID.AddPointer(Op); 1861 ID.AddPointer(Ty); 1862 void *IP = nullptr; 1863 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1864 // Limit recursion depth. 1865 if (Depth > MaxCastDepth) { 1866 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1867 Op, Ty); 1868 UniqueSCEVs.InsertNode(S, IP); 1869 addToLoopUseLists(S); 1870 return S; 1871 } 1872 1873 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1874 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1875 // It's possible the bits taken off by the truncate were all sign bits. If 1876 // so, we should be able to simplify this further. 1877 const SCEV *X = ST->getOperand(); 1878 ConstantRange CR = getSignedRange(X); 1879 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1880 unsigned NewBits = getTypeSizeInBits(Ty); 1881 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1882 CR.sextOrTrunc(NewBits))) 1883 return getTruncateOrSignExtend(X, Ty, Depth); 1884 } 1885 1886 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1887 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1888 if (SA->hasNoSignedWrap()) { 1889 // If the addition does not sign overflow then we can, by definition, 1890 // commute the sign extension with the addition operation. 1891 SmallVector<const SCEV *, 4> Ops; 1892 for (const auto *Op : SA->operands()) 1893 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1894 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1895 } 1896 1897 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1898 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1899 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1900 // 1901 // For instance, this will bring two seemingly different expressions: 1902 // 1 + sext(5 + 20 * %x + 24 * %y) and 1903 // sext(6 + 20 * %x + 24 * %y) 1904 // to the same form: 1905 // 2 + sext(4 + 20 * %x + 24 * %y) 1906 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1907 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1908 if (D != 0) { 1909 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1910 const SCEV *SResidual = 1911 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1912 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1913 return getAddExpr(SSExtD, SSExtR, 1914 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1915 Depth + 1); 1916 } 1917 } 1918 } 1919 // If the input value is a chrec scev, and we can prove that the value 1920 // did not overflow the old, smaller, value, we can sign extend all of the 1921 // operands (often constants). This allows analysis of something like 1922 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1924 if (AR->isAffine()) { 1925 const SCEV *Start = AR->getStart(); 1926 const SCEV *Step = AR->getStepRecurrence(*this); 1927 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1928 const Loop *L = AR->getLoop(); 1929 1930 if (!AR->hasNoSignedWrap()) { 1931 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1932 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1933 } 1934 1935 // If we have special knowledge that this addrec won't overflow, 1936 // we don't need to do any further analysis. 1937 if (AR->hasNoSignedWrap()) 1938 return getAddRecExpr( 1939 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1940 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1941 1942 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1943 // Note that this serves two purposes: It filters out loops that are 1944 // simply not analyzable, and it covers the case where this code is 1945 // being called from within backedge-taken count analysis, such that 1946 // attempting to ask for the backedge-taken count would likely result 1947 // in infinite recursion. In the later case, the analysis code will 1948 // cope with a conservative value, and it will take care to purge 1949 // that value once it has finished. 1950 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1951 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1952 // Manually compute the final value for AR, checking for 1953 // overflow. 1954 1955 // Check whether the backedge-taken count can be losslessly casted to 1956 // the addrec's type. The count is always unsigned. 1957 const SCEV *CastedMaxBECount = 1958 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1959 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1960 CastedMaxBECount, MaxBECount->getType(), Depth); 1961 if (MaxBECount == RecastedMaxBECount) { 1962 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1963 // Check whether Start+Step*MaxBECount has no signed overflow. 1964 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1965 SCEV::FlagAnyWrap, Depth + 1); 1966 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1967 SCEV::FlagAnyWrap, 1968 Depth + 1), 1969 WideTy, Depth + 1); 1970 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1971 const SCEV *WideMaxBECount = 1972 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1973 const SCEV *OperandExtendedAdd = 1974 getAddExpr(WideStart, 1975 getMulExpr(WideMaxBECount, 1976 getSignExtendExpr(Step, WideTy, Depth + 1), 1977 SCEV::FlagAnyWrap, Depth + 1), 1978 SCEV::FlagAnyWrap, Depth + 1); 1979 if (SAdd == OperandExtendedAdd) { 1980 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1981 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 1982 // Return the expression with the addrec on the outside. 1983 return getAddRecExpr( 1984 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1985 Depth + 1), 1986 getSignExtendExpr(Step, Ty, Depth + 1), L, 1987 AR->getNoWrapFlags()); 1988 } 1989 // Similar to above, only this time treat the step value as unsigned. 1990 // This covers loops that count up with an unsigned step. 1991 OperandExtendedAdd = 1992 getAddExpr(WideStart, 1993 getMulExpr(WideMaxBECount, 1994 getZeroExtendExpr(Step, WideTy, Depth + 1), 1995 SCEV::FlagAnyWrap, Depth + 1), 1996 SCEV::FlagAnyWrap, Depth + 1); 1997 if (SAdd == OperandExtendedAdd) { 1998 // If AR wraps around then 1999 // 2000 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2001 // => SAdd != OperandExtendedAdd 2002 // 2003 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2004 // (SAdd == OperandExtendedAdd => AR is NW) 2005 2006 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2007 2008 // Return the expression with the addrec on the outside. 2009 return getAddRecExpr( 2010 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2011 Depth + 1), 2012 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2013 AR->getNoWrapFlags()); 2014 } 2015 } 2016 } 2017 2018 // Normally, in the cases we can prove no-overflow via a 2019 // backedge guarding condition, we can also compute a backedge 2020 // taken count for the loop. The exceptions are assumptions and 2021 // guards present in the loop -- SCEV is not great at exploiting 2022 // these to compute max backedge taken counts, but can still use 2023 // these to prove lack of overflow. Use this fact to avoid 2024 // doing extra work that may not pay off. 2025 2026 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2027 !AC.assumptions().empty()) { 2028 // If the backedge is guarded by a comparison with the pre-inc 2029 // value the addrec is safe. Also, if the entry is guarded by 2030 // a comparison with the start value and the backedge is 2031 // guarded by a comparison with the post-inc value, the addrec 2032 // is safe. 2033 ICmpInst::Predicate Pred; 2034 const SCEV *OverflowLimit = 2035 getSignedOverflowLimitForStep(Step, &Pred, this); 2036 if (OverflowLimit && 2037 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2038 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2039 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2040 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2041 return getAddRecExpr( 2042 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2043 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2044 } 2045 } 2046 2047 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2048 // if D + (C - D + Step * n) could be proven to not signed wrap 2049 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2050 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2051 const APInt &C = SC->getAPInt(); 2052 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2053 if (D != 0) { 2054 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2055 const SCEV *SResidual = 2056 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2057 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2058 return getAddExpr(SSExtD, SSExtR, 2059 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2060 Depth + 1); 2061 } 2062 } 2063 2064 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2065 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2066 return getAddRecExpr( 2067 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2068 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2069 } 2070 } 2071 2072 // If the input value is provably positive and we could not simplify 2073 // away the sext build a zext instead. 2074 if (isKnownNonNegative(Op)) 2075 return getZeroExtendExpr(Op, Ty, Depth + 1); 2076 2077 // The cast wasn't folded; create an explicit cast node. 2078 // Recompute the insert position, as it may have been invalidated. 2079 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2080 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2081 Op, Ty); 2082 UniqueSCEVs.InsertNode(S, IP); 2083 addToLoopUseLists(S); 2084 return S; 2085 } 2086 2087 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2088 /// unspecified bits out to the given type. 2089 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2090 Type *Ty) { 2091 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2092 "This is not an extending conversion!"); 2093 assert(isSCEVable(Ty) && 2094 "This is not a conversion to a SCEVable type!"); 2095 Ty = getEffectiveSCEVType(Ty); 2096 2097 // Sign-extend negative constants. 2098 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2099 if (SC->getAPInt().isNegative()) 2100 return getSignExtendExpr(Op, Ty); 2101 2102 // Peel off a truncate cast. 2103 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2104 const SCEV *NewOp = T->getOperand(); 2105 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2106 return getAnyExtendExpr(NewOp, Ty); 2107 return getTruncateOrNoop(NewOp, Ty); 2108 } 2109 2110 // Next try a zext cast. If the cast is folded, use it. 2111 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2112 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2113 return ZExt; 2114 2115 // Next try a sext cast. If the cast is folded, use it. 2116 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2117 if (!isa<SCEVSignExtendExpr>(SExt)) 2118 return SExt; 2119 2120 // Force the cast to be folded into the operands of an addrec. 2121 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2122 SmallVector<const SCEV *, 4> Ops; 2123 for (const SCEV *Op : AR->operands()) 2124 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2125 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2126 } 2127 2128 // If the expression is obviously signed, use the sext cast value. 2129 if (isa<SCEVSMaxExpr>(Op)) 2130 return SExt; 2131 2132 // Absent any other information, use the zext cast value. 2133 return ZExt; 2134 } 2135 2136 /// Process the given Ops list, which is a list of operands to be added under 2137 /// the given scale, update the given map. This is a helper function for 2138 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2139 /// that would form an add expression like this: 2140 /// 2141 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2142 /// 2143 /// where A and B are constants, update the map with these values: 2144 /// 2145 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2146 /// 2147 /// and add 13 + A*B*29 to AccumulatedConstant. 2148 /// This will allow getAddRecExpr to produce this: 2149 /// 2150 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2151 /// 2152 /// This form often exposes folding opportunities that are hidden in 2153 /// the original operand list. 2154 /// 2155 /// Return true iff it appears that any interesting folding opportunities 2156 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2157 /// the common case where no interesting opportunities are present, and 2158 /// is also used as a check to avoid infinite recursion. 2159 static bool 2160 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2161 SmallVectorImpl<const SCEV *> &NewOps, 2162 APInt &AccumulatedConstant, 2163 const SCEV *const *Ops, size_t NumOperands, 2164 const APInt &Scale, 2165 ScalarEvolution &SE) { 2166 bool Interesting = false; 2167 2168 // Iterate over the add operands. They are sorted, with constants first. 2169 unsigned i = 0; 2170 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2171 ++i; 2172 // Pull a buried constant out to the outside. 2173 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2174 Interesting = true; 2175 AccumulatedConstant += Scale * C->getAPInt(); 2176 } 2177 2178 // Next comes everything else. We're especially interested in multiplies 2179 // here, but they're in the middle, so just visit the rest with one loop. 2180 for (; i != NumOperands; ++i) { 2181 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2182 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2183 APInt NewScale = 2184 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2185 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2186 // A multiplication of a constant with another add; recurse. 2187 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2188 Interesting |= 2189 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2190 Add->op_begin(), Add->getNumOperands(), 2191 NewScale, SE); 2192 } else { 2193 // A multiplication of a constant with some other value. Update 2194 // the map. 2195 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2196 const SCEV *Key = SE.getMulExpr(MulOps); 2197 auto Pair = M.insert({Key, NewScale}); 2198 if (Pair.second) { 2199 NewOps.push_back(Pair.first->first); 2200 } else { 2201 Pair.first->second += NewScale; 2202 // The map already had an entry for this value, which may indicate 2203 // a folding opportunity. 2204 Interesting = true; 2205 } 2206 } 2207 } else { 2208 // An ordinary operand. Update the map. 2209 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2210 M.insert({Ops[i], Scale}); 2211 if (Pair.second) { 2212 NewOps.push_back(Pair.first->first); 2213 } else { 2214 Pair.first->second += Scale; 2215 // The map already had an entry for this value, which may indicate 2216 // a folding opportunity. 2217 Interesting = true; 2218 } 2219 } 2220 } 2221 2222 return Interesting; 2223 } 2224 2225 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2226 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2227 // can't-overflow flags for the operation if possible. 2228 static SCEV::NoWrapFlags 2229 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2230 const ArrayRef<const SCEV *> Ops, 2231 SCEV::NoWrapFlags Flags) { 2232 using namespace std::placeholders; 2233 2234 using OBO = OverflowingBinaryOperator; 2235 2236 bool CanAnalyze = 2237 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2238 (void)CanAnalyze; 2239 assert(CanAnalyze && "don't call from other places!"); 2240 2241 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2242 SCEV::NoWrapFlags SignOrUnsignWrap = 2243 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2244 2245 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2246 auto IsKnownNonNegative = [&](const SCEV *S) { 2247 return SE->isKnownNonNegative(S); 2248 }; 2249 2250 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2251 Flags = 2252 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2253 2254 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2255 2256 if (SignOrUnsignWrap != SignOrUnsignMask && 2257 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2258 isa<SCEVConstant>(Ops[0])) { 2259 2260 auto Opcode = [&] { 2261 switch (Type) { 2262 case scAddExpr: 2263 return Instruction::Add; 2264 case scMulExpr: 2265 return Instruction::Mul; 2266 default: 2267 llvm_unreachable("Unexpected SCEV op."); 2268 } 2269 }(); 2270 2271 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2272 2273 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2274 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2275 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2276 Opcode, C, OBO::NoSignedWrap); 2277 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2278 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2279 } 2280 2281 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2282 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2283 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2284 Opcode, C, OBO::NoUnsignedWrap); 2285 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2286 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2287 } 2288 } 2289 2290 return Flags; 2291 } 2292 2293 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2294 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2295 } 2296 2297 /// Get a canonical add expression, or something simpler if possible. 2298 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2299 SCEV::NoWrapFlags OrigFlags, 2300 unsigned Depth) { 2301 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2302 "only nuw or nsw allowed"); 2303 assert(!Ops.empty() && "Cannot get empty add!"); 2304 if (Ops.size() == 1) return Ops[0]; 2305 #ifndef NDEBUG 2306 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2307 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2309 "SCEVAddExpr operand types don't match!"); 2310 #endif 2311 2312 // Sort by complexity, this groups all similar expression types together. 2313 GroupByComplexity(Ops, &LI, DT); 2314 2315 // If there are any constants, fold them together. 2316 unsigned Idx = 0; 2317 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2318 ++Idx; 2319 assert(Idx < Ops.size()); 2320 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2321 // We found two constants, fold them together! 2322 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2323 if (Ops.size() == 2) return Ops[0]; 2324 Ops.erase(Ops.begin()+1); // Erase the folded element 2325 LHSC = cast<SCEVConstant>(Ops[0]); 2326 } 2327 2328 // If we are left with a constant zero being added, strip it off. 2329 if (LHSC->getValue()->isZero()) { 2330 Ops.erase(Ops.begin()); 2331 --Idx; 2332 } 2333 2334 if (Ops.size() == 1) return Ops[0]; 2335 } 2336 2337 // Delay expensive flag strengthening until necessary. 2338 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2339 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2340 }; 2341 2342 // Limit recursion calls depth. 2343 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2344 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2345 2346 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2347 // Don't strengthen flags if we have no new information. 2348 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2349 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2350 Add->setNoWrapFlags(ComputeFlags(Ops)); 2351 return S; 2352 } 2353 2354 // Okay, check to see if the same value occurs in the operand list more than 2355 // once. If so, merge them together into an multiply expression. Since we 2356 // sorted the list, these values are required to be adjacent. 2357 Type *Ty = Ops[0]->getType(); 2358 bool FoundMatch = false; 2359 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2360 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2361 // Scan ahead to count how many equal operands there are. 2362 unsigned Count = 2; 2363 while (i+Count != e && Ops[i+Count] == Ops[i]) 2364 ++Count; 2365 // Merge the values into a multiply. 2366 const SCEV *Scale = getConstant(Ty, Count); 2367 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2368 if (Ops.size() == Count) 2369 return Mul; 2370 Ops[i] = Mul; 2371 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2372 --i; e -= Count - 1; 2373 FoundMatch = true; 2374 } 2375 if (FoundMatch) 2376 return getAddExpr(Ops, OrigFlags, Depth + 1); 2377 2378 // Check for truncates. If all the operands are truncated from the same 2379 // type, see if factoring out the truncate would permit the result to be 2380 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2381 // if the contents of the resulting outer trunc fold to something simple. 2382 auto FindTruncSrcType = [&]() -> Type * { 2383 // We're ultimately looking to fold an addrec of truncs and muls of only 2384 // constants and truncs, so if we find any other types of SCEV 2385 // as operands of the addrec then we bail and return nullptr here. 2386 // Otherwise, we return the type of the operand of a trunc that we find. 2387 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2388 return T->getOperand()->getType(); 2389 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2390 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2391 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2392 return T->getOperand()->getType(); 2393 } 2394 return nullptr; 2395 }; 2396 if (auto *SrcType = FindTruncSrcType()) { 2397 SmallVector<const SCEV *, 8> LargeOps; 2398 bool Ok = true; 2399 // Check all the operands to see if they can be represented in the 2400 // source type of the truncate. 2401 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2402 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2403 if (T->getOperand()->getType() != SrcType) { 2404 Ok = false; 2405 break; 2406 } 2407 LargeOps.push_back(T->getOperand()); 2408 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2409 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2410 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2411 SmallVector<const SCEV *, 8> LargeMulOps; 2412 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2413 if (const SCEVTruncateExpr *T = 2414 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2415 if (T->getOperand()->getType() != SrcType) { 2416 Ok = false; 2417 break; 2418 } 2419 LargeMulOps.push_back(T->getOperand()); 2420 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2421 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2422 } else { 2423 Ok = false; 2424 break; 2425 } 2426 } 2427 if (Ok) 2428 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2429 } else { 2430 Ok = false; 2431 break; 2432 } 2433 } 2434 if (Ok) { 2435 // Evaluate the expression in the larger type. 2436 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2437 // If it folds to something simple, use it. Otherwise, don't. 2438 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2439 return getTruncateExpr(Fold, Ty); 2440 } 2441 } 2442 2443 // Skip past any other cast SCEVs. 2444 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2445 ++Idx; 2446 2447 // If there are add operands they would be next. 2448 if (Idx < Ops.size()) { 2449 bool DeletedAdd = false; 2450 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2451 if (Ops.size() > AddOpsInlineThreshold || 2452 Add->getNumOperands() > AddOpsInlineThreshold) 2453 break; 2454 // If we have an add, expand the add operands onto the end of the operands 2455 // list. 2456 Ops.erase(Ops.begin()+Idx); 2457 Ops.append(Add->op_begin(), Add->op_end()); 2458 DeletedAdd = true; 2459 } 2460 2461 // If we deleted at least one add, we added operands to the end of the list, 2462 // and they are not necessarily sorted. Recurse to resort and resimplify 2463 // any operands we just acquired. 2464 if (DeletedAdd) 2465 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2466 } 2467 2468 // Skip over the add expression until we get to a multiply. 2469 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2470 ++Idx; 2471 2472 // Check to see if there are any folding opportunities present with 2473 // operands multiplied by constant values. 2474 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2475 uint64_t BitWidth = getTypeSizeInBits(Ty); 2476 DenseMap<const SCEV *, APInt> M; 2477 SmallVector<const SCEV *, 8> NewOps; 2478 APInt AccumulatedConstant(BitWidth, 0); 2479 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2480 Ops.data(), Ops.size(), 2481 APInt(BitWidth, 1), *this)) { 2482 struct APIntCompare { 2483 bool operator()(const APInt &LHS, const APInt &RHS) const { 2484 return LHS.ult(RHS); 2485 } 2486 }; 2487 2488 // Some interesting folding opportunity is present, so its worthwhile to 2489 // re-generate the operands list. Group the operands by constant scale, 2490 // to avoid multiplying by the same constant scale multiple times. 2491 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2492 for (const SCEV *NewOp : NewOps) 2493 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2494 // Re-generate the operands list. 2495 Ops.clear(); 2496 if (AccumulatedConstant != 0) 2497 Ops.push_back(getConstant(AccumulatedConstant)); 2498 for (auto &MulOp : MulOpLists) 2499 if (MulOp.first != 0) 2500 Ops.push_back(getMulExpr( 2501 getConstant(MulOp.first), 2502 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2503 SCEV::FlagAnyWrap, Depth + 1)); 2504 if (Ops.empty()) 2505 return getZero(Ty); 2506 if (Ops.size() == 1) 2507 return Ops[0]; 2508 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2509 } 2510 } 2511 2512 // If we are adding something to a multiply expression, make sure the 2513 // something is not already an operand of the multiply. If so, merge it into 2514 // the multiply. 2515 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2516 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2517 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2518 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2519 if (isa<SCEVConstant>(MulOpSCEV)) 2520 continue; 2521 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2522 if (MulOpSCEV == Ops[AddOp]) { 2523 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2524 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2525 if (Mul->getNumOperands() != 2) { 2526 // If the multiply has more than two operands, we must get the 2527 // Y*Z term. 2528 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2529 Mul->op_begin()+MulOp); 2530 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2531 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2532 } 2533 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2534 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2535 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2536 SCEV::FlagAnyWrap, Depth + 1); 2537 if (Ops.size() == 2) return OuterMul; 2538 if (AddOp < Idx) { 2539 Ops.erase(Ops.begin()+AddOp); 2540 Ops.erase(Ops.begin()+Idx-1); 2541 } else { 2542 Ops.erase(Ops.begin()+Idx); 2543 Ops.erase(Ops.begin()+AddOp-1); 2544 } 2545 Ops.push_back(OuterMul); 2546 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2547 } 2548 2549 // Check this multiply against other multiplies being added together. 2550 for (unsigned OtherMulIdx = Idx+1; 2551 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2552 ++OtherMulIdx) { 2553 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2554 // If MulOp occurs in OtherMul, we can fold the two multiplies 2555 // together. 2556 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2557 OMulOp != e; ++OMulOp) 2558 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2559 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2560 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2561 if (Mul->getNumOperands() != 2) { 2562 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2563 Mul->op_begin()+MulOp); 2564 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2565 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2566 } 2567 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2568 if (OtherMul->getNumOperands() != 2) { 2569 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2570 OtherMul->op_begin()+OMulOp); 2571 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2572 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2573 } 2574 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2575 const SCEV *InnerMulSum = 2576 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2577 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2578 SCEV::FlagAnyWrap, Depth + 1); 2579 if (Ops.size() == 2) return OuterMul; 2580 Ops.erase(Ops.begin()+Idx); 2581 Ops.erase(Ops.begin()+OtherMulIdx-1); 2582 Ops.push_back(OuterMul); 2583 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2584 } 2585 } 2586 } 2587 } 2588 2589 // If there are any add recurrences in the operands list, see if any other 2590 // added values are loop invariant. If so, we can fold them into the 2591 // recurrence. 2592 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2593 ++Idx; 2594 2595 // Scan over all recurrences, trying to fold loop invariants into them. 2596 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2597 // Scan all of the other operands to this add and add them to the vector if 2598 // they are loop invariant w.r.t. the recurrence. 2599 SmallVector<const SCEV *, 8> LIOps; 2600 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2601 const Loop *AddRecLoop = AddRec->getLoop(); 2602 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2603 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2604 LIOps.push_back(Ops[i]); 2605 Ops.erase(Ops.begin()+i); 2606 --i; --e; 2607 } 2608 2609 // If we found some loop invariants, fold them into the recurrence. 2610 if (!LIOps.empty()) { 2611 // Compute nowrap flags for the addition of the loop-invariant ops and 2612 // the addrec. Temporarily push it as an operand for that purpose. 2613 LIOps.push_back(AddRec); 2614 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2615 LIOps.pop_back(); 2616 2617 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2618 LIOps.push_back(AddRec->getStart()); 2619 2620 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2621 AddRec->op_end()); 2622 // This follows from the fact that the no-wrap flags on the outer add 2623 // expression are applicable on the 0th iteration, when the add recurrence 2624 // will be equal to its start value. 2625 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2626 2627 // Build the new addrec. Propagate the NUW and NSW flags if both the 2628 // outer add and the inner addrec are guaranteed to have no overflow. 2629 // Always propagate NW. 2630 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2631 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2632 2633 // If all of the other operands were loop invariant, we are done. 2634 if (Ops.size() == 1) return NewRec; 2635 2636 // Otherwise, add the folded AddRec by the non-invariant parts. 2637 for (unsigned i = 0;; ++i) 2638 if (Ops[i] == AddRec) { 2639 Ops[i] = NewRec; 2640 break; 2641 } 2642 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2643 } 2644 2645 // Okay, if there weren't any loop invariants to be folded, check to see if 2646 // there are multiple AddRec's with the same loop induction variable being 2647 // added together. If so, we can fold them. 2648 for (unsigned OtherIdx = Idx+1; 2649 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2650 ++OtherIdx) { 2651 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2652 // so that the 1st found AddRecExpr is dominated by all others. 2653 assert(DT.dominates( 2654 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2655 AddRec->getLoop()->getHeader()) && 2656 "AddRecExprs are not sorted in reverse dominance order?"); 2657 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2658 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2659 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2660 AddRec->op_end()); 2661 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2662 ++OtherIdx) { 2663 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2664 if (OtherAddRec->getLoop() == AddRecLoop) { 2665 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2666 i != e; ++i) { 2667 if (i >= AddRecOps.size()) { 2668 AddRecOps.append(OtherAddRec->op_begin()+i, 2669 OtherAddRec->op_end()); 2670 break; 2671 } 2672 SmallVector<const SCEV *, 2> TwoOps = { 2673 AddRecOps[i], OtherAddRec->getOperand(i)}; 2674 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2675 } 2676 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2677 } 2678 } 2679 // Step size has changed, so we cannot guarantee no self-wraparound. 2680 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2681 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2682 } 2683 } 2684 2685 // Otherwise couldn't fold anything into this recurrence. Move onto the 2686 // next one. 2687 } 2688 2689 // Okay, it looks like we really DO need an add expr. Check to see if we 2690 // already have one, otherwise create a new one. 2691 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2692 } 2693 2694 const SCEV * 2695 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2696 SCEV::NoWrapFlags Flags) { 2697 FoldingSetNodeID ID; 2698 ID.AddInteger(scAddExpr); 2699 for (const SCEV *Op : Ops) 2700 ID.AddPointer(Op); 2701 void *IP = nullptr; 2702 SCEVAddExpr *S = 2703 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2704 if (!S) { 2705 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2706 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2707 S = new (SCEVAllocator) 2708 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2709 UniqueSCEVs.InsertNode(S, IP); 2710 addToLoopUseLists(S); 2711 } 2712 S->setNoWrapFlags(Flags); 2713 return S; 2714 } 2715 2716 const SCEV * 2717 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2718 const Loop *L, SCEV::NoWrapFlags Flags) { 2719 FoldingSetNodeID ID; 2720 ID.AddInteger(scAddRecExpr); 2721 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2722 ID.AddPointer(Ops[i]); 2723 ID.AddPointer(L); 2724 void *IP = nullptr; 2725 SCEVAddRecExpr *S = 2726 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2727 if (!S) { 2728 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2729 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2730 S = new (SCEVAllocator) 2731 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2732 UniqueSCEVs.InsertNode(S, IP); 2733 addToLoopUseLists(S); 2734 } 2735 setNoWrapFlags(S, Flags); 2736 return S; 2737 } 2738 2739 const SCEV * 2740 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2741 SCEV::NoWrapFlags Flags) { 2742 FoldingSetNodeID ID; 2743 ID.AddInteger(scMulExpr); 2744 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2745 ID.AddPointer(Ops[i]); 2746 void *IP = nullptr; 2747 SCEVMulExpr *S = 2748 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2749 if (!S) { 2750 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2751 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2752 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2753 O, Ops.size()); 2754 UniqueSCEVs.InsertNode(S, IP); 2755 addToLoopUseLists(S); 2756 } 2757 S->setNoWrapFlags(Flags); 2758 return S; 2759 } 2760 2761 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2762 uint64_t k = i*j; 2763 if (j > 1 && k / j != i) Overflow = true; 2764 return k; 2765 } 2766 2767 /// Compute the result of "n choose k", the binomial coefficient. If an 2768 /// intermediate computation overflows, Overflow will be set and the return will 2769 /// be garbage. Overflow is not cleared on absence of overflow. 2770 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2771 // We use the multiplicative formula: 2772 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2773 // At each iteration, we take the n-th term of the numeral and divide by the 2774 // (k-n)th term of the denominator. This division will always produce an 2775 // integral result, and helps reduce the chance of overflow in the 2776 // intermediate computations. However, we can still overflow even when the 2777 // final result would fit. 2778 2779 if (n == 0 || n == k) return 1; 2780 if (k > n) return 0; 2781 2782 if (k > n/2) 2783 k = n-k; 2784 2785 uint64_t r = 1; 2786 for (uint64_t i = 1; i <= k; ++i) { 2787 r = umul_ov(r, n-(i-1), Overflow); 2788 r /= i; 2789 } 2790 return r; 2791 } 2792 2793 /// Determine if any of the operands in this SCEV are a constant or if 2794 /// any of the add or multiply expressions in this SCEV contain a constant. 2795 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2796 struct FindConstantInAddMulChain { 2797 bool FoundConstant = false; 2798 2799 bool follow(const SCEV *S) { 2800 FoundConstant |= isa<SCEVConstant>(S); 2801 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2802 } 2803 2804 bool isDone() const { 2805 return FoundConstant; 2806 } 2807 }; 2808 2809 FindConstantInAddMulChain F; 2810 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2811 ST.visitAll(StartExpr); 2812 return F.FoundConstant; 2813 } 2814 2815 /// Get a canonical multiply expression, or something simpler if possible. 2816 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2817 SCEV::NoWrapFlags OrigFlags, 2818 unsigned Depth) { 2819 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2820 "only nuw or nsw allowed"); 2821 assert(!Ops.empty() && "Cannot get empty mul!"); 2822 if (Ops.size() == 1) return Ops[0]; 2823 #ifndef NDEBUG 2824 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2825 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2826 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2827 "SCEVMulExpr operand types don't match!"); 2828 #endif 2829 2830 // Sort by complexity, this groups all similar expression types together. 2831 GroupByComplexity(Ops, &LI, DT); 2832 2833 // If there are any constants, fold them together. 2834 unsigned Idx = 0; 2835 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2836 ++Idx; 2837 assert(Idx < Ops.size()); 2838 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2839 // We found two constants, fold them together! 2840 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2841 if (Ops.size() == 2) return Ops[0]; 2842 Ops.erase(Ops.begin()+1); // Erase the folded element 2843 LHSC = cast<SCEVConstant>(Ops[0]); 2844 } 2845 2846 // If we have a multiply of zero, it will always be zero. 2847 if (LHSC->getValue()->isZero()) 2848 return LHSC; 2849 2850 // If we are left with a constant one being multiplied, strip it off. 2851 if (LHSC->getValue()->isOne()) { 2852 Ops.erase(Ops.begin()); 2853 --Idx; 2854 } 2855 2856 if (Ops.size() == 1) 2857 return Ops[0]; 2858 } 2859 2860 // Delay expensive flag strengthening until necessary. 2861 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2862 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2863 }; 2864 2865 // Limit recursion calls depth. 2866 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2867 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2868 2869 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2870 // Don't strengthen flags if we have no new information. 2871 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2872 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2873 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2874 return S; 2875 } 2876 2877 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2878 if (Ops.size() == 2) { 2879 // C1*(C2+V) -> C1*C2 + C1*V 2880 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2881 // If any of Add's ops are Adds or Muls with a constant, apply this 2882 // transformation as well. 2883 // 2884 // TODO: There are some cases where this transformation is not 2885 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2886 // this transformation should be narrowed down. 2887 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2888 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2889 SCEV::FlagAnyWrap, Depth + 1), 2890 getMulExpr(LHSC, Add->getOperand(1), 2891 SCEV::FlagAnyWrap, Depth + 1), 2892 SCEV::FlagAnyWrap, Depth + 1); 2893 2894 if (Ops[0]->isAllOnesValue()) { 2895 // If we have a mul by -1 of an add, try distributing the -1 among the 2896 // add operands. 2897 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2898 SmallVector<const SCEV *, 4> NewOps; 2899 bool AnyFolded = false; 2900 for (const SCEV *AddOp : Add->operands()) { 2901 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2902 Depth + 1); 2903 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2904 NewOps.push_back(Mul); 2905 } 2906 if (AnyFolded) 2907 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2908 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2909 // Negation preserves a recurrence's no self-wrap property. 2910 SmallVector<const SCEV *, 4> Operands; 2911 for (const SCEV *AddRecOp : AddRec->operands()) 2912 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2913 Depth + 1)); 2914 2915 return getAddRecExpr(Operands, AddRec->getLoop(), 2916 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2917 } 2918 } 2919 } 2920 } 2921 2922 // Skip over the add expression until we get to a multiply. 2923 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2924 ++Idx; 2925 2926 // If there are mul operands inline them all into this expression. 2927 if (Idx < Ops.size()) { 2928 bool DeletedMul = false; 2929 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2930 if (Ops.size() > MulOpsInlineThreshold) 2931 break; 2932 // If we have an mul, expand the mul operands onto the end of the 2933 // operands list. 2934 Ops.erase(Ops.begin()+Idx); 2935 Ops.append(Mul->op_begin(), Mul->op_end()); 2936 DeletedMul = true; 2937 } 2938 2939 // If we deleted at least one mul, we added operands to the end of the 2940 // list, and they are not necessarily sorted. Recurse to resort and 2941 // resimplify any operands we just acquired. 2942 if (DeletedMul) 2943 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2944 } 2945 2946 // If there are any add recurrences in the operands list, see if any other 2947 // added values are loop invariant. If so, we can fold them into the 2948 // recurrence. 2949 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2950 ++Idx; 2951 2952 // Scan over all recurrences, trying to fold loop invariants into them. 2953 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2954 // Scan all of the other operands to this mul and add them to the vector 2955 // if they are loop invariant w.r.t. the recurrence. 2956 SmallVector<const SCEV *, 8> LIOps; 2957 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2958 const Loop *AddRecLoop = AddRec->getLoop(); 2959 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2960 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2961 LIOps.push_back(Ops[i]); 2962 Ops.erase(Ops.begin()+i); 2963 --i; --e; 2964 } 2965 2966 // If we found some loop invariants, fold them into the recurrence. 2967 if (!LIOps.empty()) { 2968 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2969 SmallVector<const SCEV *, 4> NewOps; 2970 NewOps.reserve(AddRec->getNumOperands()); 2971 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2972 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2973 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2974 SCEV::FlagAnyWrap, Depth + 1)); 2975 2976 // Build the new addrec. Propagate the NUW and NSW flags if both the 2977 // outer mul and the inner addrec are guaranteed to have no overflow. 2978 // 2979 // No self-wrap cannot be guaranteed after changing the step size, but 2980 // will be inferred if either NUW or NSW is true. 2981 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 2982 const SCEV *NewRec = getAddRecExpr( 2983 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 2984 2985 // If all of the other operands were loop invariant, we are done. 2986 if (Ops.size() == 1) return NewRec; 2987 2988 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2989 for (unsigned i = 0;; ++i) 2990 if (Ops[i] == AddRec) { 2991 Ops[i] = NewRec; 2992 break; 2993 } 2994 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2995 } 2996 2997 // Okay, if there weren't any loop invariants to be folded, check to see 2998 // if there are multiple AddRec's with the same loop induction variable 2999 // being multiplied together. If so, we can fold them. 3000 3001 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3002 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3003 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3004 // ]]],+,...up to x=2n}. 3005 // Note that the arguments to choose() are always integers with values 3006 // known at compile time, never SCEV objects. 3007 // 3008 // The implementation avoids pointless extra computations when the two 3009 // addrec's are of different length (mathematically, it's equivalent to 3010 // an infinite stream of zeros on the right). 3011 bool OpsModified = false; 3012 for (unsigned OtherIdx = Idx+1; 3013 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3014 ++OtherIdx) { 3015 const SCEVAddRecExpr *OtherAddRec = 3016 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3017 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3018 continue; 3019 3020 // Limit max number of arguments to avoid creation of unreasonably big 3021 // SCEVAddRecs with very complex operands. 3022 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3023 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3024 continue; 3025 3026 bool Overflow = false; 3027 Type *Ty = AddRec->getType(); 3028 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3029 SmallVector<const SCEV*, 7> AddRecOps; 3030 for (int x = 0, xe = AddRec->getNumOperands() + 3031 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3032 SmallVector <const SCEV *, 7> SumOps; 3033 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3034 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3035 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3036 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3037 z < ze && !Overflow; ++z) { 3038 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3039 uint64_t Coeff; 3040 if (LargerThan64Bits) 3041 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3042 else 3043 Coeff = Coeff1*Coeff2; 3044 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3045 const SCEV *Term1 = AddRec->getOperand(y-z); 3046 const SCEV *Term2 = OtherAddRec->getOperand(z); 3047 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3048 SCEV::FlagAnyWrap, Depth + 1)); 3049 } 3050 } 3051 if (SumOps.empty()) 3052 SumOps.push_back(getZero(Ty)); 3053 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3054 } 3055 if (!Overflow) { 3056 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3057 SCEV::FlagAnyWrap); 3058 if (Ops.size() == 2) return NewAddRec; 3059 Ops[Idx] = NewAddRec; 3060 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3061 OpsModified = true; 3062 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3063 if (!AddRec) 3064 break; 3065 } 3066 } 3067 if (OpsModified) 3068 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3069 3070 // Otherwise couldn't fold anything into this recurrence. Move onto the 3071 // next one. 3072 } 3073 3074 // Okay, it looks like we really DO need an mul expr. Check to see if we 3075 // already have one, otherwise create a new one. 3076 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3077 } 3078 3079 /// Represents an unsigned remainder expression based on unsigned division. 3080 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3081 const SCEV *RHS) { 3082 assert(getEffectiveSCEVType(LHS->getType()) == 3083 getEffectiveSCEVType(RHS->getType()) && 3084 "SCEVURemExpr operand types don't match!"); 3085 3086 // Short-circuit easy cases 3087 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3088 // If constant is one, the result is trivial 3089 if (RHSC->getValue()->isOne()) 3090 return getZero(LHS->getType()); // X urem 1 --> 0 3091 3092 // If constant is a power of two, fold into a zext(trunc(LHS)). 3093 if (RHSC->getAPInt().isPowerOf2()) { 3094 Type *FullTy = LHS->getType(); 3095 Type *TruncTy = 3096 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3097 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3098 } 3099 } 3100 3101 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3102 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3103 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3104 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3105 } 3106 3107 /// Get a canonical unsigned division expression, or something simpler if 3108 /// possible. 3109 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3110 const SCEV *RHS) { 3111 assert(getEffectiveSCEVType(LHS->getType()) == 3112 getEffectiveSCEVType(RHS->getType()) && 3113 "SCEVUDivExpr operand types don't match!"); 3114 3115 FoldingSetNodeID ID; 3116 ID.AddInteger(scUDivExpr); 3117 ID.AddPointer(LHS); 3118 ID.AddPointer(RHS); 3119 void *IP = nullptr; 3120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3121 return S; 3122 3123 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3124 if (RHSC->getValue()->isOne()) 3125 return LHS; // X udiv 1 --> x 3126 // If the denominator is zero, the result of the udiv is undefined. Don't 3127 // try to analyze it, because the resolution chosen here may differ from 3128 // the resolution chosen in other parts of the compiler. 3129 if (!RHSC->getValue()->isZero()) { 3130 // Determine if the division can be folded into the operands of 3131 // its operands. 3132 // TODO: Generalize this to non-constants by using known-bits information. 3133 Type *Ty = LHS->getType(); 3134 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3135 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3136 // For non-power-of-two values, effectively round the value up to the 3137 // nearest power of two. 3138 if (!RHSC->getAPInt().isPowerOf2()) 3139 ++MaxShiftAmt; 3140 IntegerType *ExtTy = 3141 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3142 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3143 if (const SCEVConstant *Step = 3144 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3145 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3146 const APInt &StepInt = Step->getAPInt(); 3147 const APInt &DivInt = RHSC->getAPInt(); 3148 if (!StepInt.urem(DivInt) && 3149 getZeroExtendExpr(AR, ExtTy) == 3150 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3151 getZeroExtendExpr(Step, ExtTy), 3152 AR->getLoop(), SCEV::FlagAnyWrap)) { 3153 SmallVector<const SCEV *, 4> Operands; 3154 for (const SCEV *Op : AR->operands()) 3155 Operands.push_back(getUDivExpr(Op, RHS)); 3156 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3157 } 3158 /// Get a canonical UDivExpr for a recurrence. 3159 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3160 // We can currently only fold X%N if X is constant. 3161 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3162 if (StartC && !DivInt.urem(StepInt) && 3163 getZeroExtendExpr(AR, ExtTy) == 3164 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3165 getZeroExtendExpr(Step, ExtTy), 3166 AR->getLoop(), SCEV::FlagAnyWrap)) { 3167 const APInt &StartInt = StartC->getAPInt(); 3168 const APInt &StartRem = StartInt.urem(StepInt); 3169 if (StartRem != 0) { 3170 const SCEV *NewLHS = 3171 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3172 AR->getLoop(), SCEV::FlagNW); 3173 if (LHS != NewLHS) { 3174 LHS = NewLHS; 3175 3176 // Reset the ID to include the new LHS, and check if it is 3177 // already cached. 3178 ID.clear(); 3179 ID.AddInteger(scUDivExpr); 3180 ID.AddPointer(LHS); 3181 ID.AddPointer(RHS); 3182 IP = nullptr; 3183 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3184 return S; 3185 } 3186 } 3187 } 3188 } 3189 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3190 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3191 SmallVector<const SCEV *, 4> Operands; 3192 for (const SCEV *Op : M->operands()) 3193 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3194 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3195 // Find an operand that's safely divisible. 3196 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3197 const SCEV *Op = M->getOperand(i); 3198 const SCEV *Div = getUDivExpr(Op, RHSC); 3199 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3200 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3201 M->op_end()); 3202 Operands[i] = Div; 3203 return getMulExpr(Operands); 3204 } 3205 } 3206 } 3207 3208 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3209 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3210 if (auto *DivisorConstant = 3211 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3212 bool Overflow = false; 3213 APInt NewRHS = 3214 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3215 if (Overflow) { 3216 return getConstant(RHSC->getType(), 0, false); 3217 } 3218 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3219 } 3220 } 3221 3222 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3223 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3224 SmallVector<const SCEV *, 4> Operands; 3225 for (const SCEV *Op : A->operands()) 3226 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3227 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3228 Operands.clear(); 3229 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3230 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3231 if (isa<SCEVUDivExpr>(Op) || 3232 getMulExpr(Op, RHS) != A->getOperand(i)) 3233 break; 3234 Operands.push_back(Op); 3235 } 3236 if (Operands.size() == A->getNumOperands()) 3237 return getAddExpr(Operands); 3238 } 3239 } 3240 3241 // Fold if both operands are constant. 3242 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3243 Constant *LHSCV = LHSC->getValue(); 3244 Constant *RHSCV = RHSC->getValue(); 3245 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3246 RHSCV))); 3247 } 3248 } 3249 } 3250 3251 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3252 // changes). Make sure we get a new one. 3253 IP = nullptr; 3254 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3255 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3256 LHS, RHS); 3257 UniqueSCEVs.InsertNode(S, IP); 3258 addToLoopUseLists(S); 3259 return S; 3260 } 3261 3262 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3263 APInt A = C1->getAPInt().abs(); 3264 APInt B = C2->getAPInt().abs(); 3265 uint32_t ABW = A.getBitWidth(); 3266 uint32_t BBW = B.getBitWidth(); 3267 3268 if (ABW > BBW) 3269 B = B.zext(ABW); 3270 else if (ABW < BBW) 3271 A = A.zext(BBW); 3272 3273 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3274 } 3275 3276 /// Get a canonical unsigned division expression, or something simpler if 3277 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3278 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3279 /// it's not exact because the udiv may be clearing bits. 3280 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3281 const SCEV *RHS) { 3282 // TODO: we could try to find factors in all sorts of things, but for now we 3283 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3284 // end of this file for inspiration. 3285 3286 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3287 if (!Mul || !Mul->hasNoUnsignedWrap()) 3288 return getUDivExpr(LHS, RHS); 3289 3290 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3291 // If the mulexpr multiplies by a constant, then that constant must be the 3292 // first element of the mulexpr. 3293 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3294 if (LHSCst == RHSCst) { 3295 SmallVector<const SCEV *, 2> Operands; 3296 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3297 return getMulExpr(Operands); 3298 } 3299 3300 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3301 // that there's a factor provided by one of the other terms. We need to 3302 // check. 3303 APInt Factor = gcd(LHSCst, RHSCst); 3304 if (!Factor.isIntN(1)) { 3305 LHSCst = 3306 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3307 RHSCst = 3308 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3309 SmallVector<const SCEV *, 2> Operands; 3310 Operands.push_back(LHSCst); 3311 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3312 LHS = getMulExpr(Operands); 3313 RHS = RHSCst; 3314 Mul = dyn_cast<SCEVMulExpr>(LHS); 3315 if (!Mul) 3316 return getUDivExactExpr(LHS, RHS); 3317 } 3318 } 3319 } 3320 3321 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3322 if (Mul->getOperand(i) == RHS) { 3323 SmallVector<const SCEV *, 2> Operands; 3324 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3325 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3326 return getMulExpr(Operands); 3327 } 3328 } 3329 3330 return getUDivExpr(LHS, RHS); 3331 } 3332 3333 /// Get an add recurrence expression for the specified loop. Simplify the 3334 /// expression as much as possible. 3335 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3336 const Loop *L, 3337 SCEV::NoWrapFlags Flags) { 3338 SmallVector<const SCEV *, 4> Operands; 3339 Operands.push_back(Start); 3340 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3341 if (StepChrec->getLoop() == L) { 3342 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3343 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3344 } 3345 3346 Operands.push_back(Step); 3347 return getAddRecExpr(Operands, L, Flags); 3348 } 3349 3350 /// Get an add recurrence expression for the specified loop. Simplify the 3351 /// expression as much as possible. 3352 const SCEV * 3353 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3354 const Loop *L, SCEV::NoWrapFlags Flags) { 3355 if (Operands.size() == 1) return Operands[0]; 3356 #ifndef NDEBUG 3357 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3358 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3359 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3360 "SCEVAddRecExpr operand types don't match!"); 3361 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3362 assert(isLoopInvariant(Operands[i], L) && 3363 "SCEVAddRecExpr operand is not loop-invariant!"); 3364 #endif 3365 3366 if (Operands.back()->isZero()) { 3367 Operands.pop_back(); 3368 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3369 } 3370 3371 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3372 // use that information to infer NUW and NSW flags. However, computing a 3373 // BE count requires calling getAddRecExpr, so we may not yet have a 3374 // meaningful BE count at this point (and if we don't, we'd be stuck 3375 // with a SCEVCouldNotCompute as the cached BE count). 3376 3377 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3378 3379 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3380 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3381 const Loop *NestedLoop = NestedAR->getLoop(); 3382 if (L->contains(NestedLoop) 3383 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3384 : (!NestedLoop->contains(L) && 3385 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3386 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3387 NestedAR->op_end()); 3388 Operands[0] = NestedAR->getStart(); 3389 // AddRecs require their operands be loop-invariant with respect to their 3390 // loops. Don't perform this transformation if it would break this 3391 // requirement. 3392 bool AllInvariant = all_of( 3393 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3394 3395 if (AllInvariant) { 3396 // Create a recurrence for the outer loop with the same step size. 3397 // 3398 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3399 // inner recurrence has the same property. 3400 SCEV::NoWrapFlags OuterFlags = 3401 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3402 3403 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3404 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3405 return isLoopInvariant(Op, NestedLoop); 3406 }); 3407 3408 if (AllInvariant) { 3409 // Ok, both add recurrences are valid after the transformation. 3410 // 3411 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3412 // the outer recurrence has the same property. 3413 SCEV::NoWrapFlags InnerFlags = 3414 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3415 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3416 } 3417 } 3418 // Reset Operands to its original state. 3419 Operands[0] = NestedAR; 3420 } 3421 } 3422 3423 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3424 // already have one, otherwise create a new one. 3425 return getOrCreateAddRecExpr(Operands, L, Flags); 3426 } 3427 3428 const SCEV * 3429 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3430 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3431 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3432 // getSCEV(Base)->getType() has the same address space as Base->getType() 3433 // because SCEV::getType() preserves the address space. 3434 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3435 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3436 // instruction to its SCEV, because the Instruction may be guarded by control 3437 // flow and the no-overflow bits may not be valid for the expression in any 3438 // context. This can be fixed similarly to how these flags are handled for 3439 // adds. 3440 SCEV::NoWrapFlags OffsetWrap = 3441 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3442 3443 Type *CurTy = GEP->getType(); 3444 bool FirstIter = true; 3445 SmallVector<const SCEV *, 4> Offsets; 3446 for (const SCEV *IndexExpr : IndexExprs) { 3447 // Compute the (potentially symbolic) offset in bytes for this index. 3448 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3449 // For a struct, add the member offset. 3450 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3451 unsigned FieldNo = Index->getZExtValue(); 3452 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3453 Offsets.push_back(FieldOffset); 3454 3455 // Update CurTy to the type of the field at Index. 3456 CurTy = STy->getTypeAtIndex(Index); 3457 } else { 3458 // Update CurTy to its element type. 3459 if (FirstIter) { 3460 assert(isa<PointerType>(CurTy) && 3461 "The first index of a GEP indexes a pointer"); 3462 CurTy = GEP->getSourceElementType(); 3463 FirstIter = false; 3464 } else { 3465 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3466 } 3467 // For an array, add the element offset, explicitly scaled. 3468 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3469 // Getelementptr indices are signed. 3470 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3471 3472 // Multiply the index by the element size to compute the element offset. 3473 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3474 Offsets.push_back(LocalOffset); 3475 } 3476 } 3477 3478 // Handle degenerate case of GEP without offsets. 3479 if (Offsets.empty()) 3480 return BaseExpr; 3481 3482 // Add the offsets together, assuming nsw if inbounds. 3483 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3484 // Add the base address and the offset. We cannot use the nsw flag, as the 3485 // base address is unsigned. However, if we know that the offset is 3486 // non-negative, we can use nuw. 3487 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3488 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3489 return getAddExpr(BaseExpr, Offset, BaseWrap); 3490 } 3491 3492 std::tuple<SCEV *, FoldingSetNodeID, void *> 3493 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3494 ArrayRef<const SCEV *> Ops) { 3495 FoldingSetNodeID ID; 3496 void *IP = nullptr; 3497 ID.AddInteger(SCEVType); 3498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3499 ID.AddPointer(Ops[i]); 3500 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3501 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3502 } 3503 3504 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3505 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3506 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3507 } 3508 3509 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3510 Type *Ty = Op->getType(); 3511 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3512 } 3513 3514 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3515 SmallVectorImpl<const SCEV *> &Ops) { 3516 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3517 if (Ops.size() == 1) return Ops[0]; 3518 #ifndef NDEBUG 3519 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3520 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3521 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3522 "Operand types don't match!"); 3523 #endif 3524 3525 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3526 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3527 3528 // Sort by complexity, this groups all similar expression types together. 3529 GroupByComplexity(Ops, &LI, DT); 3530 3531 // Check if we have created the same expression before. 3532 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3533 return S; 3534 } 3535 3536 // If there are any constants, fold them together. 3537 unsigned Idx = 0; 3538 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3539 ++Idx; 3540 assert(Idx < Ops.size()); 3541 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3542 if (Kind == scSMaxExpr) 3543 return APIntOps::smax(LHS, RHS); 3544 else if (Kind == scSMinExpr) 3545 return APIntOps::smin(LHS, RHS); 3546 else if (Kind == scUMaxExpr) 3547 return APIntOps::umax(LHS, RHS); 3548 else if (Kind == scUMinExpr) 3549 return APIntOps::umin(LHS, RHS); 3550 llvm_unreachable("Unknown SCEV min/max opcode"); 3551 }; 3552 3553 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3554 // We found two constants, fold them together! 3555 ConstantInt *Fold = ConstantInt::get( 3556 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3557 Ops[0] = getConstant(Fold); 3558 Ops.erase(Ops.begin()+1); // Erase the folded element 3559 if (Ops.size() == 1) return Ops[0]; 3560 LHSC = cast<SCEVConstant>(Ops[0]); 3561 } 3562 3563 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3564 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3565 3566 if (IsMax ? IsMinV : IsMaxV) { 3567 // If we are left with a constant minimum(/maximum)-int, strip it off. 3568 Ops.erase(Ops.begin()); 3569 --Idx; 3570 } else if (IsMax ? IsMaxV : IsMinV) { 3571 // If we have a max(/min) with a constant maximum(/minimum)-int, 3572 // it will always be the extremum. 3573 return LHSC; 3574 } 3575 3576 if (Ops.size() == 1) return Ops[0]; 3577 } 3578 3579 // Find the first operation of the same kind 3580 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3581 ++Idx; 3582 3583 // Check to see if one of the operands is of the same kind. If so, expand its 3584 // operands onto our operand list, and recurse to simplify. 3585 if (Idx < Ops.size()) { 3586 bool DeletedAny = false; 3587 while (Ops[Idx]->getSCEVType() == Kind) { 3588 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3589 Ops.erase(Ops.begin()+Idx); 3590 Ops.append(SMME->op_begin(), SMME->op_end()); 3591 DeletedAny = true; 3592 } 3593 3594 if (DeletedAny) 3595 return getMinMaxExpr(Kind, Ops); 3596 } 3597 3598 // Okay, check to see if the same value occurs in the operand list twice. If 3599 // so, delete one. Since we sorted the list, these values are required to 3600 // be adjacent. 3601 llvm::CmpInst::Predicate GEPred = 3602 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3603 llvm::CmpInst::Predicate LEPred = 3604 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3605 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3606 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3607 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3608 if (Ops[i] == Ops[i + 1] || 3609 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3610 // X op Y op Y --> X op Y 3611 // X op Y --> X, if we know X, Y are ordered appropriately 3612 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3613 --i; 3614 --e; 3615 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3616 Ops[i + 1])) { 3617 // X op Y --> Y, if we know X, Y are ordered appropriately 3618 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3619 --i; 3620 --e; 3621 } 3622 } 3623 3624 if (Ops.size() == 1) return Ops[0]; 3625 3626 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3627 3628 // Okay, it looks like we really DO need an expr. Check to see if we 3629 // already have one, otherwise create a new one. 3630 const SCEV *ExistingSCEV; 3631 FoldingSetNodeID ID; 3632 void *IP; 3633 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3634 if (ExistingSCEV) 3635 return ExistingSCEV; 3636 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3637 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3638 SCEV *S = new (SCEVAllocator) 3639 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3640 3641 UniqueSCEVs.InsertNode(S, IP); 3642 addToLoopUseLists(S); 3643 return S; 3644 } 3645 3646 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3647 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3648 return getSMaxExpr(Ops); 3649 } 3650 3651 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3652 return getMinMaxExpr(scSMaxExpr, Ops); 3653 } 3654 3655 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3656 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3657 return getUMaxExpr(Ops); 3658 } 3659 3660 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3661 return getMinMaxExpr(scUMaxExpr, Ops); 3662 } 3663 3664 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3665 const SCEV *RHS) { 3666 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3667 return getSMinExpr(Ops); 3668 } 3669 3670 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3671 return getMinMaxExpr(scSMinExpr, Ops); 3672 } 3673 3674 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3675 const SCEV *RHS) { 3676 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3677 return getUMinExpr(Ops); 3678 } 3679 3680 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3681 return getMinMaxExpr(scUMinExpr, Ops); 3682 } 3683 3684 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3685 if (isa<ScalableVectorType>(AllocTy)) { 3686 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3687 Constant *One = ConstantInt::get(IntTy, 1); 3688 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3689 // Note that the expression we created is the final expression, we don't 3690 // want to simplify it any further Also, if we call a normal getSCEV(), 3691 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3692 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3693 } 3694 // We can bypass creating a target-independent 3695 // constant expression and then folding it back into a ConstantInt. 3696 // This is just a compile-time optimization. 3697 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3698 } 3699 3700 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3701 StructType *STy, 3702 unsigned FieldNo) { 3703 // We can bypass creating a target-independent 3704 // constant expression and then folding it back into a ConstantInt. 3705 // This is just a compile-time optimization. 3706 return getConstant( 3707 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3708 } 3709 3710 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3711 // Don't attempt to do anything other than create a SCEVUnknown object 3712 // here. createSCEV only calls getUnknown after checking for all other 3713 // interesting possibilities, and any other code that calls getUnknown 3714 // is doing so in order to hide a value from SCEV canonicalization. 3715 3716 FoldingSetNodeID ID; 3717 ID.AddInteger(scUnknown); 3718 ID.AddPointer(V); 3719 void *IP = nullptr; 3720 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3721 assert(cast<SCEVUnknown>(S)->getValue() == V && 3722 "Stale SCEVUnknown in uniquing map!"); 3723 return S; 3724 } 3725 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3726 FirstUnknown); 3727 FirstUnknown = cast<SCEVUnknown>(S); 3728 UniqueSCEVs.InsertNode(S, IP); 3729 return S; 3730 } 3731 3732 //===----------------------------------------------------------------------===// 3733 // Basic SCEV Analysis and PHI Idiom Recognition Code 3734 // 3735 3736 /// Test if values of the given type are analyzable within the SCEV 3737 /// framework. This primarily includes integer types, and it can optionally 3738 /// include pointer types if the ScalarEvolution class has access to 3739 /// target-specific information. 3740 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3741 // Integers and pointers are always SCEVable. 3742 return Ty->isIntOrPtrTy(); 3743 } 3744 3745 /// Return the size in bits of the specified type, for which isSCEVable must 3746 /// return true. 3747 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3748 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3749 if (Ty->isPointerTy()) 3750 return getDataLayout().getIndexTypeSizeInBits(Ty); 3751 return getDataLayout().getTypeSizeInBits(Ty); 3752 } 3753 3754 /// Return a type with the same bitwidth as the given type and which represents 3755 /// how SCEV will treat the given type, for which isSCEVable must return 3756 /// true. For pointer types, this is the pointer index sized integer type. 3757 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3758 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3759 3760 if (Ty->isIntegerTy()) 3761 return Ty; 3762 3763 // The only other support type is pointer. 3764 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3765 return getDataLayout().getIndexType(Ty); 3766 } 3767 3768 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3769 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3770 } 3771 3772 const SCEV *ScalarEvolution::getCouldNotCompute() { 3773 return CouldNotCompute.get(); 3774 } 3775 3776 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3777 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3778 auto *SU = dyn_cast<SCEVUnknown>(S); 3779 return SU && SU->getValue() == nullptr; 3780 }); 3781 3782 return !ContainsNulls; 3783 } 3784 3785 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3786 HasRecMapType::iterator I = HasRecMap.find(S); 3787 if (I != HasRecMap.end()) 3788 return I->second; 3789 3790 bool FoundAddRec = 3791 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3792 HasRecMap.insert({S, FoundAddRec}); 3793 return FoundAddRec; 3794 } 3795 3796 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3797 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3798 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3799 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3800 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3801 if (!Add) 3802 return {S, nullptr}; 3803 3804 if (Add->getNumOperands() != 2) 3805 return {S, nullptr}; 3806 3807 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3808 if (!ConstOp) 3809 return {S, nullptr}; 3810 3811 return {Add->getOperand(1), ConstOp->getValue()}; 3812 } 3813 3814 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3815 /// by the value and offset from any ValueOffsetPair in the set. 3816 SetVector<ScalarEvolution::ValueOffsetPair> * 3817 ScalarEvolution::getSCEVValues(const SCEV *S) { 3818 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3819 if (SI == ExprValueMap.end()) 3820 return nullptr; 3821 #ifndef NDEBUG 3822 if (VerifySCEVMap) { 3823 // Check there is no dangling Value in the set returned. 3824 for (const auto &VE : SI->second) 3825 assert(ValueExprMap.count(VE.first)); 3826 } 3827 #endif 3828 return &SI->second; 3829 } 3830 3831 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3832 /// cannot be used separately. eraseValueFromMap should be used to remove 3833 /// V from ValueExprMap and ExprValueMap at the same time. 3834 void ScalarEvolution::eraseValueFromMap(Value *V) { 3835 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3836 if (I != ValueExprMap.end()) { 3837 const SCEV *S = I->second; 3838 // Remove {V, 0} from the set of ExprValueMap[S] 3839 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3840 SV->remove({V, nullptr}); 3841 3842 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3843 const SCEV *Stripped; 3844 ConstantInt *Offset; 3845 std::tie(Stripped, Offset) = splitAddExpr(S); 3846 if (Offset != nullptr) { 3847 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3848 SV->remove({V, Offset}); 3849 } 3850 ValueExprMap.erase(V); 3851 } 3852 } 3853 3854 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3855 /// TODO: In reality it is better to check the poison recursively 3856 /// but this is better than nothing. 3857 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3858 if (auto *I = dyn_cast<Instruction>(V)) { 3859 if (isa<OverflowingBinaryOperator>(I)) { 3860 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3861 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3862 return true; 3863 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3864 return true; 3865 } 3866 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3867 return true; 3868 } 3869 return false; 3870 } 3871 3872 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3873 /// create a new one. 3874 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3875 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3876 3877 const SCEV *S = getExistingSCEV(V); 3878 if (S == nullptr) { 3879 S = createSCEV(V); 3880 // During PHI resolution, it is possible to create two SCEVs for the same 3881 // V, so it is needed to double check whether V->S is inserted into 3882 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3883 std::pair<ValueExprMapType::iterator, bool> Pair = 3884 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3885 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3886 ExprValueMap[S].insert({V, nullptr}); 3887 3888 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3889 // ExprValueMap. 3890 const SCEV *Stripped = S; 3891 ConstantInt *Offset = nullptr; 3892 std::tie(Stripped, Offset) = splitAddExpr(S); 3893 // If stripped is SCEVUnknown, don't bother to save 3894 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3895 // increase the complexity of the expansion code. 3896 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3897 // because it may generate add/sub instead of GEP in SCEV expansion. 3898 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3899 !isa<GetElementPtrInst>(V)) 3900 ExprValueMap[Stripped].insert({V, Offset}); 3901 } 3902 } 3903 return S; 3904 } 3905 3906 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3907 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3908 3909 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3910 if (I != ValueExprMap.end()) { 3911 const SCEV *S = I->second; 3912 if (checkValidity(S)) 3913 return S; 3914 eraseValueFromMap(V); 3915 forgetMemoizedResults(S); 3916 } 3917 return nullptr; 3918 } 3919 3920 /// Return a SCEV corresponding to -V = -1*V 3921 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3922 SCEV::NoWrapFlags Flags) { 3923 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3924 return getConstant( 3925 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3926 3927 Type *Ty = V->getType(); 3928 Ty = getEffectiveSCEVType(Ty); 3929 return getMulExpr(V, getMinusOne(Ty), Flags); 3930 } 3931 3932 /// If Expr computes ~A, return A else return nullptr 3933 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3934 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3935 if (!Add || Add->getNumOperands() != 2 || 3936 !Add->getOperand(0)->isAllOnesValue()) 3937 return nullptr; 3938 3939 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3940 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3941 !AddRHS->getOperand(0)->isAllOnesValue()) 3942 return nullptr; 3943 3944 return AddRHS->getOperand(1); 3945 } 3946 3947 /// Return a SCEV corresponding to ~V = -1-V 3948 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3949 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3950 return getConstant( 3951 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3952 3953 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3954 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3955 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3956 SmallVector<const SCEV *, 2> MatchedOperands; 3957 for (const SCEV *Operand : MME->operands()) { 3958 const SCEV *Matched = MatchNotExpr(Operand); 3959 if (!Matched) 3960 return (const SCEV *)nullptr; 3961 MatchedOperands.push_back(Matched); 3962 } 3963 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3964 MatchedOperands); 3965 }; 3966 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3967 return Replaced; 3968 } 3969 3970 Type *Ty = V->getType(); 3971 Ty = getEffectiveSCEVType(Ty); 3972 return getMinusSCEV(getMinusOne(Ty), V); 3973 } 3974 3975 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3976 SCEV::NoWrapFlags Flags, 3977 unsigned Depth) { 3978 // Fast path: X - X --> 0. 3979 if (LHS == RHS) 3980 return getZero(LHS->getType()); 3981 3982 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3983 // makes it so that we cannot make much use of NUW. 3984 auto AddFlags = SCEV::FlagAnyWrap; 3985 const bool RHSIsNotMinSigned = 3986 !getSignedRangeMin(RHS).isMinSignedValue(); 3987 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3988 // Let M be the minimum representable signed value. Then (-1)*RHS 3989 // signed-wraps if and only if RHS is M. That can happen even for 3990 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3991 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3992 // (-1)*RHS, we need to prove that RHS != M. 3993 // 3994 // If LHS is non-negative and we know that LHS - RHS does not 3995 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3996 // either by proving that RHS > M or that LHS >= 0. 3997 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3998 AddFlags = SCEV::FlagNSW; 3999 } 4000 } 4001 4002 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4003 // RHS is NSW and LHS >= 0. 4004 // 4005 // The difficulty here is that the NSW flag may have been proven 4006 // relative to a loop that is to be found in a recurrence in LHS and 4007 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4008 // larger scope than intended. 4009 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4010 4011 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4012 } 4013 4014 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4015 unsigned Depth) { 4016 Type *SrcTy = V->getType(); 4017 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4018 "Cannot truncate or zero extend with non-integer arguments!"); 4019 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4020 return V; // No conversion 4021 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4022 return getTruncateExpr(V, Ty, Depth); 4023 return getZeroExtendExpr(V, Ty, Depth); 4024 } 4025 4026 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4027 unsigned Depth) { 4028 Type *SrcTy = V->getType(); 4029 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4030 "Cannot truncate or zero extend with non-integer arguments!"); 4031 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4032 return V; // No conversion 4033 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4034 return getTruncateExpr(V, Ty, Depth); 4035 return getSignExtendExpr(V, Ty, Depth); 4036 } 4037 4038 const SCEV * 4039 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4040 Type *SrcTy = V->getType(); 4041 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4042 "Cannot noop or zero extend with non-integer arguments!"); 4043 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4044 "getNoopOrZeroExtend cannot truncate!"); 4045 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4046 return V; // No conversion 4047 return getZeroExtendExpr(V, Ty); 4048 } 4049 4050 const SCEV * 4051 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4052 Type *SrcTy = V->getType(); 4053 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4054 "Cannot noop or sign extend with non-integer arguments!"); 4055 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4056 "getNoopOrSignExtend cannot truncate!"); 4057 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4058 return V; // No conversion 4059 return getSignExtendExpr(V, Ty); 4060 } 4061 4062 const SCEV * 4063 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4064 Type *SrcTy = V->getType(); 4065 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4066 "Cannot noop or any extend with non-integer arguments!"); 4067 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4068 "getNoopOrAnyExtend cannot truncate!"); 4069 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4070 return V; // No conversion 4071 return getAnyExtendExpr(V, Ty); 4072 } 4073 4074 const SCEV * 4075 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4076 Type *SrcTy = V->getType(); 4077 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4078 "Cannot truncate or noop with non-integer arguments!"); 4079 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4080 "getTruncateOrNoop cannot extend!"); 4081 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4082 return V; // No conversion 4083 return getTruncateExpr(V, Ty); 4084 } 4085 4086 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4087 const SCEV *RHS) { 4088 const SCEV *PromotedLHS = LHS; 4089 const SCEV *PromotedRHS = RHS; 4090 4091 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4092 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4093 else 4094 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4095 4096 return getUMaxExpr(PromotedLHS, PromotedRHS); 4097 } 4098 4099 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4100 const SCEV *RHS) { 4101 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4102 return getUMinFromMismatchedTypes(Ops); 4103 } 4104 4105 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4106 SmallVectorImpl<const SCEV *> &Ops) { 4107 assert(!Ops.empty() && "At least one operand must be!"); 4108 // Trivial case. 4109 if (Ops.size() == 1) 4110 return Ops[0]; 4111 4112 // Find the max type first. 4113 Type *MaxType = nullptr; 4114 for (auto *S : Ops) 4115 if (MaxType) 4116 MaxType = getWiderType(MaxType, S->getType()); 4117 else 4118 MaxType = S->getType(); 4119 assert(MaxType && "Failed to find maximum type!"); 4120 4121 // Extend all ops to max type. 4122 SmallVector<const SCEV *, 2> PromotedOps; 4123 for (auto *S : Ops) 4124 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4125 4126 // Generate umin. 4127 return getUMinExpr(PromotedOps); 4128 } 4129 4130 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4131 // A pointer operand may evaluate to a nonpointer expression, such as null. 4132 if (!V->getType()->isPointerTy()) 4133 return V; 4134 4135 while (true) { 4136 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4137 V = Cast->getOperand(); 4138 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4139 const SCEV *PtrOp = nullptr; 4140 for (const SCEV *NAryOp : NAry->operands()) { 4141 if (NAryOp->getType()->isPointerTy()) { 4142 // Cannot find the base of an expression with multiple pointer ops. 4143 if (PtrOp) 4144 return V; 4145 PtrOp = NAryOp; 4146 } 4147 } 4148 if (!PtrOp) // All operands were non-pointer. 4149 return V; 4150 V = PtrOp; 4151 } else // Not something we can look further into. 4152 return V; 4153 } 4154 } 4155 4156 /// Push users of the given Instruction onto the given Worklist. 4157 static void 4158 PushDefUseChildren(Instruction *I, 4159 SmallVectorImpl<Instruction *> &Worklist) { 4160 // Push the def-use children onto the Worklist stack. 4161 for (User *U : I->users()) 4162 Worklist.push_back(cast<Instruction>(U)); 4163 } 4164 4165 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4166 SmallVector<Instruction *, 16> Worklist; 4167 PushDefUseChildren(PN, Worklist); 4168 4169 SmallPtrSet<Instruction *, 8> Visited; 4170 Visited.insert(PN); 4171 while (!Worklist.empty()) { 4172 Instruction *I = Worklist.pop_back_val(); 4173 if (!Visited.insert(I).second) 4174 continue; 4175 4176 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4177 if (It != ValueExprMap.end()) { 4178 const SCEV *Old = It->second; 4179 4180 // Short-circuit the def-use traversal if the symbolic name 4181 // ceases to appear in expressions. 4182 if (Old != SymName && !hasOperand(Old, SymName)) 4183 continue; 4184 4185 // SCEVUnknown for a PHI either means that it has an unrecognized 4186 // structure, it's a PHI that's in the progress of being computed 4187 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4188 // additional loop trip count information isn't going to change anything. 4189 // In the second case, createNodeForPHI will perform the necessary 4190 // updates on its own when it gets to that point. In the third, we do 4191 // want to forget the SCEVUnknown. 4192 if (!isa<PHINode>(I) || 4193 !isa<SCEVUnknown>(Old) || 4194 (I != PN && Old == SymName)) { 4195 eraseValueFromMap(It->first); 4196 forgetMemoizedResults(Old); 4197 } 4198 } 4199 4200 PushDefUseChildren(I, Worklist); 4201 } 4202 } 4203 4204 namespace { 4205 4206 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4207 /// expression in case its Loop is L. If it is not L then 4208 /// if IgnoreOtherLoops is true then use AddRec itself 4209 /// otherwise rewrite cannot be done. 4210 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4211 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4212 public: 4213 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4214 bool IgnoreOtherLoops = true) { 4215 SCEVInitRewriter Rewriter(L, SE); 4216 const SCEV *Result = Rewriter.visit(S); 4217 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4218 return SE.getCouldNotCompute(); 4219 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4220 ? SE.getCouldNotCompute() 4221 : Result; 4222 } 4223 4224 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4225 if (!SE.isLoopInvariant(Expr, L)) 4226 SeenLoopVariantSCEVUnknown = true; 4227 return Expr; 4228 } 4229 4230 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4231 // Only re-write AddRecExprs for this loop. 4232 if (Expr->getLoop() == L) 4233 return Expr->getStart(); 4234 SeenOtherLoops = true; 4235 return Expr; 4236 } 4237 4238 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4239 4240 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4241 4242 private: 4243 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4244 : SCEVRewriteVisitor(SE), L(L) {} 4245 4246 const Loop *L; 4247 bool SeenLoopVariantSCEVUnknown = false; 4248 bool SeenOtherLoops = false; 4249 }; 4250 4251 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4252 /// increment expression in case its Loop is L. If it is not L then 4253 /// use AddRec itself. 4254 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4255 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4256 public: 4257 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4258 SCEVPostIncRewriter Rewriter(L, SE); 4259 const SCEV *Result = Rewriter.visit(S); 4260 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4261 ? SE.getCouldNotCompute() 4262 : Result; 4263 } 4264 4265 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4266 if (!SE.isLoopInvariant(Expr, L)) 4267 SeenLoopVariantSCEVUnknown = true; 4268 return Expr; 4269 } 4270 4271 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4272 // Only re-write AddRecExprs for this loop. 4273 if (Expr->getLoop() == L) 4274 return Expr->getPostIncExpr(SE); 4275 SeenOtherLoops = true; 4276 return Expr; 4277 } 4278 4279 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4280 4281 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4282 4283 private: 4284 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4285 : SCEVRewriteVisitor(SE), L(L) {} 4286 4287 const Loop *L; 4288 bool SeenLoopVariantSCEVUnknown = false; 4289 bool SeenOtherLoops = false; 4290 }; 4291 4292 /// This class evaluates the compare condition by matching it against the 4293 /// condition of loop latch. If there is a match we assume a true value 4294 /// for the condition while building SCEV nodes. 4295 class SCEVBackedgeConditionFolder 4296 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4297 public: 4298 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4299 ScalarEvolution &SE) { 4300 bool IsPosBECond = false; 4301 Value *BECond = nullptr; 4302 if (BasicBlock *Latch = L->getLoopLatch()) { 4303 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4304 if (BI && BI->isConditional()) { 4305 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4306 "Both outgoing branches should not target same header!"); 4307 BECond = BI->getCondition(); 4308 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4309 } else { 4310 return S; 4311 } 4312 } 4313 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4314 return Rewriter.visit(S); 4315 } 4316 4317 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4318 const SCEV *Result = Expr; 4319 bool InvariantF = SE.isLoopInvariant(Expr, L); 4320 4321 if (!InvariantF) { 4322 Instruction *I = cast<Instruction>(Expr->getValue()); 4323 switch (I->getOpcode()) { 4324 case Instruction::Select: { 4325 SelectInst *SI = cast<SelectInst>(I); 4326 Optional<const SCEV *> Res = 4327 compareWithBackedgeCondition(SI->getCondition()); 4328 if (Res.hasValue()) { 4329 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4330 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4331 } 4332 break; 4333 } 4334 default: { 4335 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4336 if (Res.hasValue()) 4337 Result = Res.getValue(); 4338 break; 4339 } 4340 } 4341 } 4342 return Result; 4343 } 4344 4345 private: 4346 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4347 bool IsPosBECond, ScalarEvolution &SE) 4348 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4349 IsPositiveBECond(IsPosBECond) {} 4350 4351 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4352 4353 const Loop *L; 4354 /// Loop back condition. 4355 Value *BackedgeCond = nullptr; 4356 /// Set to true if loop back is on positive branch condition. 4357 bool IsPositiveBECond; 4358 }; 4359 4360 Optional<const SCEV *> 4361 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4362 4363 // If value matches the backedge condition for loop latch, 4364 // then return a constant evolution node based on loopback 4365 // branch taken. 4366 if (BackedgeCond == IC) 4367 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4368 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4369 return None; 4370 } 4371 4372 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4373 public: 4374 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4375 ScalarEvolution &SE) { 4376 SCEVShiftRewriter Rewriter(L, SE); 4377 const SCEV *Result = Rewriter.visit(S); 4378 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4379 } 4380 4381 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4382 // Only allow AddRecExprs for this loop. 4383 if (!SE.isLoopInvariant(Expr, L)) 4384 Valid = false; 4385 return Expr; 4386 } 4387 4388 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4389 if (Expr->getLoop() == L && Expr->isAffine()) 4390 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4391 Valid = false; 4392 return Expr; 4393 } 4394 4395 bool isValid() { return Valid; } 4396 4397 private: 4398 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4399 : SCEVRewriteVisitor(SE), L(L) {} 4400 4401 const Loop *L; 4402 bool Valid = true; 4403 }; 4404 4405 } // end anonymous namespace 4406 4407 SCEV::NoWrapFlags 4408 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4409 if (!AR->isAffine()) 4410 return SCEV::FlagAnyWrap; 4411 4412 using OBO = OverflowingBinaryOperator; 4413 4414 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4415 4416 if (!AR->hasNoSignedWrap()) { 4417 ConstantRange AddRecRange = getSignedRange(AR); 4418 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4419 4420 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4421 Instruction::Add, IncRange, OBO::NoSignedWrap); 4422 if (NSWRegion.contains(AddRecRange)) 4423 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4424 } 4425 4426 if (!AR->hasNoUnsignedWrap()) { 4427 ConstantRange AddRecRange = getUnsignedRange(AR); 4428 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4429 4430 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4431 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4432 if (NUWRegion.contains(AddRecRange)) 4433 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4434 } 4435 4436 return Result; 4437 } 4438 4439 namespace { 4440 4441 /// Represents an abstract binary operation. This may exist as a 4442 /// normal instruction or constant expression, or may have been 4443 /// derived from an expression tree. 4444 struct BinaryOp { 4445 unsigned Opcode; 4446 Value *LHS; 4447 Value *RHS; 4448 bool IsNSW = false; 4449 bool IsNUW = false; 4450 bool IsExact = false; 4451 4452 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4453 /// constant expression. 4454 Operator *Op = nullptr; 4455 4456 explicit BinaryOp(Operator *Op) 4457 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4458 Op(Op) { 4459 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4460 IsNSW = OBO->hasNoSignedWrap(); 4461 IsNUW = OBO->hasNoUnsignedWrap(); 4462 } 4463 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4464 IsExact = PEO->isExact(); 4465 } 4466 4467 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4468 bool IsNUW = false, bool IsExact = false) 4469 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4470 IsExact(IsExact) {} 4471 }; 4472 4473 } // end anonymous namespace 4474 4475 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4476 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4477 auto *Op = dyn_cast<Operator>(V); 4478 if (!Op) 4479 return None; 4480 4481 // Implementation detail: all the cleverness here should happen without 4482 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4483 // SCEV expressions when possible, and we should not break that. 4484 4485 switch (Op->getOpcode()) { 4486 case Instruction::Add: 4487 case Instruction::Sub: 4488 case Instruction::Mul: 4489 case Instruction::UDiv: 4490 case Instruction::URem: 4491 case Instruction::And: 4492 case Instruction::Or: 4493 case Instruction::AShr: 4494 case Instruction::Shl: 4495 return BinaryOp(Op); 4496 4497 case Instruction::Xor: 4498 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4499 // If the RHS of the xor is a signmask, then this is just an add. 4500 // Instcombine turns add of signmask into xor as a strength reduction step. 4501 if (RHSC->getValue().isSignMask()) 4502 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4503 return BinaryOp(Op); 4504 4505 case Instruction::LShr: 4506 // Turn logical shift right of a constant into a unsigned divide. 4507 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4508 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4509 4510 // If the shift count is not less than the bitwidth, the result of 4511 // the shift is undefined. Don't try to analyze it, because the 4512 // resolution chosen here may differ from the resolution chosen in 4513 // other parts of the compiler. 4514 if (SA->getValue().ult(BitWidth)) { 4515 Constant *X = 4516 ConstantInt::get(SA->getContext(), 4517 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4518 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4519 } 4520 } 4521 return BinaryOp(Op); 4522 4523 case Instruction::ExtractValue: { 4524 auto *EVI = cast<ExtractValueInst>(Op); 4525 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4526 break; 4527 4528 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4529 if (!WO) 4530 break; 4531 4532 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4533 bool Signed = WO->isSigned(); 4534 // TODO: Should add nuw/nsw flags for mul as well. 4535 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4536 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4537 4538 // Now that we know that all uses of the arithmetic-result component of 4539 // CI are guarded by the overflow check, we can go ahead and pretend 4540 // that the arithmetic is non-overflowing. 4541 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4542 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4543 } 4544 4545 default: 4546 break; 4547 } 4548 4549 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4550 // semantics as a Sub, return a binary sub expression. 4551 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4552 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4553 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4554 4555 return None; 4556 } 4557 4558 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4559 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4560 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4561 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4562 /// follows one of the following patterns: 4563 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4564 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4565 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4566 /// we return the type of the truncation operation, and indicate whether the 4567 /// truncated type should be treated as signed/unsigned by setting 4568 /// \p Signed to true/false, respectively. 4569 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4570 bool &Signed, ScalarEvolution &SE) { 4571 // The case where Op == SymbolicPHI (that is, with no type conversions on 4572 // the way) is handled by the regular add recurrence creating logic and 4573 // would have already been triggered in createAddRecForPHI. Reaching it here 4574 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4575 // because one of the other operands of the SCEVAddExpr updating this PHI is 4576 // not invariant). 4577 // 4578 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4579 // this case predicates that allow us to prove that Op == SymbolicPHI will 4580 // be added. 4581 if (Op == SymbolicPHI) 4582 return nullptr; 4583 4584 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4585 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4586 if (SourceBits != NewBits) 4587 return nullptr; 4588 4589 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4590 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4591 if (!SExt && !ZExt) 4592 return nullptr; 4593 const SCEVTruncateExpr *Trunc = 4594 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4595 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4596 if (!Trunc) 4597 return nullptr; 4598 const SCEV *X = Trunc->getOperand(); 4599 if (X != SymbolicPHI) 4600 return nullptr; 4601 Signed = SExt != nullptr; 4602 return Trunc->getType(); 4603 } 4604 4605 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4606 if (!PN->getType()->isIntegerTy()) 4607 return nullptr; 4608 const Loop *L = LI.getLoopFor(PN->getParent()); 4609 if (!L || L->getHeader() != PN->getParent()) 4610 return nullptr; 4611 return L; 4612 } 4613 4614 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4615 // computation that updates the phi follows the following pattern: 4616 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4617 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4618 // If so, try to see if it can be rewritten as an AddRecExpr under some 4619 // Predicates. If successful, return them as a pair. Also cache the results 4620 // of the analysis. 4621 // 4622 // Example usage scenario: 4623 // Say the Rewriter is called for the following SCEV: 4624 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4625 // where: 4626 // %X = phi i64 (%Start, %BEValue) 4627 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4628 // and call this function with %SymbolicPHI = %X. 4629 // 4630 // The analysis will find that the value coming around the backedge has 4631 // the following SCEV: 4632 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4633 // Upon concluding that this matches the desired pattern, the function 4634 // will return the pair {NewAddRec, SmallPredsVec} where: 4635 // NewAddRec = {%Start,+,%Step} 4636 // SmallPredsVec = {P1, P2, P3} as follows: 4637 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4638 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4639 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4640 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4641 // under the predicates {P1,P2,P3}. 4642 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4643 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4644 // 4645 // TODO's: 4646 // 4647 // 1) Extend the Induction descriptor to also support inductions that involve 4648 // casts: When needed (namely, when we are called in the context of the 4649 // vectorizer induction analysis), a Set of cast instructions will be 4650 // populated by this method, and provided back to isInductionPHI. This is 4651 // needed to allow the vectorizer to properly record them to be ignored by 4652 // the cost model and to avoid vectorizing them (otherwise these casts, 4653 // which are redundant under the runtime overflow checks, will be 4654 // vectorized, which can be costly). 4655 // 4656 // 2) Support additional induction/PHISCEV patterns: We also want to support 4657 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4658 // after the induction update operation (the induction increment): 4659 // 4660 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4661 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4662 // 4663 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4664 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4665 // 4666 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4667 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4668 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4669 SmallVector<const SCEVPredicate *, 3> Predicates; 4670 4671 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4672 // return an AddRec expression under some predicate. 4673 4674 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4675 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4676 assert(L && "Expecting an integer loop header phi"); 4677 4678 // The loop may have multiple entrances or multiple exits; we can analyze 4679 // this phi as an addrec if it has a unique entry value and a unique 4680 // backedge value. 4681 Value *BEValueV = nullptr, *StartValueV = nullptr; 4682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4683 Value *V = PN->getIncomingValue(i); 4684 if (L->contains(PN->getIncomingBlock(i))) { 4685 if (!BEValueV) { 4686 BEValueV = V; 4687 } else if (BEValueV != V) { 4688 BEValueV = nullptr; 4689 break; 4690 } 4691 } else if (!StartValueV) { 4692 StartValueV = V; 4693 } else if (StartValueV != V) { 4694 StartValueV = nullptr; 4695 break; 4696 } 4697 } 4698 if (!BEValueV || !StartValueV) 4699 return None; 4700 4701 const SCEV *BEValue = getSCEV(BEValueV); 4702 4703 // If the value coming around the backedge is an add with the symbolic 4704 // value we just inserted, possibly with casts that we can ignore under 4705 // an appropriate runtime guard, then we found a simple induction variable! 4706 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4707 if (!Add) 4708 return None; 4709 4710 // If there is a single occurrence of the symbolic value, possibly 4711 // casted, replace it with a recurrence. 4712 unsigned FoundIndex = Add->getNumOperands(); 4713 Type *TruncTy = nullptr; 4714 bool Signed; 4715 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4716 if ((TruncTy = 4717 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4718 if (FoundIndex == e) { 4719 FoundIndex = i; 4720 break; 4721 } 4722 4723 if (FoundIndex == Add->getNumOperands()) 4724 return None; 4725 4726 // Create an add with everything but the specified operand. 4727 SmallVector<const SCEV *, 8> Ops; 4728 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4729 if (i != FoundIndex) 4730 Ops.push_back(Add->getOperand(i)); 4731 const SCEV *Accum = getAddExpr(Ops); 4732 4733 // The runtime checks will not be valid if the step amount is 4734 // varying inside the loop. 4735 if (!isLoopInvariant(Accum, L)) 4736 return None; 4737 4738 // *** Part2: Create the predicates 4739 4740 // Analysis was successful: we have a phi-with-cast pattern for which we 4741 // can return an AddRec expression under the following predicates: 4742 // 4743 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4744 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4745 // P2: An Equal predicate that guarantees that 4746 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4747 // P3: An Equal predicate that guarantees that 4748 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4749 // 4750 // As we next prove, the above predicates guarantee that: 4751 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4752 // 4753 // 4754 // More formally, we want to prove that: 4755 // Expr(i+1) = Start + (i+1) * Accum 4756 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4757 // 4758 // Given that: 4759 // 1) Expr(0) = Start 4760 // 2) Expr(1) = Start + Accum 4761 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4762 // 3) Induction hypothesis (step i): 4763 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4764 // 4765 // Proof: 4766 // Expr(i+1) = 4767 // = Start + (i+1)*Accum 4768 // = (Start + i*Accum) + Accum 4769 // = Expr(i) + Accum 4770 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4771 // :: from step i 4772 // 4773 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4774 // 4775 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4776 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4777 // + Accum :: from P3 4778 // 4779 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4780 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4781 // 4782 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4783 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4784 // 4785 // By induction, the same applies to all iterations 1<=i<n: 4786 // 4787 4788 // Create a truncated addrec for which we will add a no overflow check (P1). 4789 const SCEV *StartVal = getSCEV(StartValueV); 4790 const SCEV *PHISCEV = 4791 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4792 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4793 4794 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4795 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4796 // will be constant. 4797 // 4798 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4799 // add P1. 4800 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4801 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4802 Signed ? SCEVWrapPredicate::IncrementNSSW 4803 : SCEVWrapPredicate::IncrementNUSW; 4804 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4805 Predicates.push_back(AddRecPred); 4806 } 4807 4808 // Create the Equal Predicates P2,P3: 4809 4810 // It is possible that the predicates P2 and/or P3 are computable at 4811 // compile time due to StartVal and/or Accum being constants. 4812 // If either one is, then we can check that now and escape if either P2 4813 // or P3 is false. 4814 4815 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4816 // for each of StartVal and Accum 4817 auto getExtendedExpr = [&](const SCEV *Expr, 4818 bool CreateSignExtend) -> const SCEV * { 4819 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4820 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4821 const SCEV *ExtendedExpr = 4822 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4823 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4824 return ExtendedExpr; 4825 }; 4826 4827 // Given: 4828 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4829 // = getExtendedExpr(Expr) 4830 // Determine whether the predicate P: Expr == ExtendedExpr 4831 // is known to be false at compile time 4832 auto PredIsKnownFalse = [&](const SCEV *Expr, 4833 const SCEV *ExtendedExpr) -> bool { 4834 return Expr != ExtendedExpr && 4835 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4836 }; 4837 4838 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4839 if (PredIsKnownFalse(StartVal, StartExtended)) { 4840 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4841 return None; 4842 } 4843 4844 // The Step is always Signed (because the overflow checks are either 4845 // NSSW or NUSW) 4846 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4847 if (PredIsKnownFalse(Accum, AccumExtended)) { 4848 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4849 return None; 4850 } 4851 4852 auto AppendPredicate = [&](const SCEV *Expr, 4853 const SCEV *ExtendedExpr) -> void { 4854 if (Expr != ExtendedExpr && 4855 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4856 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4857 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4858 Predicates.push_back(Pred); 4859 } 4860 }; 4861 4862 AppendPredicate(StartVal, StartExtended); 4863 AppendPredicate(Accum, AccumExtended); 4864 4865 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4866 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4867 // into NewAR if it will also add the runtime overflow checks specified in 4868 // Predicates. 4869 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4870 4871 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4872 std::make_pair(NewAR, Predicates); 4873 // Remember the result of the analysis for this SCEV at this locayyytion. 4874 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4875 return PredRewrite; 4876 } 4877 4878 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4879 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4880 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4881 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4882 if (!L) 4883 return None; 4884 4885 // Check to see if we already analyzed this PHI. 4886 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4887 if (I != PredicatedSCEVRewrites.end()) { 4888 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4889 I->second; 4890 // Analysis was done before and failed to create an AddRec: 4891 if (Rewrite.first == SymbolicPHI) 4892 return None; 4893 // Analysis was done before and succeeded to create an AddRec under 4894 // a predicate: 4895 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4896 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4897 return Rewrite; 4898 } 4899 4900 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4901 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4902 4903 // Record in the cache that the analysis failed 4904 if (!Rewrite) { 4905 SmallVector<const SCEVPredicate *, 3> Predicates; 4906 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4907 return None; 4908 } 4909 4910 return Rewrite; 4911 } 4912 4913 // FIXME: This utility is currently required because the Rewriter currently 4914 // does not rewrite this expression: 4915 // {0, +, (sext ix (trunc iy to ix) to iy)} 4916 // into {0, +, %step}, 4917 // even when the following Equal predicate exists: 4918 // "%step == (sext ix (trunc iy to ix) to iy)". 4919 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4920 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4921 if (AR1 == AR2) 4922 return true; 4923 4924 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4925 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4926 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4927 return false; 4928 return true; 4929 }; 4930 4931 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4932 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4933 return false; 4934 return true; 4935 } 4936 4937 /// A helper function for createAddRecFromPHI to handle simple cases. 4938 /// 4939 /// This function tries to find an AddRec expression for the simplest (yet most 4940 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4941 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4942 /// technique for finding the AddRec expression. 4943 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4944 Value *BEValueV, 4945 Value *StartValueV) { 4946 const Loop *L = LI.getLoopFor(PN->getParent()); 4947 assert(L && L->getHeader() == PN->getParent()); 4948 assert(BEValueV && StartValueV); 4949 4950 auto BO = MatchBinaryOp(BEValueV, DT); 4951 if (!BO) 4952 return nullptr; 4953 4954 if (BO->Opcode != Instruction::Add) 4955 return nullptr; 4956 4957 const SCEV *Accum = nullptr; 4958 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4959 Accum = getSCEV(BO->RHS); 4960 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4961 Accum = getSCEV(BO->LHS); 4962 4963 if (!Accum) 4964 return nullptr; 4965 4966 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4967 if (BO->IsNUW) 4968 Flags = setFlags(Flags, SCEV::FlagNUW); 4969 if (BO->IsNSW) 4970 Flags = setFlags(Flags, SCEV::FlagNSW); 4971 4972 const SCEV *StartVal = getSCEV(StartValueV); 4973 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4974 4975 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4976 4977 // We can add Flags to the post-inc expression only if we 4978 // know that it is *undefined behavior* for BEValueV to 4979 // overflow. 4980 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4981 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4982 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4983 4984 return PHISCEV; 4985 } 4986 4987 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4988 const Loop *L = LI.getLoopFor(PN->getParent()); 4989 if (!L || L->getHeader() != PN->getParent()) 4990 return nullptr; 4991 4992 // The loop may have multiple entrances or multiple exits; we can analyze 4993 // this phi as an addrec if it has a unique entry value and a unique 4994 // backedge value. 4995 Value *BEValueV = nullptr, *StartValueV = nullptr; 4996 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4997 Value *V = PN->getIncomingValue(i); 4998 if (L->contains(PN->getIncomingBlock(i))) { 4999 if (!BEValueV) { 5000 BEValueV = V; 5001 } else if (BEValueV != V) { 5002 BEValueV = nullptr; 5003 break; 5004 } 5005 } else if (!StartValueV) { 5006 StartValueV = V; 5007 } else if (StartValueV != V) { 5008 StartValueV = nullptr; 5009 break; 5010 } 5011 } 5012 if (!BEValueV || !StartValueV) 5013 return nullptr; 5014 5015 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5016 "PHI node already processed?"); 5017 5018 // First, try to find AddRec expression without creating a fictituos symbolic 5019 // value for PN. 5020 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5021 return S; 5022 5023 // Handle PHI node value symbolically. 5024 const SCEV *SymbolicName = getUnknown(PN); 5025 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5026 5027 // Using this symbolic name for the PHI, analyze the value coming around 5028 // the back-edge. 5029 const SCEV *BEValue = getSCEV(BEValueV); 5030 5031 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5032 // has a special value for the first iteration of the loop. 5033 5034 // If the value coming around the backedge is an add with the symbolic 5035 // value we just inserted, then we found a simple induction variable! 5036 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5037 // If there is a single occurrence of the symbolic value, replace it 5038 // with a recurrence. 5039 unsigned FoundIndex = Add->getNumOperands(); 5040 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5041 if (Add->getOperand(i) == SymbolicName) 5042 if (FoundIndex == e) { 5043 FoundIndex = i; 5044 break; 5045 } 5046 5047 if (FoundIndex != Add->getNumOperands()) { 5048 // Create an add with everything but the specified operand. 5049 SmallVector<const SCEV *, 8> Ops; 5050 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5051 if (i != FoundIndex) 5052 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5053 L, *this)); 5054 const SCEV *Accum = getAddExpr(Ops); 5055 5056 // This is not a valid addrec if the step amount is varying each 5057 // loop iteration, but is not itself an addrec in this loop. 5058 if (isLoopInvariant(Accum, L) || 5059 (isa<SCEVAddRecExpr>(Accum) && 5060 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5061 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5062 5063 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5064 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5065 if (BO->IsNUW) 5066 Flags = setFlags(Flags, SCEV::FlagNUW); 5067 if (BO->IsNSW) 5068 Flags = setFlags(Flags, SCEV::FlagNSW); 5069 } 5070 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5071 // If the increment is an inbounds GEP, then we know the address 5072 // space cannot be wrapped around. We cannot make any guarantee 5073 // about signed or unsigned overflow because pointers are 5074 // unsigned but we may have a negative index from the base 5075 // pointer. We can guarantee that no unsigned wrap occurs if the 5076 // indices form a positive value. 5077 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5078 Flags = setFlags(Flags, SCEV::FlagNW); 5079 5080 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5081 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5082 Flags = setFlags(Flags, SCEV::FlagNUW); 5083 } 5084 5085 // We cannot transfer nuw and nsw flags from subtraction 5086 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5087 // for instance. 5088 } 5089 5090 const SCEV *StartVal = getSCEV(StartValueV); 5091 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5092 5093 // Okay, for the entire analysis of this edge we assumed the PHI 5094 // to be symbolic. We now need to go back and purge all of the 5095 // entries for the scalars that use the symbolic expression. 5096 forgetSymbolicName(PN, SymbolicName); 5097 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5098 5099 // We can add Flags to the post-inc expression only if we 5100 // know that it is *undefined behavior* for BEValueV to 5101 // overflow. 5102 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5103 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5104 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5105 5106 return PHISCEV; 5107 } 5108 } 5109 } else { 5110 // Otherwise, this could be a loop like this: 5111 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5112 // In this case, j = {1,+,1} and BEValue is j. 5113 // Because the other in-value of i (0) fits the evolution of BEValue 5114 // i really is an addrec evolution. 5115 // 5116 // We can generalize this saying that i is the shifted value of BEValue 5117 // by one iteration: 5118 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5119 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5120 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5121 if (Shifted != getCouldNotCompute() && 5122 Start != getCouldNotCompute()) { 5123 const SCEV *StartVal = getSCEV(StartValueV); 5124 if (Start == StartVal) { 5125 // Okay, for the entire analysis of this edge we assumed the PHI 5126 // to be symbolic. We now need to go back and purge all of the 5127 // entries for the scalars that use the symbolic expression. 5128 forgetSymbolicName(PN, SymbolicName); 5129 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5130 return Shifted; 5131 } 5132 } 5133 } 5134 5135 // Remove the temporary PHI node SCEV that has been inserted while intending 5136 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5137 // as it will prevent later (possibly simpler) SCEV expressions to be added 5138 // to the ValueExprMap. 5139 eraseValueFromMap(PN); 5140 5141 return nullptr; 5142 } 5143 5144 // Checks if the SCEV S is available at BB. S is considered available at BB 5145 // if S can be materialized at BB without introducing a fault. 5146 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5147 BasicBlock *BB) { 5148 struct CheckAvailable { 5149 bool TraversalDone = false; 5150 bool Available = true; 5151 5152 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5153 BasicBlock *BB = nullptr; 5154 DominatorTree &DT; 5155 5156 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5157 : L(L), BB(BB), DT(DT) {} 5158 5159 bool setUnavailable() { 5160 TraversalDone = true; 5161 Available = false; 5162 return false; 5163 } 5164 5165 bool follow(const SCEV *S) { 5166 switch (S->getSCEVType()) { 5167 case scConstant: 5168 case scPtrToInt: 5169 case scTruncate: 5170 case scZeroExtend: 5171 case scSignExtend: 5172 case scAddExpr: 5173 case scMulExpr: 5174 case scUMaxExpr: 5175 case scSMaxExpr: 5176 case scUMinExpr: 5177 case scSMinExpr: 5178 // These expressions are available if their operand(s) is/are. 5179 return true; 5180 5181 case scAddRecExpr: { 5182 // We allow add recurrences that are on the loop BB is in, or some 5183 // outer loop. This guarantees availability because the value of the 5184 // add recurrence at BB is simply the "current" value of the induction 5185 // variable. We can relax this in the future; for instance an add 5186 // recurrence on a sibling dominating loop is also available at BB. 5187 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5188 if (L && (ARLoop == L || ARLoop->contains(L))) 5189 return true; 5190 5191 return setUnavailable(); 5192 } 5193 5194 case scUnknown: { 5195 // For SCEVUnknown, we check for simple dominance. 5196 const auto *SU = cast<SCEVUnknown>(S); 5197 Value *V = SU->getValue(); 5198 5199 if (isa<Argument>(V)) 5200 return false; 5201 5202 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5203 return false; 5204 5205 return setUnavailable(); 5206 } 5207 5208 case scUDivExpr: 5209 case scCouldNotCompute: 5210 // We do not try to smart about these at all. 5211 return setUnavailable(); 5212 } 5213 llvm_unreachable("Unknown SCEV kind!"); 5214 } 5215 5216 bool isDone() { return TraversalDone; } 5217 }; 5218 5219 CheckAvailable CA(L, BB, DT); 5220 SCEVTraversal<CheckAvailable> ST(CA); 5221 5222 ST.visitAll(S); 5223 return CA.Available; 5224 } 5225 5226 // Try to match a control flow sequence that branches out at BI and merges back 5227 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5228 // match. 5229 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5230 Value *&C, Value *&LHS, Value *&RHS) { 5231 C = BI->getCondition(); 5232 5233 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5234 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5235 5236 if (!LeftEdge.isSingleEdge()) 5237 return false; 5238 5239 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5240 5241 Use &LeftUse = Merge->getOperandUse(0); 5242 Use &RightUse = Merge->getOperandUse(1); 5243 5244 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5245 LHS = LeftUse; 5246 RHS = RightUse; 5247 return true; 5248 } 5249 5250 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5251 LHS = RightUse; 5252 RHS = LeftUse; 5253 return true; 5254 } 5255 5256 return false; 5257 } 5258 5259 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5260 auto IsReachable = 5261 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5262 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5263 const Loop *L = LI.getLoopFor(PN->getParent()); 5264 5265 // We don't want to break LCSSA, even in a SCEV expression tree. 5266 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5267 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5268 return nullptr; 5269 5270 // Try to match 5271 // 5272 // br %cond, label %left, label %right 5273 // left: 5274 // br label %merge 5275 // right: 5276 // br label %merge 5277 // merge: 5278 // V = phi [ %x, %left ], [ %y, %right ] 5279 // 5280 // as "select %cond, %x, %y" 5281 5282 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5283 assert(IDom && "At least the entry block should dominate PN"); 5284 5285 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5286 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5287 5288 if (BI && BI->isConditional() && 5289 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5290 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5291 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5292 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5293 } 5294 5295 return nullptr; 5296 } 5297 5298 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5299 if (const SCEV *S = createAddRecFromPHI(PN)) 5300 return S; 5301 5302 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5303 return S; 5304 5305 // If the PHI has a single incoming value, follow that value, unless the 5306 // PHI's incoming blocks are in a different loop, in which case doing so 5307 // risks breaking LCSSA form. Instcombine would normally zap these, but 5308 // it doesn't have DominatorTree information, so it may miss cases. 5309 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5310 if (LI.replacementPreservesLCSSAForm(PN, V)) 5311 return getSCEV(V); 5312 5313 // If it's not a loop phi, we can't handle it yet. 5314 return getUnknown(PN); 5315 } 5316 5317 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5318 Value *Cond, 5319 Value *TrueVal, 5320 Value *FalseVal) { 5321 // Handle "constant" branch or select. This can occur for instance when a 5322 // loop pass transforms an inner loop and moves on to process the outer loop. 5323 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5324 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5325 5326 // Try to match some simple smax or umax patterns. 5327 auto *ICI = dyn_cast<ICmpInst>(Cond); 5328 if (!ICI) 5329 return getUnknown(I); 5330 5331 Value *LHS = ICI->getOperand(0); 5332 Value *RHS = ICI->getOperand(1); 5333 5334 switch (ICI->getPredicate()) { 5335 case ICmpInst::ICMP_SLT: 5336 case ICmpInst::ICMP_SLE: 5337 std::swap(LHS, RHS); 5338 LLVM_FALLTHROUGH; 5339 case ICmpInst::ICMP_SGT: 5340 case ICmpInst::ICMP_SGE: 5341 // a >s b ? a+x : b+x -> smax(a, b)+x 5342 // a >s b ? b+x : a+x -> smin(a, b)+x 5343 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5344 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5345 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5346 const SCEV *LA = getSCEV(TrueVal); 5347 const SCEV *RA = getSCEV(FalseVal); 5348 const SCEV *LDiff = getMinusSCEV(LA, LS); 5349 const SCEV *RDiff = getMinusSCEV(RA, RS); 5350 if (LDiff == RDiff) 5351 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5352 LDiff = getMinusSCEV(LA, RS); 5353 RDiff = getMinusSCEV(RA, LS); 5354 if (LDiff == RDiff) 5355 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5356 } 5357 break; 5358 case ICmpInst::ICMP_ULT: 5359 case ICmpInst::ICMP_ULE: 5360 std::swap(LHS, RHS); 5361 LLVM_FALLTHROUGH; 5362 case ICmpInst::ICMP_UGT: 5363 case ICmpInst::ICMP_UGE: 5364 // a >u b ? a+x : b+x -> umax(a, b)+x 5365 // a >u b ? b+x : a+x -> umin(a, b)+x 5366 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5367 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5368 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5369 const SCEV *LA = getSCEV(TrueVal); 5370 const SCEV *RA = getSCEV(FalseVal); 5371 const SCEV *LDiff = getMinusSCEV(LA, LS); 5372 const SCEV *RDiff = getMinusSCEV(RA, RS); 5373 if (LDiff == RDiff) 5374 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5375 LDiff = getMinusSCEV(LA, RS); 5376 RDiff = getMinusSCEV(RA, LS); 5377 if (LDiff == RDiff) 5378 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5379 } 5380 break; 5381 case ICmpInst::ICMP_NE: 5382 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5383 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5384 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5385 const SCEV *One = getOne(I->getType()); 5386 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5387 const SCEV *LA = getSCEV(TrueVal); 5388 const SCEV *RA = getSCEV(FalseVal); 5389 const SCEV *LDiff = getMinusSCEV(LA, LS); 5390 const SCEV *RDiff = getMinusSCEV(RA, One); 5391 if (LDiff == RDiff) 5392 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5393 } 5394 break; 5395 case ICmpInst::ICMP_EQ: 5396 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5397 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5398 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5399 const SCEV *One = getOne(I->getType()); 5400 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5401 const SCEV *LA = getSCEV(TrueVal); 5402 const SCEV *RA = getSCEV(FalseVal); 5403 const SCEV *LDiff = getMinusSCEV(LA, One); 5404 const SCEV *RDiff = getMinusSCEV(RA, LS); 5405 if (LDiff == RDiff) 5406 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5407 } 5408 break; 5409 default: 5410 break; 5411 } 5412 5413 return getUnknown(I); 5414 } 5415 5416 /// Expand GEP instructions into add and multiply operations. This allows them 5417 /// to be analyzed by regular SCEV code. 5418 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5419 // Don't attempt to analyze GEPs over unsized objects. 5420 if (!GEP->getSourceElementType()->isSized()) 5421 return getUnknown(GEP); 5422 5423 SmallVector<const SCEV *, 4> IndexExprs; 5424 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5425 IndexExprs.push_back(getSCEV(*Index)); 5426 return getGEPExpr(GEP, IndexExprs); 5427 } 5428 5429 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5430 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5431 return C->getAPInt().countTrailingZeros(); 5432 5433 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5434 return GetMinTrailingZeros(I->getOperand()); 5435 5436 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5437 return std::min(GetMinTrailingZeros(T->getOperand()), 5438 (uint32_t)getTypeSizeInBits(T->getType())); 5439 5440 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5441 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5442 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5443 ? getTypeSizeInBits(E->getType()) 5444 : OpRes; 5445 } 5446 5447 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5448 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5449 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5450 ? getTypeSizeInBits(E->getType()) 5451 : OpRes; 5452 } 5453 5454 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5455 // The result is the min of all operands results. 5456 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5457 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5458 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5459 return MinOpRes; 5460 } 5461 5462 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5463 // The result is the sum of all operands results. 5464 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5465 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5466 for (unsigned i = 1, e = M->getNumOperands(); 5467 SumOpRes != BitWidth && i != e; ++i) 5468 SumOpRes = 5469 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5470 return SumOpRes; 5471 } 5472 5473 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5474 // The result is the min of all operands results. 5475 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5476 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5477 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5478 return MinOpRes; 5479 } 5480 5481 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5482 // The result is the min of all operands results. 5483 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5484 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5485 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5486 return MinOpRes; 5487 } 5488 5489 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5490 // The result is the min of all operands results. 5491 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5492 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5493 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5494 return MinOpRes; 5495 } 5496 5497 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5498 // For a SCEVUnknown, ask ValueTracking. 5499 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5500 return Known.countMinTrailingZeros(); 5501 } 5502 5503 // SCEVUDivExpr 5504 return 0; 5505 } 5506 5507 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5508 auto I = MinTrailingZerosCache.find(S); 5509 if (I != MinTrailingZerosCache.end()) 5510 return I->second; 5511 5512 uint32_t Result = GetMinTrailingZerosImpl(S); 5513 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5514 assert(InsertPair.second && "Should insert a new key"); 5515 return InsertPair.first->second; 5516 } 5517 5518 /// Helper method to assign a range to V from metadata present in the IR. 5519 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5520 if (Instruction *I = dyn_cast<Instruction>(V)) 5521 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5522 return getConstantRangeFromMetadata(*MD); 5523 5524 return None; 5525 } 5526 5527 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5528 SCEV::NoWrapFlags Flags) { 5529 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5530 AddRec->setNoWrapFlags(Flags); 5531 UnsignedRanges.erase(AddRec); 5532 SignedRanges.erase(AddRec); 5533 } 5534 } 5535 5536 /// Determine the range for a particular SCEV. If SignHint is 5537 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5538 /// with a "cleaner" unsigned (resp. signed) representation. 5539 const ConstantRange & 5540 ScalarEvolution::getRangeRef(const SCEV *S, 5541 ScalarEvolution::RangeSignHint SignHint) { 5542 DenseMap<const SCEV *, ConstantRange> &Cache = 5543 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5544 : SignedRanges; 5545 ConstantRange::PreferredRangeType RangeType = 5546 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5547 ? ConstantRange::Unsigned : ConstantRange::Signed; 5548 5549 // See if we've computed this range already. 5550 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5551 if (I != Cache.end()) 5552 return I->second; 5553 5554 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5555 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5556 5557 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5558 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5559 using OBO = OverflowingBinaryOperator; 5560 5561 // If the value has known zeros, the maximum value will have those known zeros 5562 // as well. 5563 uint32_t TZ = GetMinTrailingZeros(S); 5564 if (TZ != 0) { 5565 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5566 ConservativeResult = 5567 ConstantRange(APInt::getMinValue(BitWidth), 5568 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5569 else 5570 ConservativeResult = ConstantRange( 5571 APInt::getSignedMinValue(BitWidth), 5572 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5573 } 5574 5575 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5576 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5577 unsigned WrapType = OBO::AnyWrap; 5578 if (Add->hasNoSignedWrap()) 5579 WrapType |= OBO::NoSignedWrap; 5580 if (Add->hasNoUnsignedWrap()) 5581 WrapType |= OBO::NoUnsignedWrap; 5582 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5583 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5584 WrapType, RangeType); 5585 return setRange(Add, SignHint, 5586 ConservativeResult.intersectWith(X, RangeType)); 5587 } 5588 5589 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5590 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5591 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5592 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5593 return setRange(Mul, SignHint, 5594 ConservativeResult.intersectWith(X, RangeType)); 5595 } 5596 5597 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5598 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5599 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5600 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5601 return setRange(SMax, SignHint, 5602 ConservativeResult.intersectWith(X, RangeType)); 5603 } 5604 5605 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5606 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5607 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5608 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5609 return setRange(UMax, SignHint, 5610 ConservativeResult.intersectWith(X, RangeType)); 5611 } 5612 5613 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5614 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5615 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5616 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5617 return setRange(SMin, SignHint, 5618 ConservativeResult.intersectWith(X, RangeType)); 5619 } 5620 5621 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5622 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5623 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5624 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5625 return setRange(UMin, SignHint, 5626 ConservativeResult.intersectWith(X, RangeType)); 5627 } 5628 5629 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5630 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5631 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5632 return setRange(UDiv, SignHint, 5633 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5634 } 5635 5636 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5637 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5638 return setRange(ZExt, SignHint, 5639 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5640 RangeType)); 5641 } 5642 5643 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5644 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5645 return setRange(SExt, SignHint, 5646 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5647 RangeType)); 5648 } 5649 5650 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5651 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5652 return setRange(PtrToInt, SignHint, X); 5653 } 5654 5655 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5656 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5657 return setRange(Trunc, SignHint, 5658 ConservativeResult.intersectWith(X.truncate(BitWidth), 5659 RangeType)); 5660 } 5661 5662 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5663 // If there's no unsigned wrap, the value will never be less than its 5664 // initial value. 5665 if (AddRec->hasNoUnsignedWrap()) { 5666 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5667 if (!UnsignedMinValue.isNullValue()) 5668 ConservativeResult = ConservativeResult.intersectWith( 5669 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5670 } 5671 5672 // If there's no signed wrap, and all the operands except initial value have 5673 // the same sign or zero, the value won't ever be: 5674 // 1: smaller than initial value if operands are non negative, 5675 // 2: bigger than initial value if operands are non positive. 5676 // For both cases, value can not cross signed min/max boundary. 5677 if (AddRec->hasNoSignedWrap()) { 5678 bool AllNonNeg = true; 5679 bool AllNonPos = true; 5680 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5681 if (!isKnownNonNegative(AddRec->getOperand(i))) 5682 AllNonNeg = false; 5683 if (!isKnownNonPositive(AddRec->getOperand(i))) 5684 AllNonPos = false; 5685 } 5686 if (AllNonNeg) 5687 ConservativeResult = ConservativeResult.intersectWith( 5688 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5689 APInt::getSignedMinValue(BitWidth)), 5690 RangeType); 5691 else if (AllNonPos) 5692 ConservativeResult = ConservativeResult.intersectWith( 5693 ConstantRange::getNonEmpty( 5694 APInt::getSignedMinValue(BitWidth), 5695 getSignedRangeMax(AddRec->getStart()) + 1), 5696 RangeType); 5697 } 5698 5699 // TODO: non-affine addrec 5700 if (AddRec->isAffine()) { 5701 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5702 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5703 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5704 auto RangeFromAffine = getRangeForAffineAR( 5705 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5706 BitWidth); 5707 ConservativeResult = 5708 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5709 5710 auto RangeFromFactoring = getRangeViaFactoring( 5711 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5712 BitWidth); 5713 ConservativeResult = 5714 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5715 } 5716 5717 // Now try symbolic BE count and more powerful methods. 5718 if (UseExpensiveRangeSharpening) { 5719 const SCEV *SymbolicMaxBECount = 5720 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 5721 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 5722 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5723 AddRec->hasNoSelfWrap()) { 5724 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5725 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 5726 ConservativeResult = 5727 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5728 } 5729 } 5730 } 5731 5732 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5733 } 5734 5735 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5736 // Check if the IR explicitly contains !range metadata. 5737 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5738 if (MDRange.hasValue()) 5739 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5740 RangeType); 5741 5742 // Split here to avoid paying the compile-time cost of calling both 5743 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5744 // if needed. 5745 const DataLayout &DL = getDataLayout(); 5746 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5747 // For a SCEVUnknown, ask ValueTracking. 5748 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5749 if (Known.getBitWidth() != BitWidth) 5750 Known = Known.zextOrTrunc(BitWidth); 5751 // If Known does not result in full-set, intersect with it. 5752 if (Known.getMinValue() != Known.getMaxValue() + 1) 5753 ConservativeResult = ConservativeResult.intersectWith( 5754 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5755 RangeType); 5756 } else { 5757 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5758 "generalize as needed!"); 5759 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5760 // If the pointer size is larger than the index size type, this can cause 5761 // NS to be larger than BitWidth. So compensate for this. 5762 if (U->getType()->isPointerTy()) { 5763 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5764 int ptrIdxDiff = ptrSize - BitWidth; 5765 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5766 NS -= ptrIdxDiff; 5767 } 5768 5769 if (NS > 1) 5770 ConservativeResult = ConservativeResult.intersectWith( 5771 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5772 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5773 RangeType); 5774 } 5775 5776 // A range of Phi is a subset of union of all ranges of its input. 5777 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5778 // Make sure that we do not run over cycled Phis. 5779 if (PendingPhiRanges.insert(Phi).second) { 5780 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5781 for (auto &Op : Phi->operands()) { 5782 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5783 RangeFromOps = RangeFromOps.unionWith(OpRange); 5784 // No point to continue if we already have a full set. 5785 if (RangeFromOps.isFullSet()) 5786 break; 5787 } 5788 ConservativeResult = 5789 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5790 bool Erased = PendingPhiRanges.erase(Phi); 5791 assert(Erased && "Failed to erase Phi properly?"); 5792 (void) Erased; 5793 } 5794 } 5795 5796 return setRange(U, SignHint, std::move(ConservativeResult)); 5797 } 5798 5799 return setRange(S, SignHint, std::move(ConservativeResult)); 5800 } 5801 5802 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5803 // values that the expression can take. Initially, the expression has a value 5804 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5805 // argument defines if we treat Step as signed or unsigned. 5806 static ConstantRange getRangeForAffineARHelper(APInt Step, 5807 const ConstantRange &StartRange, 5808 const APInt &MaxBECount, 5809 unsigned BitWidth, bool Signed) { 5810 // If either Step or MaxBECount is 0, then the expression won't change, and we 5811 // just need to return the initial range. 5812 if (Step == 0 || MaxBECount == 0) 5813 return StartRange; 5814 5815 // If we don't know anything about the initial value (i.e. StartRange is 5816 // FullRange), then we don't know anything about the final range either. 5817 // Return FullRange. 5818 if (StartRange.isFullSet()) 5819 return ConstantRange::getFull(BitWidth); 5820 5821 // If Step is signed and negative, then we use its absolute value, but we also 5822 // note that we're moving in the opposite direction. 5823 bool Descending = Signed && Step.isNegative(); 5824 5825 if (Signed) 5826 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5827 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5828 // This equations hold true due to the well-defined wrap-around behavior of 5829 // APInt. 5830 Step = Step.abs(); 5831 5832 // Check if Offset is more than full span of BitWidth. If it is, the 5833 // expression is guaranteed to overflow. 5834 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5835 return ConstantRange::getFull(BitWidth); 5836 5837 // Offset is by how much the expression can change. Checks above guarantee no 5838 // overflow here. 5839 APInt Offset = Step * MaxBECount; 5840 5841 // Minimum value of the final range will match the minimal value of StartRange 5842 // if the expression is increasing and will be decreased by Offset otherwise. 5843 // Maximum value of the final range will match the maximal value of StartRange 5844 // if the expression is decreasing and will be increased by Offset otherwise. 5845 APInt StartLower = StartRange.getLower(); 5846 APInt StartUpper = StartRange.getUpper() - 1; 5847 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5848 : (StartUpper + std::move(Offset)); 5849 5850 // It's possible that the new minimum/maximum value will fall into the initial 5851 // range (due to wrap around). This means that the expression can take any 5852 // value in this bitwidth, and we have to return full range. 5853 if (StartRange.contains(MovedBoundary)) 5854 return ConstantRange::getFull(BitWidth); 5855 5856 APInt NewLower = 5857 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5858 APInt NewUpper = 5859 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5860 NewUpper += 1; 5861 5862 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5863 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5864 } 5865 5866 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5867 const SCEV *Step, 5868 const SCEV *MaxBECount, 5869 unsigned BitWidth) { 5870 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5871 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5872 "Precondition!"); 5873 5874 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5875 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5876 5877 // First, consider step signed. 5878 ConstantRange StartSRange = getSignedRange(Start); 5879 ConstantRange StepSRange = getSignedRange(Step); 5880 5881 // If Step can be both positive and negative, we need to find ranges for the 5882 // maximum absolute step values in both directions and union them. 5883 ConstantRange SR = 5884 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5885 MaxBECountValue, BitWidth, /* Signed = */ true); 5886 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5887 StartSRange, MaxBECountValue, 5888 BitWidth, /* Signed = */ true)); 5889 5890 // Next, consider step unsigned. 5891 ConstantRange UR = getRangeForAffineARHelper( 5892 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5893 MaxBECountValue, BitWidth, /* Signed = */ false); 5894 5895 // Finally, intersect signed and unsigned ranges. 5896 return SR.intersectWith(UR, ConstantRange::Smallest); 5897 } 5898 5899 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 5900 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 5901 ScalarEvolution::RangeSignHint SignHint) { 5902 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 5903 assert(AddRec->hasNoSelfWrap() && 5904 "This only works for non-self-wrapping AddRecs!"); 5905 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 5906 const SCEV *Step = AddRec->getStepRecurrence(*this); 5907 // Only deal with constant step to save compile time. 5908 if (!isa<SCEVConstant>(Step)) 5909 return ConstantRange::getFull(BitWidth); 5910 // Let's make sure that we can prove that we do not self-wrap during 5911 // MaxBECount iterations. We need this because MaxBECount is a maximum 5912 // iteration count estimate, and we might infer nw from some exit for which we 5913 // do not know max exit count (or any other side reasoning). 5914 // TODO: Turn into assert at some point. 5915 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 5916 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 5917 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 5918 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 5919 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 5920 MaxItersWithoutWrap)) 5921 return ConstantRange::getFull(BitWidth); 5922 5923 ICmpInst::Predicate LEPred = 5924 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 5925 ICmpInst::Predicate GEPred = 5926 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 5927 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 5928 5929 // We know that there is no self-wrap. Let's take Start and End values and 5930 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 5931 // the iteration. They either lie inside the range [Min(Start, End), 5932 // Max(Start, End)] or outside it: 5933 // 5934 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 5935 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 5936 // 5937 // No self wrap flag guarantees that the intermediate values cannot be BOTH 5938 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 5939 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 5940 // Start <= End and step is positive, or Start >= End and step is negative. 5941 const SCEV *Start = AddRec->getStart(); 5942 ConstantRange StartRange = getRangeRef(Start, SignHint); 5943 ConstantRange EndRange = getRangeRef(End, SignHint); 5944 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 5945 // If they already cover full iteration space, we will know nothing useful 5946 // even if we prove what we want to prove. 5947 if (RangeBetween.isFullSet()) 5948 return RangeBetween; 5949 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 5950 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 5951 : RangeBetween.isWrappedSet(); 5952 if (IsWrappedSet) 5953 return ConstantRange::getFull(BitWidth); 5954 5955 if (isKnownPositive(Step) && 5956 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 5957 return RangeBetween; 5958 else if (isKnownNegative(Step) && 5959 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 5960 return RangeBetween; 5961 return ConstantRange::getFull(BitWidth); 5962 } 5963 5964 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5965 const SCEV *Step, 5966 const SCEV *MaxBECount, 5967 unsigned BitWidth) { 5968 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5969 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5970 5971 struct SelectPattern { 5972 Value *Condition = nullptr; 5973 APInt TrueValue; 5974 APInt FalseValue; 5975 5976 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5977 const SCEV *S) { 5978 Optional<unsigned> CastOp; 5979 APInt Offset(BitWidth, 0); 5980 5981 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5982 "Should be!"); 5983 5984 // Peel off a constant offset: 5985 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5986 // In the future we could consider being smarter here and handle 5987 // {Start+Step,+,Step} too. 5988 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5989 return; 5990 5991 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5992 S = SA->getOperand(1); 5993 } 5994 5995 // Peel off a cast operation 5996 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 5997 CastOp = SCast->getSCEVType(); 5998 S = SCast->getOperand(); 5999 } 6000 6001 using namespace llvm::PatternMatch; 6002 6003 auto *SU = dyn_cast<SCEVUnknown>(S); 6004 const APInt *TrueVal, *FalseVal; 6005 if (!SU || 6006 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6007 m_APInt(FalseVal)))) { 6008 Condition = nullptr; 6009 return; 6010 } 6011 6012 TrueValue = *TrueVal; 6013 FalseValue = *FalseVal; 6014 6015 // Re-apply the cast we peeled off earlier 6016 if (CastOp.hasValue()) 6017 switch (*CastOp) { 6018 default: 6019 llvm_unreachable("Unknown SCEV cast type!"); 6020 6021 case scTruncate: 6022 TrueValue = TrueValue.trunc(BitWidth); 6023 FalseValue = FalseValue.trunc(BitWidth); 6024 break; 6025 case scZeroExtend: 6026 TrueValue = TrueValue.zext(BitWidth); 6027 FalseValue = FalseValue.zext(BitWidth); 6028 break; 6029 case scSignExtend: 6030 TrueValue = TrueValue.sext(BitWidth); 6031 FalseValue = FalseValue.sext(BitWidth); 6032 break; 6033 } 6034 6035 // Re-apply the constant offset we peeled off earlier 6036 TrueValue += Offset; 6037 FalseValue += Offset; 6038 } 6039 6040 bool isRecognized() { return Condition != nullptr; } 6041 }; 6042 6043 SelectPattern StartPattern(*this, BitWidth, Start); 6044 if (!StartPattern.isRecognized()) 6045 return ConstantRange::getFull(BitWidth); 6046 6047 SelectPattern StepPattern(*this, BitWidth, Step); 6048 if (!StepPattern.isRecognized()) 6049 return ConstantRange::getFull(BitWidth); 6050 6051 if (StartPattern.Condition != StepPattern.Condition) { 6052 // We don't handle this case today; but we could, by considering four 6053 // possibilities below instead of two. I'm not sure if there are cases where 6054 // that will help over what getRange already does, though. 6055 return ConstantRange::getFull(BitWidth); 6056 } 6057 6058 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6059 // construct arbitrary general SCEV expressions here. This function is called 6060 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6061 // say) can end up caching a suboptimal value. 6062 6063 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6064 // C2352 and C2512 (otherwise it isn't needed). 6065 6066 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6067 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6068 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6069 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6070 6071 ConstantRange TrueRange = 6072 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6073 ConstantRange FalseRange = 6074 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6075 6076 return TrueRange.unionWith(FalseRange); 6077 } 6078 6079 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6080 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6081 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6082 6083 // Return early if there are no flags to propagate to the SCEV. 6084 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6085 if (BinOp->hasNoUnsignedWrap()) 6086 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6087 if (BinOp->hasNoSignedWrap()) 6088 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6089 if (Flags == SCEV::FlagAnyWrap) 6090 return SCEV::FlagAnyWrap; 6091 6092 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6093 } 6094 6095 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6096 // Here we check that I is in the header of the innermost loop containing I, 6097 // since we only deal with instructions in the loop header. The actual loop we 6098 // need to check later will come from an add recurrence, but getting that 6099 // requires computing the SCEV of the operands, which can be expensive. This 6100 // check we can do cheaply to rule out some cases early. 6101 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6102 if (InnermostContainingLoop == nullptr || 6103 InnermostContainingLoop->getHeader() != I->getParent()) 6104 return false; 6105 6106 // Only proceed if we can prove that I does not yield poison. 6107 if (!programUndefinedIfPoison(I)) 6108 return false; 6109 6110 // At this point we know that if I is executed, then it does not wrap 6111 // according to at least one of NSW or NUW. If I is not executed, then we do 6112 // not know if the calculation that I represents would wrap. Multiple 6113 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6114 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6115 // derived from other instructions that map to the same SCEV. We cannot make 6116 // that guarantee for cases where I is not executed. So we need to find the 6117 // loop that I is considered in relation to and prove that I is executed for 6118 // every iteration of that loop. That implies that the value that I 6119 // calculates does not wrap anywhere in the loop, so then we can apply the 6120 // flags to the SCEV. 6121 // 6122 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6123 // from different loops, so that we know which loop to prove that I is 6124 // executed in. 6125 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6126 // I could be an extractvalue from a call to an overflow intrinsic. 6127 // TODO: We can do better here in some cases. 6128 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6129 return false; 6130 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6131 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6132 bool AllOtherOpsLoopInvariant = true; 6133 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6134 ++OtherOpIndex) { 6135 if (OtherOpIndex != OpIndex) { 6136 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6137 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6138 AllOtherOpsLoopInvariant = false; 6139 break; 6140 } 6141 } 6142 } 6143 if (AllOtherOpsLoopInvariant && 6144 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6145 return true; 6146 } 6147 } 6148 return false; 6149 } 6150 6151 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6152 // If we know that \c I can never be poison period, then that's enough. 6153 if (isSCEVExprNeverPoison(I)) 6154 return true; 6155 6156 // For an add recurrence specifically, we assume that infinite loops without 6157 // side effects are undefined behavior, and then reason as follows: 6158 // 6159 // If the add recurrence is poison in any iteration, it is poison on all 6160 // future iterations (since incrementing poison yields poison). If the result 6161 // of the add recurrence is fed into the loop latch condition and the loop 6162 // does not contain any throws or exiting blocks other than the latch, we now 6163 // have the ability to "choose" whether the backedge is taken or not (by 6164 // choosing a sufficiently evil value for the poison feeding into the branch) 6165 // for every iteration including and after the one in which \p I first became 6166 // poison. There are two possibilities (let's call the iteration in which \p 6167 // I first became poison as K): 6168 // 6169 // 1. In the set of iterations including and after K, the loop body executes 6170 // no side effects. In this case executing the backege an infinte number 6171 // of times will yield undefined behavior. 6172 // 6173 // 2. In the set of iterations including and after K, the loop body executes 6174 // at least one side effect. In this case, that specific instance of side 6175 // effect is control dependent on poison, which also yields undefined 6176 // behavior. 6177 6178 auto *ExitingBB = L->getExitingBlock(); 6179 auto *LatchBB = L->getLoopLatch(); 6180 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6181 return false; 6182 6183 SmallPtrSet<const Instruction *, 16> Pushed; 6184 SmallVector<const Instruction *, 8> PoisonStack; 6185 6186 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6187 // things that are known to be poison under that assumption go on the 6188 // PoisonStack. 6189 Pushed.insert(I); 6190 PoisonStack.push_back(I); 6191 6192 bool LatchControlDependentOnPoison = false; 6193 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6194 const Instruction *Poison = PoisonStack.pop_back_val(); 6195 6196 for (auto *PoisonUser : Poison->users()) { 6197 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6198 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6199 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6200 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6201 assert(BI->isConditional() && "Only possibility!"); 6202 if (BI->getParent() == LatchBB) { 6203 LatchControlDependentOnPoison = true; 6204 break; 6205 } 6206 } 6207 } 6208 } 6209 6210 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6211 } 6212 6213 ScalarEvolution::LoopProperties 6214 ScalarEvolution::getLoopProperties(const Loop *L) { 6215 using LoopProperties = ScalarEvolution::LoopProperties; 6216 6217 auto Itr = LoopPropertiesCache.find(L); 6218 if (Itr == LoopPropertiesCache.end()) { 6219 auto HasSideEffects = [](Instruction *I) { 6220 if (auto *SI = dyn_cast<StoreInst>(I)) 6221 return !SI->isSimple(); 6222 6223 return I->mayHaveSideEffects(); 6224 }; 6225 6226 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6227 /*HasNoSideEffects*/ true}; 6228 6229 for (auto *BB : L->getBlocks()) 6230 for (auto &I : *BB) { 6231 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6232 LP.HasNoAbnormalExits = false; 6233 if (HasSideEffects(&I)) 6234 LP.HasNoSideEffects = false; 6235 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6236 break; // We're already as pessimistic as we can get. 6237 } 6238 6239 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6240 assert(InsertPair.second && "We just checked!"); 6241 Itr = InsertPair.first; 6242 } 6243 6244 return Itr->second; 6245 } 6246 6247 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6248 if (!isSCEVable(V->getType())) 6249 return getUnknown(V); 6250 6251 if (Instruction *I = dyn_cast<Instruction>(V)) { 6252 // Don't attempt to analyze instructions in blocks that aren't 6253 // reachable. Such instructions don't matter, and they aren't required 6254 // to obey basic rules for definitions dominating uses which this 6255 // analysis depends on. 6256 if (!DT.isReachableFromEntry(I->getParent())) 6257 return getUnknown(UndefValue::get(V->getType())); 6258 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6259 return getConstant(CI); 6260 else if (isa<ConstantPointerNull>(V)) 6261 // FIXME: we shouldn't special-case null pointer constant. 6262 return getZero(V->getType()); 6263 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6264 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6265 else if (!isa<ConstantExpr>(V)) 6266 return getUnknown(V); 6267 6268 Operator *U = cast<Operator>(V); 6269 if (auto BO = MatchBinaryOp(U, DT)) { 6270 switch (BO->Opcode) { 6271 case Instruction::Add: { 6272 // The simple thing to do would be to just call getSCEV on both operands 6273 // and call getAddExpr with the result. However if we're looking at a 6274 // bunch of things all added together, this can be quite inefficient, 6275 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6276 // Instead, gather up all the operands and make a single getAddExpr call. 6277 // LLVM IR canonical form means we need only traverse the left operands. 6278 SmallVector<const SCEV *, 4> AddOps; 6279 do { 6280 if (BO->Op) { 6281 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6282 AddOps.push_back(OpSCEV); 6283 break; 6284 } 6285 6286 // If a NUW or NSW flag can be applied to the SCEV for this 6287 // addition, then compute the SCEV for this addition by itself 6288 // with a separate call to getAddExpr. We need to do that 6289 // instead of pushing the operands of the addition onto AddOps, 6290 // since the flags are only known to apply to this particular 6291 // addition - they may not apply to other additions that can be 6292 // formed with operands from AddOps. 6293 const SCEV *RHS = getSCEV(BO->RHS); 6294 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6295 if (Flags != SCEV::FlagAnyWrap) { 6296 const SCEV *LHS = getSCEV(BO->LHS); 6297 if (BO->Opcode == Instruction::Sub) 6298 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6299 else 6300 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6301 break; 6302 } 6303 } 6304 6305 if (BO->Opcode == Instruction::Sub) 6306 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6307 else 6308 AddOps.push_back(getSCEV(BO->RHS)); 6309 6310 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6311 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6312 NewBO->Opcode != Instruction::Sub)) { 6313 AddOps.push_back(getSCEV(BO->LHS)); 6314 break; 6315 } 6316 BO = NewBO; 6317 } while (true); 6318 6319 return getAddExpr(AddOps); 6320 } 6321 6322 case Instruction::Mul: { 6323 SmallVector<const SCEV *, 4> MulOps; 6324 do { 6325 if (BO->Op) { 6326 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6327 MulOps.push_back(OpSCEV); 6328 break; 6329 } 6330 6331 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6332 if (Flags != SCEV::FlagAnyWrap) { 6333 MulOps.push_back( 6334 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6335 break; 6336 } 6337 } 6338 6339 MulOps.push_back(getSCEV(BO->RHS)); 6340 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6341 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6342 MulOps.push_back(getSCEV(BO->LHS)); 6343 break; 6344 } 6345 BO = NewBO; 6346 } while (true); 6347 6348 return getMulExpr(MulOps); 6349 } 6350 case Instruction::UDiv: 6351 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6352 case Instruction::URem: 6353 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6354 case Instruction::Sub: { 6355 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6356 if (BO->Op) 6357 Flags = getNoWrapFlagsFromUB(BO->Op); 6358 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6359 } 6360 case Instruction::And: 6361 // For an expression like x&255 that merely masks off the high bits, 6362 // use zext(trunc(x)) as the SCEV expression. 6363 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6364 if (CI->isZero()) 6365 return getSCEV(BO->RHS); 6366 if (CI->isMinusOne()) 6367 return getSCEV(BO->LHS); 6368 const APInt &A = CI->getValue(); 6369 6370 // Instcombine's ShrinkDemandedConstant may strip bits out of 6371 // constants, obscuring what would otherwise be a low-bits mask. 6372 // Use computeKnownBits to compute what ShrinkDemandedConstant 6373 // knew about to reconstruct a low-bits mask value. 6374 unsigned LZ = A.countLeadingZeros(); 6375 unsigned TZ = A.countTrailingZeros(); 6376 unsigned BitWidth = A.getBitWidth(); 6377 KnownBits Known(BitWidth); 6378 computeKnownBits(BO->LHS, Known, getDataLayout(), 6379 0, &AC, nullptr, &DT); 6380 6381 APInt EffectiveMask = 6382 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6383 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6384 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6385 const SCEV *LHS = getSCEV(BO->LHS); 6386 const SCEV *ShiftedLHS = nullptr; 6387 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6388 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6389 // For an expression like (x * 8) & 8, simplify the multiply. 6390 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6391 unsigned GCD = std::min(MulZeros, TZ); 6392 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6393 SmallVector<const SCEV*, 4> MulOps; 6394 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6395 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6396 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6397 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6398 } 6399 } 6400 if (!ShiftedLHS) 6401 ShiftedLHS = getUDivExpr(LHS, MulCount); 6402 return getMulExpr( 6403 getZeroExtendExpr( 6404 getTruncateExpr(ShiftedLHS, 6405 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6406 BO->LHS->getType()), 6407 MulCount); 6408 } 6409 } 6410 break; 6411 6412 case Instruction::Or: 6413 // If the RHS of the Or is a constant, we may have something like: 6414 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6415 // optimizations will transparently handle this case. 6416 // 6417 // In order for this transformation to be safe, the LHS must be of the 6418 // form X*(2^n) and the Or constant must be less than 2^n. 6419 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6420 const SCEV *LHS = getSCEV(BO->LHS); 6421 const APInt &CIVal = CI->getValue(); 6422 if (GetMinTrailingZeros(LHS) >= 6423 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6424 // Build a plain add SCEV. 6425 return getAddExpr(LHS, getSCEV(CI), 6426 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6427 } 6428 } 6429 break; 6430 6431 case Instruction::Xor: 6432 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6433 // If the RHS of xor is -1, then this is a not operation. 6434 if (CI->isMinusOne()) 6435 return getNotSCEV(getSCEV(BO->LHS)); 6436 6437 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6438 // This is a variant of the check for xor with -1, and it handles 6439 // the case where instcombine has trimmed non-demanded bits out 6440 // of an xor with -1. 6441 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6442 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6443 if (LBO->getOpcode() == Instruction::And && 6444 LCI->getValue() == CI->getValue()) 6445 if (const SCEVZeroExtendExpr *Z = 6446 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6447 Type *UTy = BO->LHS->getType(); 6448 const SCEV *Z0 = Z->getOperand(); 6449 Type *Z0Ty = Z0->getType(); 6450 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6451 6452 // If C is a low-bits mask, the zero extend is serving to 6453 // mask off the high bits. Complement the operand and 6454 // re-apply the zext. 6455 if (CI->getValue().isMask(Z0TySize)) 6456 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6457 6458 // If C is a single bit, it may be in the sign-bit position 6459 // before the zero-extend. In this case, represent the xor 6460 // using an add, which is equivalent, and re-apply the zext. 6461 APInt Trunc = CI->getValue().trunc(Z0TySize); 6462 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6463 Trunc.isSignMask()) 6464 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6465 UTy); 6466 } 6467 } 6468 break; 6469 6470 case Instruction::Shl: 6471 // Turn shift left of a constant amount into a multiply. 6472 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6473 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6474 6475 // If the shift count is not less than the bitwidth, the result of 6476 // the shift is undefined. Don't try to analyze it, because the 6477 // resolution chosen here may differ from the resolution chosen in 6478 // other parts of the compiler. 6479 if (SA->getValue().uge(BitWidth)) 6480 break; 6481 6482 // We can safely preserve the nuw flag in all cases. It's also safe to 6483 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6484 // requires special handling. It can be preserved as long as we're not 6485 // left shifting by bitwidth - 1. 6486 auto Flags = SCEV::FlagAnyWrap; 6487 if (BO->Op) { 6488 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6489 if ((MulFlags & SCEV::FlagNSW) && 6490 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6491 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6492 if (MulFlags & SCEV::FlagNUW) 6493 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6494 } 6495 6496 Constant *X = ConstantInt::get( 6497 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6498 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6499 } 6500 break; 6501 6502 case Instruction::AShr: { 6503 // AShr X, C, where C is a constant. 6504 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6505 if (!CI) 6506 break; 6507 6508 Type *OuterTy = BO->LHS->getType(); 6509 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6510 // If the shift count is not less than the bitwidth, the result of 6511 // the shift is undefined. Don't try to analyze it, because the 6512 // resolution chosen here may differ from the resolution chosen in 6513 // other parts of the compiler. 6514 if (CI->getValue().uge(BitWidth)) 6515 break; 6516 6517 if (CI->isZero()) 6518 return getSCEV(BO->LHS); // shift by zero --> noop 6519 6520 uint64_t AShrAmt = CI->getZExtValue(); 6521 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6522 6523 Operator *L = dyn_cast<Operator>(BO->LHS); 6524 if (L && L->getOpcode() == Instruction::Shl) { 6525 // X = Shl A, n 6526 // Y = AShr X, m 6527 // Both n and m are constant. 6528 6529 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6530 if (L->getOperand(1) == BO->RHS) 6531 // For a two-shift sext-inreg, i.e. n = m, 6532 // use sext(trunc(x)) as the SCEV expression. 6533 return getSignExtendExpr( 6534 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6535 6536 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6537 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6538 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6539 if (ShlAmt > AShrAmt) { 6540 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6541 // expression. We already checked that ShlAmt < BitWidth, so 6542 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6543 // ShlAmt - AShrAmt < Amt. 6544 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6545 ShlAmt - AShrAmt); 6546 return getSignExtendExpr( 6547 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6548 getConstant(Mul)), OuterTy); 6549 } 6550 } 6551 } 6552 if (BO->IsExact) { 6553 // Given exact arithmetic in-bounds right-shift by a constant, 6554 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6555 const SCEV *X = getSCEV(BO->LHS); 6556 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6557 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6558 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6559 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6560 } 6561 break; 6562 } 6563 } 6564 } 6565 6566 switch (U->getOpcode()) { 6567 case Instruction::Trunc: 6568 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6569 6570 case Instruction::ZExt: 6571 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6572 6573 case Instruction::SExt: 6574 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6575 // The NSW flag of a subtract does not always survive the conversion to 6576 // A + (-1)*B. By pushing sign extension onto its operands we are much 6577 // more likely to preserve NSW and allow later AddRec optimisations. 6578 // 6579 // NOTE: This is effectively duplicating this logic from getSignExtend: 6580 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6581 // but by that point the NSW information has potentially been lost. 6582 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6583 Type *Ty = U->getType(); 6584 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6585 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6586 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6587 } 6588 } 6589 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6590 6591 case Instruction::BitCast: 6592 // BitCasts are no-op casts so we just eliminate the cast. 6593 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6594 return getSCEV(U->getOperand(0)); 6595 break; 6596 6597 case Instruction::PtrToInt: { 6598 // Pointer to integer cast is straight-forward, so do model it. 6599 Value *Ptr = U->getOperand(0); 6600 const SCEV *Op = getSCEV(Ptr); 6601 Type *DstIntTy = U->getType(); 6602 // SCEV doesn't have constant pointer expression type, but it supports 6603 // nullptr constant (and only that one), which is modelled in SCEV as a 6604 // zero integer constant. So just skip the ptrtoint cast for constants. 6605 if (isa<SCEVConstant>(Op)) 6606 return getTruncateOrZeroExtend(Op, DstIntTy); 6607 Type *PtrTy = Ptr->getType(); 6608 Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy); 6609 // But only if effective SCEV (integer) type is wide enough to represent 6610 // all possible pointer values. 6611 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) != 6612 getDataLayout().getTypeSizeInBits(IntPtrTy)) 6613 return getUnknown(V); 6614 return getPtrToIntExpr(Op, DstIntTy); 6615 } 6616 case Instruction::IntToPtr: 6617 // Just don't deal with inttoptr casts. 6618 return getUnknown(V); 6619 6620 case Instruction::SDiv: 6621 // If both operands are non-negative, this is just an udiv. 6622 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6623 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6624 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6625 break; 6626 6627 case Instruction::SRem: 6628 // If both operands are non-negative, this is just an urem. 6629 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6630 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6631 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6632 break; 6633 6634 case Instruction::GetElementPtr: 6635 return createNodeForGEP(cast<GEPOperator>(U)); 6636 6637 case Instruction::PHI: 6638 return createNodeForPHI(cast<PHINode>(U)); 6639 6640 case Instruction::Select: 6641 // U can also be a select constant expr, which let fall through. Since 6642 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6643 // constant expressions cannot have instructions as operands, we'd have 6644 // returned getUnknown for a select constant expressions anyway. 6645 if (isa<Instruction>(U)) 6646 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6647 U->getOperand(1), U->getOperand(2)); 6648 break; 6649 6650 case Instruction::Call: 6651 case Instruction::Invoke: 6652 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6653 return getSCEV(RV); 6654 6655 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6656 switch (II->getIntrinsicID()) { 6657 case Intrinsic::abs: 6658 return getAbsExpr( 6659 getSCEV(II->getArgOperand(0)), 6660 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6661 case Intrinsic::umax: 6662 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6663 getSCEV(II->getArgOperand(1))); 6664 case Intrinsic::umin: 6665 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6666 getSCEV(II->getArgOperand(1))); 6667 case Intrinsic::smax: 6668 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6669 getSCEV(II->getArgOperand(1))); 6670 case Intrinsic::smin: 6671 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6672 getSCEV(II->getArgOperand(1))); 6673 case Intrinsic::usub_sat: { 6674 const SCEV *X = getSCEV(II->getArgOperand(0)); 6675 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6676 const SCEV *ClampedY = getUMinExpr(X, Y); 6677 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6678 } 6679 case Intrinsic::uadd_sat: { 6680 const SCEV *X = getSCEV(II->getArgOperand(0)); 6681 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6682 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6683 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6684 } 6685 case Intrinsic::start_loop_iterations: 6686 // A start_loop_iterations is just equivalent to the first operand for 6687 // SCEV purposes. 6688 return getSCEV(II->getArgOperand(0)); 6689 default: 6690 break; 6691 } 6692 } 6693 break; 6694 } 6695 6696 return getUnknown(V); 6697 } 6698 6699 //===----------------------------------------------------------------------===// 6700 // Iteration Count Computation Code 6701 // 6702 6703 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6704 if (!ExitCount) 6705 return 0; 6706 6707 ConstantInt *ExitConst = ExitCount->getValue(); 6708 6709 // Guard against huge trip counts. 6710 if (ExitConst->getValue().getActiveBits() > 32) 6711 return 0; 6712 6713 // In case of integer overflow, this returns 0, which is correct. 6714 return ((unsigned)ExitConst->getZExtValue()) + 1; 6715 } 6716 6717 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6718 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6719 return getSmallConstantTripCount(L, ExitingBB); 6720 6721 // No trip count information for multiple exits. 6722 return 0; 6723 } 6724 6725 unsigned 6726 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6727 const BasicBlock *ExitingBlock) { 6728 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6729 assert(L->isLoopExiting(ExitingBlock) && 6730 "Exiting block must actually branch out of the loop!"); 6731 const SCEVConstant *ExitCount = 6732 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6733 return getConstantTripCount(ExitCount); 6734 } 6735 6736 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6737 const auto *MaxExitCount = 6738 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6739 return getConstantTripCount(MaxExitCount); 6740 } 6741 6742 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6743 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6744 return getSmallConstantTripMultiple(L, ExitingBB); 6745 6746 // No trip multiple information for multiple exits. 6747 return 0; 6748 } 6749 6750 /// Returns the largest constant divisor of the trip count of this loop as a 6751 /// normal unsigned value, if possible. This means that the actual trip count is 6752 /// always a multiple of the returned value (don't forget the trip count could 6753 /// very well be zero as well!). 6754 /// 6755 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6756 /// multiple of a constant (which is also the case if the trip count is simply 6757 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6758 /// if the trip count is very large (>= 2^32). 6759 /// 6760 /// As explained in the comments for getSmallConstantTripCount, this assumes 6761 /// that control exits the loop via ExitingBlock. 6762 unsigned 6763 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6764 const BasicBlock *ExitingBlock) { 6765 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6766 assert(L->isLoopExiting(ExitingBlock) && 6767 "Exiting block must actually branch out of the loop!"); 6768 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6769 if (ExitCount == getCouldNotCompute()) 6770 return 1; 6771 6772 // Get the trip count from the BE count by adding 1. 6773 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6774 6775 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6776 if (!TC) 6777 // Attempt to factor more general cases. Returns the greatest power of 6778 // two divisor. If overflow happens, the trip count expression is still 6779 // divisible by the greatest power of 2 divisor returned. 6780 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6781 6782 ConstantInt *Result = TC->getValue(); 6783 6784 // Guard against huge trip counts (this requires checking 6785 // for zero to handle the case where the trip count == -1 and the 6786 // addition wraps). 6787 if (!Result || Result->getValue().getActiveBits() > 32 || 6788 Result->getValue().getActiveBits() == 0) 6789 return 1; 6790 6791 return (unsigned)Result->getZExtValue(); 6792 } 6793 6794 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6795 const BasicBlock *ExitingBlock, 6796 ExitCountKind Kind) { 6797 switch (Kind) { 6798 case Exact: 6799 case SymbolicMaximum: 6800 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6801 case ConstantMaximum: 6802 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 6803 }; 6804 llvm_unreachable("Invalid ExitCountKind!"); 6805 } 6806 6807 const SCEV * 6808 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6809 SCEVUnionPredicate &Preds) { 6810 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6811 } 6812 6813 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6814 ExitCountKind Kind) { 6815 switch (Kind) { 6816 case Exact: 6817 return getBackedgeTakenInfo(L).getExact(L, this); 6818 case ConstantMaximum: 6819 return getBackedgeTakenInfo(L).getConstantMax(this); 6820 case SymbolicMaximum: 6821 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 6822 }; 6823 llvm_unreachable("Invalid ExitCountKind!"); 6824 } 6825 6826 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6827 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 6828 } 6829 6830 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6831 static void 6832 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6833 BasicBlock *Header = L->getHeader(); 6834 6835 // Push all Loop-header PHIs onto the Worklist stack. 6836 for (PHINode &PN : Header->phis()) 6837 Worklist.push_back(&PN); 6838 } 6839 6840 const ScalarEvolution::BackedgeTakenInfo & 6841 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6842 auto &BTI = getBackedgeTakenInfo(L); 6843 if (BTI.hasFullInfo()) 6844 return BTI; 6845 6846 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6847 6848 if (!Pair.second) 6849 return Pair.first->second; 6850 6851 BackedgeTakenInfo Result = 6852 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6853 6854 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6855 } 6856 6857 ScalarEvolution::BackedgeTakenInfo & 6858 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6859 // Initially insert an invalid entry for this loop. If the insertion 6860 // succeeds, proceed to actually compute a backedge-taken count and 6861 // update the value. The temporary CouldNotCompute value tells SCEV 6862 // code elsewhere that it shouldn't attempt to request a new 6863 // backedge-taken count, which could result in infinite recursion. 6864 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6865 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6866 if (!Pair.second) 6867 return Pair.first->second; 6868 6869 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6870 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6871 // must be cleared in this scope. 6872 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6873 6874 // In product build, there are no usage of statistic. 6875 (void)NumTripCountsComputed; 6876 (void)NumTripCountsNotComputed; 6877 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6878 const SCEV *BEExact = Result.getExact(L, this); 6879 if (BEExact != getCouldNotCompute()) { 6880 assert(isLoopInvariant(BEExact, L) && 6881 isLoopInvariant(Result.getConstantMax(this), L) && 6882 "Computed backedge-taken count isn't loop invariant for loop!"); 6883 ++NumTripCountsComputed; 6884 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 6885 isa<PHINode>(L->getHeader()->begin())) { 6886 // Only count loops that have phi nodes as not being computable. 6887 ++NumTripCountsNotComputed; 6888 } 6889 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6890 6891 // Now that we know more about the trip count for this loop, forget any 6892 // existing SCEV values for PHI nodes in this loop since they are only 6893 // conservative estimates made without the benefit of trip count 6894 // information. This is similar to the code in forgetLoop, except that 6895 // it handles SCEVUnknown PHI nodes specially. 6896 if (Result.hasAnyInfo()) { 6897 SmallVector<Instruction *, 16> Worklist; 6898 PushLoopPHIs(L, Worklist); 6899 6900 SmallPtrSet<Instruction *, 8> Discovered; 6901 while (!Worklist.empty()) { 6902 Instruction *I = Worklist.pop_back_val(); 6903 6904 ValueExprMapType::iterator It = 6905 ValueExprMap.find_as(static_cast<Value *>(I)); 6906 if (It != ValueExprMap.end()) { 6907 const SCEV *Old = It->second; 6908 6909 // SCEVUnknown for a PHI either means that it has an unrecognized 6910 // structure, or it's a PHI that's in the progress of being computed 6911 // by createNodeForPHI. In the former case, additional loop trip 6912 // count information isn't going to change anything. In the later 6913 // case, createNodeForPHI will perform the necessary updates on its 6914 // own when it gets to that point. 6915 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6916 eraseValueFromMap(It->first); 6917 forgetMemoizedResults(Old); 6918 } 6919 if (PHINode *PN = dyn_cast<PHINode>(I)) 6920 ConstantEvolutionLoopExitValue.erase(PN); 6921 } 6922 6923 // Since we don't need to invalidate anything for correctness and we're 6924 // only invalidating to make SCEV's results more precise, we get to stop 6925 // early to avoid invalidating too much. This is especially important in 6926 // cases like: 6927 // 6928 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6929 // loop0: 6930 // %pn0 = phi 6931 // ... 6932 // loop1: 6933 // %pn1 = phi 6934 // ... 6935 // 6936 // where both loop0 and loop1's backedge taken count uses the SCEV 6937 // expression for %v. If we don't have the early stop below then in cases 6938 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6939 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6940 // count for loop1, effectively nullifying SCEV's trip count cache. 6941 for (auto *U : I->users()) 6942 if (auto *I = dyn_cast<Instruction>(U)) { 6943 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6944 if (LoopForUser && L->contains(LoopForUser) && 6945 Discovered.insert(I).second) 6946 Worklist.push_back(I); 6947 } 6948 } 6949 } 6950 6951 // Re-lookup the insert position, since the call to 6952 // computeBackedgeTakenCount above could result in a 6953 // recusive call to getBackedgeTakenInfo (on a different 6954 // loop), which would invalidate the iterator computed 6955 // earlier. 6956 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6957 } 6958 6959 void ScalarEvolution::forgetAllLoops() { 6960 // This method is intended to forget all info about loops. It should 6961 // invalidate caches as if the following happened: 6962 // - The trip counts of all loops have changed arbitrarily 6963 // - Every llvm::Value has been updated in place to produce a different 6964 // result. 6965 BackedgeTakenCounts.clear(); 6966 PredicatedBackedgeTakenCounts.clear(); 6967 LoopPropertiesCache.clear(); 6968 ConstantEvolutionLoopExitValue.clear(); 6969 ValueExprMap.clear(); 6970 ValuesAtScopes.clear(); 6971 LoopDispositions.clear(); 6972 BlockDispositions.clear(); 6973 UnsignedRanges.clear(); 6974 SignedRanges.clear(); 6975 ExprValueMap.clear(); 6976 HasRecMap.clear(); 6977 MinTrailingZerosCache.clear(); 6978 PredicatedSCEVRewrites.clear(); 6979 } 6980 6981 void ScalarEvolution::forgetLoop(const Loop *L) { 6982 // Drop any stored trip count value. 6983 auto RemoveLoopFromBackedgeMap = 6984 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6985 auto BTCPos = Map.find(L); 6986 if (BTCPos != Map.end()) { 6987 BTCPos->second.clear(); 6988 Map.erase(BTCPos); 6989 } 6990 }; 6991 6992 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6993 SmallVector<Instruction *, 32> Worklist; 6994 SmallPtrSet<Instruction *, 16> Visited; 6995 6996 // Iterate over all the loops and sub-loops to drop SCEV information. 6997 while (!LoopWorklist.empty()) { 6998 auto *CurrL = LoopWorklist.pop_back_val(); 6999 7000 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 7001 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 7002 7003 // Drop information about predicated SCEV rewrites for this loop. 7004 for (auto I = PredicatedSCEVRewrites.begin(); 7005 I != PredicatedSCEVRewrites.end();) { 7006 std::pair<const SCEV *, const Loop *> Entry = I->first; 7007 if (Entry.second == CurrL) 7008 PredicatedSCEVRewrites.erase(I++); 7009 else 7010 ++I; 7011 } 7012 7013 auto LoopUsersItr = LoopUsers.find(CurrL); 7014 if (LoopUsersItr != LoopUsers.end()) { 7015 for (auto *S : LoopUsersItr->second) 7016 forgetMemoizedResults(S); 7017 LoopUsers.erase(LoopUsersItr); 7018 } 7019 7020 // Drop information about expressions based on loop-header PHIs. 7021 PushLoopPHIs(CurrL, Worklist); 7022 7023 while (!Worklist.empty()) { 7024 Instruction *I = Worklist.pop_back_val(); 7025 if (!Visited.insert(I).second) 7026 continue; 7027 7028 ValueExprMapType::iterator It = 7029 ValueExprMap.find_as(static_cast<Value *>(I)); 7030 if (It != ValueExprMap.end()) { 7031 eraseValueFromMap(It->first); 7032 forgetMemoizedResults(It->second); 7033 if (PHINode *PN = dyn_cast<PHINode>(I)) 7034 ConstantEvolutionLoopExitValue.erase(PN); 7035 } 7036 7037 PushDefUseChildren(I, Worklist); 7038 } 7039 7040 LoopPropertiesCache.erase(CurrL); 7041 // Forget all contained loops too, to avoid dangling entries in the 7042 // ValuesAtScopes map. 7043 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7044 } 7045 } 7046 7047 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7048 while (Loop *Parent = L->getParentLoop()) 7049 L = Parent; 7050 forgetLoop(L); 7051 } 7052 7053 void ScalarEvolution::forgetValue(Value *V) { 7054 Instruction *I = dyn_cast<Instruction>(V); 7055 if (!I) return; 7056 7057 // Drop information about expressions based on loop-header PHIs. 7058 SmallVector<Instruction *, 16> Worklist; 7059 Worklist.push_back(I); 7060 7061 SmallPtrSet<Instruction *, 8> Visited; 7062 while (!Worklist.empty()) { 7063 I = Worklist.pop_back_val(); 7064 if (!Visited.insert(I).second) 7065 continue; 7066 7067 ValueExprMapType::iterator It = 7068 ValueExprMap.find_as(static_cast<Value *>(I)); 7069 if (It != ValueExprMap.end()) { 7070 eraseValueFromMap(It->first); 7071 forgetMemoizedResults(It->second); 7072 if (PHINode *PN = dyn_cast<PHINode>(I)) 7073 ConstantEvolutionLoopExitValue.erase(PN); 7074 } 7075 7076 PushDefUseChildren(I, Worklist); 7077 } 7078 } 7079 7080 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7081 LoopDispositions.clear(); 7082 } 7083 7084 /// Get the exact loop backedge taken count considering all loop exits. A 7085 /// computable result can only be returned for loops with all exiting blocks 7086 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7087 /// is never skipped. This is a valid assumption as long as the loop exits via 7088 /// that test. For precise results, it is the caller's responsibility to specify 7089 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7090 const SCEV * 7091 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7092 SCEVUnionPredicate *Preds) const { 7093 // If any exits were not computable, the loop is not computable. 7094 if (!isComplete() || ExitNotTaken.empty()) 7095 return SE->getCouldNotCompute(); 7096 7097 const BasicBlock *Latch = L->getLoopLatch(); 7098 // All exiting blocks we have collected must dominate the only backedge. 7099 if (!Latch) 7100 return SE->getCouldNotCompute(); 7101 7102 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7103 // count is simply a minimum out of all these calculated exit counts. 7104 SmallVector<const SCEV *, 2> Ops; 7105 for (auto &ENT : ExitNotTaken) { 7106 const SCEV *BECount = ENT.ExactNotTaken; 7107 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7108 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7109 "We should only have known counts for exiting blocks that dominate " 7110 "latch!"); 7111 7112 Ops.push_back(BECount); 7113 7114 if (Preds && !ENT.hasAlwaysTruePredicate()) 7115 Preds->add(ENT.Predicate.get()); 7116 7117 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7118 "Predicate should be always true!"); 7119 } 7120 7121 return SE->getUMinFromMismatchedTypes(Ops); 7122 } 7123 7124 /// Get the exact not taken count for this loop exit. 7125 const SCEV * 7126 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7127 ScalarEvolution *SE) const { 7128 for (auto &ENT : ExitNotTaken) 7129 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7130 return ENT.ExactNotTaken; 7131 7132 return SE->getCouldNotCompute(); 7133 } 7134 7135 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7136 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7137 for (auto &ENT : ExitNotTaken) 7138 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7139 return ENT.MaxNotTaken; 7140 7141 return SE->getCouldNotCompute(); 7142 } 7143 7144 /// getConstantMax - Get the constant max backedge taken count for the loop. 7145 const SCEV * 7146 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7147 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7148 return !ENT.hasAlwaysTruePredicate(); 7149 }; 7150 7151 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7152 return SE->getCouldNotCompute(); 7153 7154 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7155 isa<SCEVConstant>(getConstantMax())) && 7156 "No point in having a non-constant max backedge taken count!"); 7157 return getConstantMax(); 7158 } 7159 7160 const SCEV * 7161 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7162 ScalarEvolution *SE) { 7163 if (!SymbolicMax) 7164 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7165 return SymbolicMax; 7166 } 7167 7168 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7169 ScalarEvolution *SE) const { 7170 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7171 return !ENT.hasAlwaysTruePredicate(); 7172 }; 7173 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7174 } 7175 7176 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7177 ScalarEvolution *SE) const { 7178 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() && 7179 SE->hasOperand(getConstantMax(), S)) 7180 return true; 7181 7182 for (auto &ENT : ExitNotTaken) 7183 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7184 SE->hasOperand(ENT.ExactNotTaken, S)) 7185 return true; 7186 7187 return false; 7188 } 7189 7190 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7191 : ExactNotTaken(E), MaxNotTaken(E) { 7192 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7193 isa<SCEVConstant>(MaxNotTaken)) && 7194 "No point in having a non-constant max backedge taken count!"); 7195 } 7196 7197 ScalarEvolution::ExitLimit::ExitLimit( 7198 const SCEV *E, const SCEV *M, bool MaxOrZero, 7199 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7200 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7201 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7202 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7203 "Exact is not allowed to be less precise than Max"); 7204 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7205 isa<SCEVConstant>(MaxNotTaken)) && 7206 "No point in having a non-constant max backedge taken count!"); 7207 for (auto *PredSet : PredSetList) 7208 for (auto *P : *PredSet) 7209 addPredicate(P); 7210 } 7211 7212 ScalarEvolution::ExitLimit::ExitLimit( 7213 const SCEV *E, const SCEV *M, bool MaxOrZero, 7214 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7215 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7216 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7217 isa<SCEVConstant>(MaxNotTaken)) && 7218 "No point in having a non-constant max backedge taken count!"); 7219 } 7220 7221 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7222 bool MaxOrZero) 7223 : ExitLimit(E, M, MaxOrZero, None) { 7224 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7225 isa<SCEVConstant>(MaxNotTaken)) && 7226 "No point in having a non-constant max backedge taken count!"); 7227 } 7228 7229 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7230 /// computable exit into a persistent ExitNotTakenInfo array. 7231 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7232 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7233 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7234 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7235 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7236 7237 ExitNotTaken.reserve(ExitCounts.size()); 7238 std::transform( 7239 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7240 [&](const EdgeExitInfo &EEI) { 7241 BasicBlock *ExitBB = EEI.first; 7242 const ExitLimit &EL = EEI.second; 7243 if (EL.Predicates.empty()) 7244 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7245 nullptr); 7246 7247 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7248 for (auto *Pred : EL.Predicates) 7249 Predicate->add(Pred); 7250 7251 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7252 std::move(Predicate)); 7253 }); 7254 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7255 isa<SCEVConstant>(ConstantMax)) && 7256 "No point in having a non-constant max backedge taken count!"); 7257 } 7258 7259 /// Invalidate this result and free the ExitNotTakenInfo array. 7260 void ScalarEvolution::BackedgeTakenInfo::clear() { 7261 ExitNotTaken.clear(); 7262 } 7263 7264 /// Compute the number of times the backedge of the specified loop will execute. 7265 ScalarEvolution::BackedgeTakenInfo 7266 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7267 bool AllowPredicates) { 7268 SmallVector<BasicBlock *, 8> ExitingBlocks; 7269 L->getExitingBlocks(ExitingBlocks); 7270 7271 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7272 7273 SmallVector<EdgeExitInfo, 4> ExitCounts; 7274 bool CouldComputeBECount = true; 7275 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7276 const SCEV *MustExitMaxBECount = nullptr; 7277 const SCEV *MayExitMaxBECount = nullptr; 7278 bool MustExitMaxOrZero = false; 7279 7280 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7281 // and compute maxBECount. 7282 // Do a union of all the predicates here. 7283 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7284 BasicBlock *ExitBB = ExitingBlocks[i]; 7285 7286 // We canonicalize untaken exits to br (constant), ignore them so that 7287 // proving an exit untaken doesn't negatively impact our ability to reason 7288 // about the loop as whole. 7289 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7290 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7291 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7292 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7293 continue; 7294 } 7295 7296 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7297 7298 assert((AllowPredicates || EL.Predicates.empty()) && 7299 "Predicated exit limit when predicates are not allowed!"); 7300 7301 // 1. For each exit that can be computed, add an entry to ExitCounts. 7302 // CouldComputeBECount is true only if all exits can be computed. 7303 if (EL.ExactNotTaken == getCouldNotCompute()) 7304 // We couldn't compute an exact value for this exit, so 7305 // we won't be able to compute an exact value for the loop. 7306 CouldComputeBECount = false; 7307 else 7308 ExitCounts.emplace_back(ExitBB, EL); 7309 7310 // 2. Derive the loop's MaxBECount from each exit's max number of 7311 // non-exiting iterations. Partition the loop exits into two kinds: 7312 // LoopMustExits and LoopMayExits. 7313 // 7314 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7315 // is a LoopMayExit. If any computable LoopMustExit is found, then 7316 // MaxBECount is the minimum EL.MaxNotTaken of computable 7317 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7318 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7319 // computable EL.MaxNotTaken. 7320 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7321 DT.dominates(ExitBB, Latch)) { 7322 if (!MustExitMaxBECount) { 7323 MustExitMaxBECount = EL.MaxNotTaken; 7324 MustExitMaxOrZero = EL.MaxOrZero; 7325 } else { 7326 MustExitMaxBECount = 7327 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7328 } 7329 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7330 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7331 MayExitMaxBECount = EL.MaxNotTaken; 7332 else { 7333 MayExitMaxBECount = 7334 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7335 } 7336 } 7337 } 7338 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7339 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7340 // The loop backedge will be taken the maximum or zero times if there's 7341 // a single exit that must be taken the maximum or zero times. 7342 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7343 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7344 MaxBECount, MaxOrZero); 7345 } 7346 7347 ScalarEvolution::ExitLimit 7348 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7349 bool AllowPredicates) { 7350 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7351 // If our exiting block does not dominate the latch, then its connection with 7352 // loop's exit limit may be far from trivial. 7353 const BasicBlock *Latch = L->getLoopLatch(); 7354 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7355 return getCouldNotCompute(); 7356 7357 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7358 Instruction *Term = ExitingBlock->getTerminator(); 7359 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7360 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7361 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7362 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7363 "It should have one successor in loop and one exit block!"); 7364 // Proceed to the next level to examine the exit condition expression. 7365 return computeExitLimitFromCond( 7366 L, BI->getCondition(), ExitIfTrue, 7367 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7368 } 7369 7370 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7371 // For switch, make sure that there is a single exit from the loop. 7372 BasicBlock *Exit = nullptr; 7373 for (auto *SBB : successors(ExitingBlock)) 7374 if (!L->contains(SBB)) { 7375 if (Exit) // Multiple exit successors. 7376 return getCouldNotCompute(); 7377 Exit = SBB; 7378 } 7379 assert(Exit && "Exiting block must have at least one exit"); 7380 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7381 /*ControlsExit=*/IsOnlyExit); 7382 } 7383 7384 return getCouldNotCompute(); 7385 } 7386 7387 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7388 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7389 bool ControlsExit, bool AllowPredicates) { 7390 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7391 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7392 ControlsExit, AllowPredicates); 7393 } 7394 7395 Optional<ScalarEvolution::ExitLimit> 7396 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7397 bool ExitIfTrue, bool ControlsExit, 7398 bool AllowPredicates) { 7399 (void)this->L; 7400 (void)this->ExitIfTrue; 7401 (void)this->AllowPredicates; 7402 7403 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7404 this->AllowPredicates == AllowPredicates && 7405 "Variance in assumed invariant key components!"); 7406 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7407 if (Itr == TripCountMap.end()) 7408 return None; 7409 return Itr->second; 7410 } 7411 7412 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7413 bool ExitIfTrue, 7414 bool ControlsExit, 7415 bool AllowPredicates, 7416 const ExitLimit &EL) { 7417 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7418 this->AllowPredicates == AllowPredicates && 7419 "Variance in assumed invariant key components!"); 7420 7421 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7422 assert(InsertResult.second && "Expected successful insertion!"); 7423 (void)InsertResult; 7424 (void)ExitIfTrue; 7425 } 7426 7427 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7428 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7429 bool ControlsExit, bool AllowPredicates) { 7430 7431 if (auto MaybeEL = 7432 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7433 return *MaybeEL; 7434 7435 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7436 ControlsExit, AllowPredicates); 7437 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7438 return EL; 7439 } 7440 7441 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7442 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7443 bool ControlsExit, bool AllowPredicates) { 7444 // Check if the controlling expression for this loop is an And or Or. 7445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7446 if (BO->getOpcode() == Instruction::And) { 7447 // Recurse on the operands of the and. 7448 bool EitherMayExit = !ExitIfTrue; 7449 ExitLimit EL0 = computeExitLimitFromCondCached( 7450 Cache, L, BO->getOperand(0), ExitIfTrue, 7451 ControlsExit && !EitherMayExit, AllowPredicates); 7452 ExitLimit EL1 = computeExitLimitFromCondCached( 7453 Cache, L, BO->getOperand(1), ExitIfTrue, 7454 ControlsExit && !EitherMayExit, AllowPredicates); 7455 // Be robust against unsimplified IR for the form "and i1 X, true" 7456 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7457 return CI->isOne() ? EL0 : EL1; 7458 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7459 return CI->isOne() ? EL1 : EL0; 7460 const SCEV *BECount = getCouldNotCompute(); 7461 const SCEV *MaxBECount = getCouldNotCompute(); 7462 if (EitherMayExit) { 7463 // Both conditions must be true for the loop to continue executing. 7464 // Choose the less conservative count. 7465 if (EL0.ExactNotTaken == getCouldNotCompute() || 7466 EL1.ExactNotTaken == getCouldNotCompute()) 7467 BECount = getCouldNotCompute(); 7468 else 7469 BECount = 7470 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7471 if (EL0.MaxNotTaken == getCouldNotCompute()) 7472 MaxBECount = EL1.MaxNotTaken; 7473 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7474 MaxBECount = EL0.MaxNotTaken; 7475 else 7476 MaxBECount = 7477 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7478 } else { 7479 // Both conditions must be true at the same time for the loop to exit. 7480 // For now, be conservative. 7481 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7482 MaxBECount = EL0.MaxNotTaken; 7483 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7484 BECount = EL0.ExactNotTaken; 7485 } 7486 7487 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7488 // to be more aggressive when computing BECount than when computing 7489 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7490 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7491 // to not. 7492 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7493 !isa<SCEVCouldNotCompute>(BECount)) 7494 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7495 7496 return ExitLimit(BECount, MaxBECount, false, 7497 {&EL0.Predicates, &EL1.Predicates}); 7498 } 7499 if (BO->getOpcode() == Instruction::Or) { 7500 // Recurse on the operands of the or. 7501 bool EitherMayExit = ExitIfTrue; 7502 ExitLimit EL0 = computeExitLimitFromCondCached( 7503 Cache, L, BO->getOperand(0), ExitIfTrue, 7504 ControlsExit && !EitherMayExit, AllowPredicates); 7505 ExitLimit EL1 = computeExitLimitFromCondCached( 7506 Cache, L, BO->getOperand(1), ExitIfTrue, 7507 ControlsExit && !EitherMayExit, AllowPredicates); 7508 // Be robust against unsimplified IR for the form "or i1 X, true" 7509 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7510 return CI->isZero() ? EL0 : EL1; 7511 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7512 return CI->isZero() ? EL1 : EL0; 7513 const SCEV *BECount = getCouldNotCompute(); 7514 const SCEV *MaxBECount = getCouldNotCompute(); 7515 if (EitherMayExit) { 7516 // Both conditions must be false for the loop to continue executing. 7517 // Choose the less conservative count. 7518 if (EL0.ExactNotTaken == getCouldNotCompute() || 7519 EL1.ExactNotTaken == getCouldNotCompute()) 7520 BECount = getCouldNotCompute(); 7521 else 7522 BECount = 7523 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7524 if (EL0.MaxNotTaken == getCouldNotCompute()) 7525 MaxBECount = EL1.MaxNotTaken; 7526 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7527 MaxBECount = EL0.MaxNotTaken; 7528 else 7529 MaxBECount = 7530 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7531 } else { 7532 // Both conditions must be false at the same time for the loop to exit. 7533 // For now, be conservative. 7534 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7535 MaxBECount = EL0.MaxNotTaken; 7536 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7537 BECount = EL0.ExactNotTaken; 7538 } 7539 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7540 // to be more aggressive when computing BECount than when computing 7541 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7542 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7543 // to not. 7544 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7545 !isa<SCEVCouldNotCompute>(BECount)) 7546 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7547 7548 return ExitLimit(BECount, MaxBECount, false, 7549 {&EL0.Predicates, &EL1.Predicates}); 7550 } 7551 } 7552 7553 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7554 // Proceed to the next level to examine the icmp. 7555 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7556 ExitLimit EL = 7557 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7558 if (EL.hasFullInfo() || !AllowPredicates) 7559 return EL; 7560 7561 // Try again, but use SCEV predicates this time. 7562 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7563 /*AllowPredicates=*/true); 7564 } 7565 7566 // Check for a constant condition. These are normally stripped out by 7567 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7568 // preserve the CFG and is temporarily leaving constant conditions 7569 // in place. 7570 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7571 if (ExitIfTrue == !CI->getZExtValue()) 7572 // The backedge is always taken. 7573 return getCouldNotCompute(); 7574 else 7575 // The backedge is never taken. 7576 return getZero(CI->getType()); 7577 } 7578 7579 // If it's not an integer or pointer comparison then compute it the hard way. 7580 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7581 } 7582 7583 ScalarEvolution::ExitLimit 7584 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7585 ICmpInst *ExitCond, 7586 bool ExitIfTrue, 7587 bool ControlsExit, 7588 bool AllowPredicates) { 7589 // If the condition was exit on true, convert the condition to exit on false 7590 ICmpInst::Predicate Pred; 7591 if (!ExitIfTrue) 7592 Pred = ExitCond->getPredicate(); 7593 else 7594 Pred = ExitCond->getInversePredicate(); 7595 const ICmpInst::Predicate OriginalPred = Pred; 7596 7597 // Handle common loops like: for (X = "string"; *X; ++X) 7598 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7599 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7600 ExitLimit ItCnt = 7601 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7602 if (ItCnt.hasAnyInfo()) 7603 return ItCnt; 7604 } 7605 7606 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7607 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7608 7609 // Try to evaluate any dependencies out of the loop. 7610 LHS = getSCEVAtScope(LHS, L); 7611 RHS = getSCEVAtScope(RHS, L); 7612 7613 // At this point, we would like to compute how many iterations of the 7614 // loop the predicate will return true for these inputs. 7615 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7616 // If there is a loop-invariant, force it into the RHS. 7617 std::swap(LHS, RHS); 7618 Pred = ICmpInst::getSwappedPredicate(Pred); 7619 } 7620 7621 // Simplify the operands before analyzing them. 7622 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7623 7624 // If we have a comparison of a chrec against a constant, try to use value 7625 // ranges to answer this query. 7626 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7627 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7628 if (AddRec->getLoop() == L) { 7629 // Form the constant range. 7630 ConstantRange CompRange = 7631 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7632 7633 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7634 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7635 } 7636 7637 switch (Pred) { 7638 case ICmpInst::ICMP_NE: { // while (X != Y) 7639 // Convert to: while (X-Y != 0) 7640 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7641 AllowPredicates); 7642 if (EL.hasAnyInfo()) return EL; 7643 break; 7644 } 7645 case ICmpInst::ICMP_EQ: { // while (X == Y) 7646 // Convert to: while (X-Y == 0) 7647 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7648 if (EL.hasAnyInfo()) return EL; 7649 break; 7650 } 7651 case ICmpInst::ICMP_SLT: 7652 case ICmpInst::ICMP_ULT: { // while (X < Y) 7653 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7654 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7655 AllowPredicates); 7656 if (EL.hasAnyInfo()) return EL; 7657 break; 7658 } 7659 case ICmpInst::ICMP_SGT: 7660 case ICmpInst::ICMP_UGT: { // while (X > Y) 7661 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7662 ExitLimit EL = 7663 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7664 AllowPredicates); 7665 if (EL.hasAnyInfo()) return EL; 7666 break; 7667 } 7668 default: 7669 break; 7670 } 7671 7672 auto *ExhaustiveCount = 7673 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7674 7675 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7676 return ExhaustiveCount; 7677 7678 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7679 ExitCond->getOperand(1), L, OriginalPred); 7680 } 7681 7682 ScalarEvolution::ExitLimit 7683 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7684 SwitchInst *Switch, 7685 BasicBlock *ExitingBlock, 7686 bool ControlsExit) { 7687 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7688 7689 // Give up if the exit is the default dest of a switch. 7690 if (Switch->getDefaultDest() == ExitingBlock) 7691 return getCouldNotCompute(); 7692 7693 assert(L->contains(Switch->getDefaultDest()) && 7694 "Default case must not exit the loop!"); 7695 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7696 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7697 7698 // while (X != Y) --> while (X-Y != 0) 7699 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7700 if (EL.hasAnyInfo()) 7701 return EL; 7702 7703 return getCouldNotCompute(); 7704 } 7705 7706 static ConstantInt * 7707 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7708 ScalarEvolution &SE) { 7709 const SCEV *InVal = SE.getConstant(C); 7710 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7711 assert(isa<SCEVConstant>(Val) && 7712 "Evaluation of SCEV at constant didn't fold correctly?"); 7713 return cast<SCEVConstant>(Val)->getValue(); 7714 } 7715 7716 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7717 /// compute the backedge execution count. 7718 ScalarEvolution::ExitLimit 7719 ScalarEvolution::computeLoadConstantCompareExitLimit( 7720 LoadInst *LI, 7721 Constant *RHS, 7722 const Loop *L, 7723 ICmpInst::Predicate predicate) { 7724 if (LI->isVolatile()) return getCouldNotCompute(); 7725 7726 // Check to see if the loaded pointer is a getelementptr of a global. 7727 // TODO: Use SCEV instead of manually grubbing with GEPs. 7728 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7729 if (!GEP) return getCouldNotCompute(); 7730 7731 // Make sure that it is really a constant global we are gepping, with an 7732 // initializer, and make sure the first IDX is really 0. 7733 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7734 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7735 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7736 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7737 return getCouldNotCompute(); 7738 7739 // Okay, we allow one non-constant index into the GEP instruction. 7740 Value *VarIdx = nullptr; 7741 std::vector<Constant*> Indexes; 7742 unsigned VarIdxNum = 0; 7743 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7744 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7745 Indexes.push_back(CI); 7746 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7747 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7748 VarIdx = GEP->getOperand(i); 7749 VarIdxNum = i-2; 7750 Indexes.push_back(nullptr); 7751 } 7752 7753 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7754 if (!VarIdx) 7755 return getCouldNotCompute(); 7756 7757 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7758 // Check to see if X is a loop variant variable value now. 7759 const SCEV *Idx = getSCEV(VarIdx); 7760 Idx = getSCEVAtScope(Idx, L); 7761 7762 // We can only recognize very limited forms of loop index expressions, in 7763 // particular, only affine AddRec's like {C1,+,C2}. 7764 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7765 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7766 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7767 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7768 return getCouldNotCompute(); 7769 7770 unsigned MaxSteps = MaxBruteForceIterations; 7771 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7772 ConstantInt *ItCst = ConstantInt::get( 7773 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7774 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7775 7776 // Form the GEP offset. 7777 Indexes[VarIdxNum] = Val; 7778 7779 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7780 Indexes); 7781 if (!Result) break; // Cannot compute! 7782 7783 // Evaluate the condition for this iteration. 7784 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7785 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7786 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7787 ++NumArrayLenItCounts; 7788 return getConstant(ItCst); // Found terminating iteration! 7789 } 7790 } 7791 return getCouldNotCompute(); 7792 } 7793 7794 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7795 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7796 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7797 if (!RHS) 7798 return getCouldNotCompute(); 7799 7800 const BasicBlock *Latch = L->getLoopLatch(); 7801 if (!Latch) 7802 return getCouldNotCompute(); 7803 7804 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7805 if (!Predecessor) 7806 return getCouldNotCompute(); 7807 7808 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7809 // Return LHS in OutLHS and shift_opt in OutOpCode. 7810 auto MatchPositiveShift = 7811 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7812 7813 using namespace PatternMatch; 7814 7815 ConstantInt *ShiftAmt; 7816 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7817 OutOpCode = Instruction::LShr; 7818 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7819 OutOpCode = Instruction::AShr; 7820 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7821 OutOpCode = Instruction::Shl; 7822 else 7823 return false; 7824 7825 return ShiftAmt->getValue().isStrictlyPositive(); 7826 }; 7827 7828 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7829 // 7830 // loop: 7831 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7832 // %iv.shifted = lshr i32 %iv, <positive constant> 7833 // 7834 // Return true on a successful match. Return the corresponding PHI node (%iv 7835 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7836 auto MatchShiftRecurrence = 7837 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7838 Optional<Instruction::BinaryOps> PostShiftOpCode; 7839 7840 { 7841 Instruction::BinaryOps OpC; 7842 Value *V; 7843 7844 // If we encounter a shift instruction, "peel off" the shift operation, 7845 // and remember that we did so. Later when we inspect %iv's backedge 7846 // value, we will make sure that the backedge value uses the same 7847 // operation. 7848 // 7849 // Note: the peeled shift operation does not have to be the same 7850 // instruction as the one feeding into the PHI's backedge value. We only 7851 // really care about it being the same *kind* of shift instruction -- 7852 // that's all that is required for our later inferences to hold. 7853 if (MatchPositiveShift(LHS, V, OpC)) { 7854 PostShiftOpCode = OpC; 7855 LHS = V; 7856 } 7857 } 7858 7859 PNOut = dyn_cast<PHINode>(LHS); 7860 if (!PNOut || PNOut->getParent() != L->getHeader()) 7861 return false; 7862 7863 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7864 Value *OpLHS; 7865 7866 return 7867 // The backedge value for the PHI node must be a shift by a positive 7868 // amount 7869 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7870 7871 // of the PHI node itself 7872 OpLHS == PNOut && 7873 7874 // and the kind of shift should be match the kind of shift we peeled 7875 // off, if any. 7876 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7877 }; 7878 7879 PHINode *PN; 7880 Instruction::BinaryOps OpCode; 7881 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7882 return getCouldNotCompute(); 7883 7884 const DataLayout &DL = getDataLayout(); 7885 7886 // The key rationale for this optimization is that for some kinds of shift 7887 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7888 // within a finite number of iterations. If the condition guarding the 7889 // backedge (in the sense that the backedge is taken if the condition is true) 7890 // is false for the value the shift recurrence stabilizes to, then we know 7891 // that the backedge is taken only a finite number of times. 7892 7893 ConstantInt *StableValue = nullptr; 7894 switch (OpCode) { 7895 default: 7896 llvm_unreachable("Impossible case!"); 7897 7898 case Instruction::AShr: { 7899 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7900 // bitwidth(K) iterations. 7901 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7902 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7903 Predecessor->getTerminator(), &DT); 7904 auto *Ty = cast<IntegerType>(RHS->getType()); 7905 if (Known.isNonNegative()) 7906 StableValue = ConstantInt::get(Ty, 0); 7907 else if (Known.isNegative()) 7908 StableValue = ConstantInt::get(Ty, -1, true); 7909 else 7910 return getCouldNotCompute(); 7911 7912 break; 7913 } 7914 case Instruction::LShr: 7915 case Instruction::Shl: 7916 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7917 // stabilize to 0 in at most bitwidth(K) iterations. 7918 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7919 break; 7920 } 7921 7922 auto *Result = 7923 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7924 assert(Result->getType()->isIntegerTy(1) && 7925 "Otherwise cannot be an operand to a branch instruction"); 7926 7927 if (Result->isZeroValue()) { 7928 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7929 const SCEV *UpperBound = 7930 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7931 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7932 } 7933 7934 return getCouldNotCompute(); 7935 } 7936 7937 /// Return true if we can constant fold an instruction of the specified type, 7938 /// assuming that all operands were constants. 7939 static bool CanConstantFold(const Instruction *I) { 7940 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7941 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7942 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7943 return true; 7944 7945 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7946 if (const Function *F = CI->getCalledFunction()) 7947 return canConstantFoldCallTo(CI, F); 7948 return false; 7949 } 7950 7951 /// Determine whether this instruction can constant evolve within this loop 7952 /// assuming its operands can all constant evolve. 7953 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7954 // An instruction outside of the loop can't be derived from a loop PHI. 7955 if (!L->contains(I)) return false; 7956 7957 if (isa<PHINode>(I)) { 7958 // We don't currently keep track of the control flow needed to evaluate 7959 // PHIs, so we cannot handle PHIs inside of loops. 7960 return L->getHeader() == I->getParent(); 7961 } 7962 7963 // If we won't be able to constant fold this expression even if the operands 7964 // are constants, bail early. 7965 return CanConstantFold(I); 7966 } 7967 7968 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7969 /// recursing through each instruction operand until reaching a loop header phi. 7970 static PHINode * 7971 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7972 DenseMap<Instruction *, PHINode *> &PHIMap, 7973 unsigned Depth) { 7974 if (Depth > MaxConstantEvolvingDepth) 7975 return nullptr; 7976 7977 // Otherwise, we can evaluate this instruction if all of its operands are 7978 // constant or derived from a PHI node themselves. 7979 PHINode *PHI = nullptr; 7980 for (Value *Op : UseInst->operands()) { 7981 if (isa<Constant>(Op)) continue; 7982 7983 Instruction *OpInst = dyn_cast<Instruction>(Op); 7984 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7985 7986 PHINode *P = dyn_cast<PHINode>(OpInst); 7987 if (!P) 7988 // If this operand is already visited, reuse the prior result. 7989 // We may have P != PHI if this is the deepest point at which the 7990 // inconsistent paths meet. 7991 P = PHIMap.lookup(OpInst); 7992 if (!P) { 7993 // Recurse and memoize the results, whether a phi is found or not. 7994 // This recursive call invalidates pointers into PHIMap. 7995 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7996 PHIMap[OpInst] = P; 7997 } 7998 if (!P) 7999 return nullptr; // Not evolving from PHI 8000 if (PHI && PHI != P) 8001 return nullptr; // Evolving from multiple different PHIs. 8002 PHI = P; 8003 } 8004 // This is a expression evolving from a constant PHI! 8005 return PHI; 8006 } 8007 8008 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8009 /// in the loop that V is derived from. We allow arbitrary operations along the 8010 /// way, but the operands of an operation must either be constants or a value 8011 /// derived from a constant PHI. If this expression does not fit with these 8012 /// constraints, return null. 8013 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8014 Instruction *I = dyn_cast<Instruction>(V); 8015 if (!I || !canConstantEvolve(I, L)) return nullptr; 8016 8017 if (PHINode *PN = dyn_cast<PHINode>(I)) 8018 return PN; 8019 8020 // Record non-constant instructions contained by the loop. 8021 DenseMap<Instruction *, PHINode *> PHIMap; 8022 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8023 } 8024 8025 /// EvaluateExpression - Given an expression that passes the 8026 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8027 /// in the loop has the value PHIVal. If we can't fold this expression for some 8028 /// reason, return null. 8029 static Constant *EvaluateExpression(Value *V, const Loop *L, 8030 DenseMap<Instruction *, Constant *> &Vals, 8031 const DataLayout &DL, 8032 const TargetLibraryInfo *TLI) { 8033 // Convenient constant check, but redundant for recursive calls. 8034 if (Constant *C = dyn_cast<Constant>(V)) return C; 8035 Instruction *I = dyn_cast<Instruction>(V); 8036 if (!I) return nullptr; 8037 8038 if (Constant *C = Vals.lookup(I)) return C; 8039 8040 // An instruction inside the loop depends on a value outside the loop that we 8041 // weren't given a mapping for, or a value such as a call inside the loop. 8042 if (!canConstantEvolve(I, L)) return nullptr; 8043 8044 // An unmapped PHI can be due to a branch or another loop inside this loop, 8045 // or due to this not being the initial iteration through a loop where we 8046 // couldn't compute the evolution of this particular PHI last time. 8047 if (isa<PHINode>(I)) return nullptr; 8048 8049 std::vector<Constant*> Operands(I->getNumOperands()); 8050 8051 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8052 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8053 if (!Operand) { 8054 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8055 if (!Operands[i]) return nullptr; 8056 continue; 8057 } 8058 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8059 Vals[Operand] = C; 8060 if (!C) return nullptr; 8061 Operands[i] = C; 8062 } 8063 8064 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8065 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8066 Operands[1], DL, TLI); 8067 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8068 if (!LI->isVolatile()) 8069 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8070 } 8071 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8072 } 8073 8074 8075 // If every incoming value to PN except the one for BB is a specific Constant, 8076 // return that, else return nullptr. 8077 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8078 Constant *IncomingVal = nullptr; 8079 8080 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8081 if (PN->getIncomingBlock(i) == BB) 8082 continue; 8083 8084 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8085 if (!CurrentVal) 8086 return nullptr; 8087 8088 if (IncomingVal != CurrentVal) { 8089 if (IncomingVal) 8090 return nullptr; 8091 IncomingVal = CurrentVal; 8092 } 8093 } 8094 8095 return IncomingVal; 8096 } 8097 8098 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8099 /// in the header of its containing loop, we know the loop executes a 8100 /// constant number of times, and the PHI node is just a recurrence 8101 /// involving constants, fold it. 8102 Constant * 8103 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8104 const APInt &BEs, 8105 const Loop *L) { 8106 auto I = ConstantEvolutionLoopExitValue.find(PN); 8107 if (I != ConstantEvolutionLoopExitValue.end()) 8108 return I->second; 8109 8110 if (BEs.ugt(MaxBruteForceIterations)) 8111 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8112 8113 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8114 8115 DenseMap<Instruction *, Constant *> CurrentIterVals; 8116 BasicBlock *Header = L->getHeader(); 8117 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8118 8119 BasicBlock *Latch = L->getLoopLatch(); 8120 if (!Latch) 8121 return nullptr; 8122 8123 for (PHINode &PHI : Header->phis()) { 8124 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8125 CurrentIterVals[&PHI] = StartCST; 8126 } 8127 if (!CurrentIterVals.count(PN)) 8128 return RetVal = nullptr; 8129 8130 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8131 8132 // Execute the loop symbolically to determine the exit value. 8133 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8134 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8135 8136 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8137 unsigned IterationNum = 0; 8138 const DataLayout &DL = getDataLayout(); 8139 for (; ; ++IterationNum) { 8140 if (IterationNum == NumIterations) 8141 return RetVal = CurrentIterVals[PN]; // Got exit value! 8142 8143 // Compute the value of the PHIs for the next iteration. 8144 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8145 DenseMap<Instruction *, Constant *> NextIterVals; 8146 Constant *NextPHI = 8147 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8148 if (!NextPHI) 8149 return nullptr; // Couldn't evaluate! 8150 NextIterVals[PN] = NextPHI; 8151 8152 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8153 8154 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8155 // cease to be able to evaluate one of them or if they stop evolving, 8156 // because that doesn't necessarily prevent us from computing PN. 8157 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8158 for (const auto &I : CurrentIterVals) { 8159 PHINode *PHI = dyn_cast<PHINode>(I.first); 8160 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8161 PHIsToCompute.emplace_back(PHI, I.second); 8162 } 8163 // We use two distinct loops because EvaluateExpression may invalidate any 8164 // iterators into CurrentIterVals. 8165 for (const auto &I : PHIsToCompute) { 8166 PHINode *PHI = I.first; 8167 Constant *&NextPHI = NextIterVals[PHI]; 8168 if (!NextPHI) { // Not already computed. 8169 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8170 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8171 } 8172 if (NextPHI != I.second) 8173 StoppedEvolving = false; 8174 } 8175 8176 // If all entries in CurrentIterVals == NextIterVals then we can stop 8177 // iterating, the loop can't continue to change. 8178 if (StoppedEvolving) 8179 return RetVal = CurrentIterVals[PN]; 8180 8181 CurrentIterVals.swap(NextIterVals); 8182 } 8183 } 8184 8185 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8186 Value *Cond, 8187 bool ExitWhen) { 8188 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8189 if (!PN) return getCouldNotCompute(); 8190 8191 // If the loop is canonicalized, the PHI will have exactly two entries. 8192 // That's the only form we support here. 8193 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8194 8195 DenseMap<Instruction *, Constant *> CurrentIterVals; 8196 BasicBlock *Header = L->getHeader(); 8197 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8198 8199 BasicBlock *Latch = L->getLoopLatch(); 8200 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8201 8202 for (PHINode &PHI : Header->phis()) { 8203 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8204 CurrentIterVals[&PHI] = StartCST; 8205 } 8206 if (!CurrentIterVals.count(PN)) 8207 return getCouldNotCompute(); 8208 8209 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8210 // the loop symbolically to determine when the condition gets a value of 8211 // "ExitWhen". 8212 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8213 const DataLayout &DL = getDataLayout(); 8214 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8215 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8216 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8217 8218 // Couldn't symbolically evaluate. 8219 if (!CondVal) return getCouldNotCompute(); 8220 8221 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8222 ++NumBruteForceTripCountsComputed; 8223 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8224 } 8225 8226 // Update all the PHI nodes for the next iteration. 8227 DenseMap<Instruction *, Constant *> NextIterVals; 8228 8229 // Create a list of which PHIs we need to compute. We want to do this before 8230 // calling EvaluateExpression on them because that may invalidate iterators 8231 // into CurrentIterVals. 8232 SmallVector<PHINode *, 8> PHIsToCompute; 8233 for (const auto &I : CurrentIterVals) { 8234 PHINode *PHI = dyn_cast<PHINode>(I.first); 8235 if (!PHI || PHI->getParent() != Header) continue; 8236 PHIsToCompute.push_back(PHI); 8237 } 8238 for (PHINode *PHI : PHIsToCompute) { 8239 Constant *&NextPHI = NextIterVals[PHI]; 8240 if (NextPHI) continue; // Already computed! 8241 8242 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8243 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8244 } 8245 CurrentIterVals.swap(NextIterVals); 8246 } 8247 8248 // Too many iterations were needed to evaluate. 8249 return getCouldNotCompute(); 8250 } 8251 8252 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8253 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8254 ValuesAtScopes[V]; 8255 // Check to see if we've folded this expression at this loop before. 8256 for (auto &LS : Values) 8257 if (LS.first == L) 8258 return LS.second ? LS.second : V; 8259 8260 Values.emplace_back(L, nullptr); 8261 8262 // Otherwise compute it. 8263 const SCEV *C = computeSCEVAtScope(V, L); 8264 for (auto &LS : reverse(ValuesAtScopes[V])) 8265 if (LS.first == L) { 8266 LS.second = C; 8267 break; 8268 } 8269 return C; 8270 } 8271 8272 /// This builds up a Constant using the ConstantExpr interface. That way, we 8273 /// will return Constants for objects which aren't represented by a 8274 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8275 /// Returns NULL if the SCEV isn't representable as a Constant. 8276 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8277 switch (V->getSCEVType()) { 8278 case scCouldNotCompute: 8279 case scAddRecExpr: 8280 return nullptr; 8281 case scConstant: 8282 return cast<SCEVConstant>(V)->getValue(); 8283 case scUnknown: 8284 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8285 case scSignExtend: { 8286 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8287 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8288 return ConstantExpr::getSExt(CastOp, SS->getType()); 8289 return nullptr; 8290 } 8291 case scZeroExtend: { 8292 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8293 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8294 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8295 return nullptr; 8296 } 8297 case scPtrToInt: { 8298 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8299 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8300 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8301 8302 return nullptr; 8303 } 8304 case scTruncate: { 8305 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8306 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8307 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8308 return nullptr; 8309 } 8310 case scAddExpr: { 8311 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8312 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8313 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8314 unsigned AS = PTy->getAddressSpace(); 8315 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8316 C = ConstantExpr::getBitCast(C, DestPtrTy); 8317 } 8318 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8319 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8320 if (!C2) 8321 return nullptr; 8322 8323 // First pointer! 8324 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8325 unsigned AS = C2->getType()->getPointerAddressSpace(); 8326 std::swap(C, C2); 8327 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8328 // The offsets have been converted to bytes. We can add bytes to an 8329 // i8* by GEP with the byte count in the first index. 8330 C = ConstantExpr::getBitCast(C, DestPtrTy); 8331 } 8332 8333 // Don't bother trying to sum two pointers. We probably can't 8334 // statically compute a load that results from it anyway. 8335 if (C2->getType()->isPointerTy()) 8336 return nullptr; 8337 8338 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8339 if (PTy->getElementType()->isStructTy()) 8340 C2 = ConstantExpr::getIntegerCast( 8341 C2, Type::getInt32Ty(C->getContext()), true); 8342 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8343 } else 8344 C = ConstantExpr::getAdd(C, C2); 8345 } 8346 return C; 8347 } 8348 return nullptr; 8349 } 8350 case scMulExpr: { 8351 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8352 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8353 // Don't bother with pointers at all. 8354 if (C->getType()->isPointerTy()) 8355 return nullptr; 8356 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8357 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8358 if (!C2 || C2->getType()->isPointerTy()) 8359 return nullptr; 8360 C = ConstantExpr::getMul(C, C2); 8361 } 8362 return C; 8363 } 8364 return nullptr; 8365 } 8366 case scUDivExpr: { 8367 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8368 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8369 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8370 if (LHS->getType() == RHS->getType()) 8371 return ConstantExpr::getUDiv(LHS, RHS); 8372 return nullptr; 8373 } 8374 case scSMaxExpr: 8375 case scUMaxExpr: 8376 case scSMinExpr: 8377 case scUMinExpr: 8378 return nullptr; // TODO: smax, umax, smin, umax. 8379 } 8380 llvm_unreachable("Unknown SCEV kind!"); 8381 } 8382 8383 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8384 if (isa<SCEVConstant>(V)) return V; 8385 8386 // If this instruction is evolved from a constant-evolving PHI, compute the 8387 // exit value from the loop without using SCEVs. 8388 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8389 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8390 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8391 const Loop *CurrLoop = this->LI[I->getParent()]; 8392 // Looking for loop exit value. 8393 if (CurrLoop && CurrLoop->getParentLoop() == L && 8394 PN->getParent() == CurrLoop->getHeader()) { 8395 // Okay, there is no closed form solution for the PHI node. Check 8396 // to see if the loop that contains it has a known backedge-taken 8397 // count. If so, we may be able to force computation of the exit 8398 // value. 8399 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8400 // This trivial case can show up in some degenerate cases where 8401 // the incoming IR has not yet been fully simplified. 8402 if (BackedgeTakenCount->isZero()) { 8403 Value *InitValue = nullptr; 8404 bool MultipleInitValues = false; 8405 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8406 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8407 if (!InitValue) 8408 InitValue = PN->getIncomingValue(i); 8409 else if (InitValue != PN->getIncomingValue(i)) { 8410 MultipleInitValues = true; 8411 break; 8412 } 8413 } 8414 } 8415 if (!MultipleInitValues && InitValue) 8416 return getSCEV(InitValue); 8417 } 8418 // Do we have a loop invariant value flowing around the backedge 8419 // for a loop which must execute the backedge? 8420 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8421 isKnownPositive(BackedgeTakenCount) && 8422 PN->getNumIncomingValues() == 2) { 8423 8424 unsigned InLoopPred = 8425 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8426 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8427 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8428 return getSCEV(BackedgeVal); 8429 } 8430 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8431 // Okay, we know how many times the containing loop executes. If 8432 // this is a constant evolving PHI node, get the final value at 8433 // the specified iteration number. 8434 Constant *RV = getConstantEvolutionLoopExitValue( 8435 PN, BTCC->getAPInt(), CurrLoop); 8436 if (RV) return getSCEV(RV); 8437 } 8438 } 8439 8440 // If there is a single-input Phi, evaluate it at our scope. If we can 8441 // prove that this replacement does not break LCSSA form, use new value. 8442 if (PN->getNumOperands() == 1) { 8443 const SCEV *Input = getSCEV(PN->getOperand(0)); 8444 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8445 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8446 // for the simplest case just support constants. 8447 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8448 } 8449 } 8450 8451 // Okay, this is an expression that we cannot symbolically evaluate 8452 // into a SCEV. Check to see if it's possible to symbolically evaluate 8453 // the arguments into constants, and if so, try to constant propagate the 8454 // result. This is particularly useful for computing loop exit values. 8455 if (CanConstantFold(I)) { 8456 SmallVector<Constant *, 4> Operands; 8457 bool MadeImprovement = false; 8458 for (Value *Op : I->operands()) { 8459 if (Constant *C = dyn_cast<Constant>(Op)) { 8460 Operands.push_back(C); 8461 continue; 8462 } 8463 8464 // If any of the operands is non-constant and if they are 8465 // non-integer and non-pointer, don't even try to analyze them 8466 // with scev techniques. 8467 if (!isSCEVable(Op->getType())) 8468 return V; 8469 8470 const SCEV *OrigV = getSCEV(Op); 8471 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8472 MadeImprovement |= OrigV != OpV; 8473 8474 Constant *C = BuildConstantFromSCEV(OpV); 8475 if (!C) return V; 8476 if (C->getType() != Op->getType()) 8477 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8478 Op->getType(), 8479 false), 8480 C, Op->getType()); 8481 Operands.push_back(C); 8482 } 8483 8484 // Check to see if getSCEVAtScope actually made an improvement. 8485 if (MadeImprovement) { 8486 Constant *C = nullptr; 8487 const DataLayout &DL = getDataLayout(); 8488 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8489 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8490 Operands[1], DL, &TLI); 8491 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8492 if (!Load->isVolatile()) 8493 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8494 DL); 8495 } else 8496 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8497 if (!C) return V; 8498 return getSCEV(C); 8499 } 8500 } 8501 } 8502 8503 // This is some other type of SCEVUnknown, just return it. 8504 return V; 8505 } 8506 8507 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8508 // Avoid performing the look-up in the common case where the specified 8509 // expression has no loop-variant portions. 8510 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8511 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8512 if (OpAtScope != Comm->getOperand(i)) { 8513 // Okay, at least one of these operands is loop variant but might be 8514 // foldable. Build a new instance of the folded commutative expression. 8515 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8516 Comm->op_begin()+i); 8517 NewOps.push_back(OpAtScope); 8518 8519 for (++i; i != e; ++i) { 8520 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8521 NewOps.push_back(OpAtScope); 8522 } 8523 if (isa<SCEVAddExpr>(Comm)) 8524 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8525 if (isa<SCEVMulExpr>(Comm)) 8526 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8527 if (isa<SCEVMinMaxExpr>(Comm)) 8528 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8529 llvm_unreachable("Unknown commutative SCEV type!"); 8530 } 8531 } 8532 // If we got here, all operands are loop invariant. 8533 return Comm; 8534 } 8535 8536 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8537 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8538 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8539 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8540 return Div; // must be loop invariant 8541 return getUDivExpr(LHS, RHS); 8542 } 8543 8544 // If this is a loop recurrence for a loop that does not contain L, then we 8545 // are dealing with the final value computed by the loop. 8546 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8547 // First, attempt to evaluate each operand. 8548 // Avoid performing the look-up in the common case where the specified 8549 // expression has no loop-variant portions. 8550 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8551 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8552 if (OpAtScope == AddRec->getOperand(i)) 8553 continue; 8554 8555 // Okay, at least one of these operands is loop variant but might be 8556 // foldable. Build a new instance of the folded commutative expression. 8557 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8558 AddRec->op_begin()+i); 8559 NewOps.push_back(OpAtScope); 8560 for (++i; i != e; ++i) 8561 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8562 8563 const SCEV *FoldedRec = 8564 getAddRecExpr(NewOps, AddRec->getLoop(), 8565 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8566 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8567 // The addrec may be folded to a nonrecurrence, for example, if the 8568 // induction variable is multiplied by zero after constant folding. Go 8569 // ahead and return the folded value. 8570 if (!AddRec) 8571 return FoldedRec; 8572 break; 8573 } 8574 8575 // If the scope is outside the addrec's loop, evaluate it by using the 8576 // loop exit value of the addrec. 8577 if (!AddRec->getLoop()->contains(L)) { 8578 // To evaluate this recurrence, we need to know how many times the AddRec 8579 // loop iterates. Compute this now. 8580 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8581 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8582 8583 // Then, evaluate the AddRec. 8584 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8585 } 8586 8587 return AddRec; 8588 } 8589 8590 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8591 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8592 if (Op == Cast->getOperand()) 8593 return Cast; // must be loop invariant 8594 return getZeroExtendExpr(Op, Cast->getType()); 8595 } 8596 8597 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8598 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8599 if (Op == Cast->getOperand()) 8600 return Cast; // must be loop invariant 8601 return getSignExtendExpr(Op, Cast->getType()); 8602 } 8603 8604 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8605 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8606 if (Op == Cast->getOperand()) 8607 return Cast; // must be loop invariant 8608 return getTruncateExpr(Op, Cast->getType()); 8609 } 8610 8611 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8612 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8613 if (Op == Cast->getOperand()) 8614 return Cast; // must be loop invariant 8615 return getPtrToIntExpr(Op, Cast->getType()); 8616 } 8617 8618 llvm_unreachable("Unknown SCEV type!"); 8619 } 8620 8621 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8622 return getSCEVAtScope(getSCEV(V), L); 8623 } 8624 8625 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8626 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8627 return stripInjectiveFunctions(ZExt->getOperand()); 8628 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8629 return stripInjectiveFunctions(SExt->getOperand()); 8630 return S; 8631 } 8632 8633 /// Finds the minimum unsigned root of the following equation: 8634 /// 8635 /// A * X = B (mod N) 8636 /// 8637 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8638 /// A and B isn't important. 8639 /// 8640 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8641 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8642 ScalarEvolution &SE) { 8643 uint32_t BW = A.getBitWidth(); 8644 assert(BW == SE.getTypeSizeInBits(B->getType())); 8645 assert(A != 0 && "A must be non-zero."); 8646 8647 // 1. D = gcd(A, N) 8648 // 8649 // The gcd of A and N may have only one prime factor: 2. The number of 8650 // trailing zeros in A is its multiplicity 8651 uint32_t Mult2 = A.countTrailingZeros(); 8652 // D = 2^Mult2 8653 8654 // 2. Check if B is divisible by D. 8655 // 8656 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8657 // is not less than multiplicity of this prime factor for D. 8658 if (SE.GetMinTrailingZeros(B) < Mult2) 8659 return SE.getCouldNotCompute(); 8660 8661 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8662 // modulo (N / D). 8663 // 8664 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8665 // (N / D) in general. The inverse itself always fits into BW bits, though, 8666 // so we immediately truncate it. 8667 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8668 APInt Mod(BW + 1, 0); 8669 Mod.setBit(BW - Mult2); // Mod = N / D 8670 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8671 8672 // 4. Compute the minimum unsigned root of the equation: 8673 // I * (B / D) mod (N / D) 8674 // To simplify the computation, we factor out the divide by D: 8675 // (I * B mod N) / D 8676 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8677 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8678 } 8679 8680 /// For a given quadratic addrec, generate coefficients of the corresponding 8681 /// quadratic equation, multiplied by a common value to ensure that they are 8682 /// integers. 8683 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8684 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8685 /// were multiplied by, and BitWidth is the bit width of the original addrec 8686 /// coefficients. 8687 /// This function returns None if the addrec coefficients are not compile- 8688 /// time constants. 8689 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8690 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8691 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8692 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8693 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8694 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8695 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8696 << *AddRec << '\n'); 8697 8698 // We currently can only solve this if the coefficients are constants. 8699 if (!LC || !MC || !NC) { 8700 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8701 return None; 8702 } 8703 8704 APInt L = LC->getAPInt(); 8705 APInt M = MC->getAPInt(); 8706 APInt N = NC->getAPInt(); 8707 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8708 8709 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8710 unsigned NewWidth = BitWidth + 1; 8711 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8712 << BitWidth << '\n'); 8713 // The sign-extension (as opposed to a zero-extension) here matches the 8714 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8715 N = N.sext(NewWidth); 8716 M = M.sext(NewWidth); 8717 L = L.sext(NewWidth); 8718 8719 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8720 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8721 // L+M, L+2M+N, L+3M+3N, ... 8722 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8723 // 8724 // The equation Acc = 0 is then 8725 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8726 // In a quadratic form it becomes: 8727 // N n^2 + (2M-N) n + 2L = 0. 8728 8729 APInt A = N; 8730 APInt B = 2 * M - A; 8731 APInt C = 2 * L; 8732 APInt T = APInt(NewWidth, 2); 8733 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8734 << "x + " << C << ", coeff bw: " << NewWidth 8735 << ", multiplied by " << T << '\n'); 8736 return std::make_tuple(A, B, C, T, BitWidth); 8737 } 8738 8739 /// Helper function to compare optional APInts: 8740 /// (a) if X and Y both exist, return min(X, Y), 8741 /// (b) if neither X nor Y exist, return None, 8742 /// (c) if exactly one of X and Y exists, return that value. 8743 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8744 if (X.hasValue() && Y.hasValue()) { 8745 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8746 APInt XW = X->sextOrSelf(W); 8747 APInt YW = Y->sextOrSelf(W); 8748 return XW.slt(YW) ? *X : *Y; 8749 } 8750 if (!X.hasValue() && !Y.hasValue()) 8751 return None; 8752 return X.hasValue() ? *X : *Y; 8753 } 8754 8755 /// Helper function to truncate an optional APInt to a given BitWidth. 8756 /// When solving addrec-related equations, it is preferable to return a value 8757 /// that has the same bit width as the original addrec's coefficients. If the 8758 /// solution fits in the original bit width, truncate it (except for i1). 8759 /// Returning a value of a different bit width may inhibit some optimizations. 8760 /// 8761 /// In general, a solution to a quadratic equation generated from an addrec 8762 /// may require BW+1 bits, where BW is the bit width of the addrec's 8763 /// coefficients. The reason is that the coefficients of the quadratic 8764 /// equation are BW+1 bits wide (to avoid truncation when converting from 8765 /// the addrec to the equation). 8766 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8767 if (!X.hasValue()) 8768 return None; 8769 unsigned W = X->getBitWidth(); 8770 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8771 return X->trunc(BitWidth); 8772 return X; 8773 } 8774 8775 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8776 /// iterations. The values L, M, N are assumed to be signed, and they 8777 /// should all have the same bit widths. 8778 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8779 /// where BW is the bit width of the addrec's coefficients. 8780 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8781 /// returned as such, otherwise the bit width of the returned value may 8782 /// be greater than BW. 8783 /// 8784 /// This function returns None if 8785 /// (a) the addrec coefficients are not constant, or 8786 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8787 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8788 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8789 static Optional<APInt> 8790 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8791 APInt A, B, C, M; 8792 unsigned BitWidth; 8793 auto T = GetQuadraticEquation(AddRec); 8794 if (!T.hasValue()) 8795 return None; 8796 8797 std::tie(A, B, C, M, BitWidth) = *T; 8798 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8799 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8800 if (!X.hasValue()) 8801 return None; 8802 8803 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8804 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8805 if (!V->isZero()) 8806 return None; 8807 8808 return TruncIfPossible(X, BitWidth); 8809 } 8810 8811 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8812 /// iterations. The values M, N are assumed to be signed, and they 8813 /// should all have the same bit widths. 8814 /// Find the least n such that c(n) does not belong to the given range, 8815 /// while c(n-1) does. 8816 /// 8817 /// This function returns None if 8818 /// (a) the addrec coefficients are not constant, or 8819 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8820 /// bounds of the range. 8821 static Optional<APInt> 8822 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8823 const ConstantRange &Range, ScalarEvolution &SE) { 8824 assert(AddRec->getOperand(0)->isZero() && 8825 "Starting value of addrec should be 0"); 8826 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8827 << Range << ", addrec " << *AddRec << '\n'); 8828 // This case is handled in getNumIterationsInRange. Here we can assume that 8829 // we start in the range. 8830 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8831 "Addrec's initial value should be in range"); 8832 8833 APInt A, B, C, M; 8834 unsigned BitWidth; 8835 auto T = GetQuadraticEquation(AddRec); 8836 if (!T.hasValue()) 8837 return None; 8838 8839 // Be careful about the return value: there can be two reasons for not 8840 // returning an actual number. First, if no solutions to the equations 8841 // were found, and second, if the solutions don't leave the given range. 8842 // The first case means that the actual solution is "unknown", the second 8843 // means that it's known, but not valid. If the solution is unknown, we 8844 // cannot make any conclusions. 8845 // Return a pair: the optional solution and a flag indicating if the 8846 // solution was found. 8847 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8848 // Solve for signed overflow and unsigned overflow, pick the lower 8849 // solution. 8850 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8851 << Bound << " (before multiplying by " << M << ")\n"); 8852 Bound *= M; // The quadratic equation multiplier. 8853 8854 Optional<APInt> SO = None; 8855 if (BitWidth > 1) { 8856 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8857 "signed overflow\n"); 8858 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8859 } 8860 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8861 "unsigned overflow\n"); 8862 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8863 BitWidth+1); 8864 8865 auto LeavesRange = [&] (const APInt &X) { 8866 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8867 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8868 if (Range.contains(V0->getValue())) 8869 return false; 8870 // X should be at least 1, so X-1 is non-negative. 8871 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8872 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8873 if (Range.contains(V1->getValue())) 8874 return true; 8875 return false; 8876 }; 8877 8878 // If SolveQuadraticEquationWrap returns None, it means that there can 8879 // be a solution, but the function failed to find it. We cannot treat it 8880 // as "no solution". 8881 if (!SO.hasValue() || !UO.hasValue()) 8882 return { None, false }; 8883 8884 // Check the smaller value first to see if it leaves the range. 8885 // At this point, both SO and UO must have values. 8886 Optional<APInt> Min = MinOptional(SO, UO); 8887 if (LeavesRange(*Min)) 8888 return { Min, true }; 8889 Optional<APInt> Max = Min == SO ? UO : SO; 8890 if (LeavesRange(*Max)) 8891 return { Max, true }; 8892 8893 // Solutions were found, but were eliminated, hence the "true". 8894 return { None, true }; 8895 }; 8896 8897 std::tie(A, B, C, M, BitWidth) = *T; 8898 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8899 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8900 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8901 auto SL = SolveForBoundary(Lower); 8902 auto SU = SolveForBoundary(Upper); 8903 // If any of the solutions was unknown, no meaninigful conclusions can 8904 // be made. 8905 if (!SL.second || !SU.second) 8906 return None; 8907 8908 // Claim: The correct solution is not some value between Min and Max. 8909 // 8910 // Justification: Assuming that Min and Max are different values, one of 8911 // them is when the first signed overflow happens, the other is when the 8912 // first unsigned overflow happens. Crossing the range boundary is only 8913 // possible via an overflow (treating 0 as a special case of it, modeling 8914 // an overflow as crossing k*2^W for some k). 8915 // 8916 // The interesting case here is when Min was eliminated as an invalid 8917 // solution, but Max was not. The argument is that if there was another 8918 // overflow between Min and Max, it would also have been eliminated if 8919 // it was considered. 8920 // 8921 // For a given boundary, it is possible to have two overflows of the same 8922 // type (signed/unsigned) without having the other type in between: this 8923 // can happen when the vertex of the parabola is between the iterations 8924 // corresponding to the overflows. This is only possible when the two 8925 // overflows cross k*2^W for the same k. In such case, if the second one 8926 // left the range (and was the first one to do so), the first overflow 8927 // would have to enter the range, which would mean that either we had left 8928 // the range before or that we started outside of it. Both of these cases 8929 // are contradictions. 8930 // 8931 // Claim: In the case where SolveForBoundary returns None, the correct 8932 // solution is not some value between the Max for this boundary and the 8933 // Min of the other boundary. 8934 // 8935 // Justification: Assume that we had such Max_A and Min_B corresponding 8936 // to range boundaries A and B and such that Max_A < Min_B. If there was 8937 // a solution between Max_A and Min_B, it would have to be caused by an 8938 // overflow corresponding to either A or B. It cannot correspond to B, 8939 // since Min_B is the first occurrence of such an overflow. If it 8940 // corresponded to A, it would have to be either a signed or an unsigned 8941 // overflow that is larger than both eliminated overflows for A. But 8942 // between the eliminated overflows and this overflow, the values would 8943 // cover the entire value space, thus crossing the other boundary, which 8944 // is a contradiction. 8945 8946 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8947 } 8948 8949 ScalarEvolution::ExitLimit 8950 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8951 bool AllowPredicates) { 8952 8953 // This is only used for loops with a "x != y" exit test. The exit condition 8954 // is now expressed as a single expression, V = x-y. So the exit test is 8955 // effectively V != 0. We know and take advantage of the fact that this 8956 // expression only being used in a comparison by zero context. 8957 8958 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8959 // If the value is a constant 8960 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8961 // If the value is already zero, the branch will execute zero times. 8962 if (C->getValue()->isZero()) return C; 8963 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8964 } 8965 8966 const SCEVAddRecExpr *AddRec = 8967 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8968 8969 if (!AddRec && AllowPredicates) 8970 // Try to make this an AddRec using runtime tests, in the first X 8971 // iterations of this loop, where X is the SCEV expression found by the 8972 // algorithm below. 8973 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8974 8975 if (!AddRec || AddRec->getLoop() != L) 8976 return getCouldNotCompute(); 8977 8978 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8979 // the quadratic equation to solve it. 8980 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8981 // We can only use this value if the chrec ends up with an exact zero 8982 // value at this index. When solving for "X*X != 5", for example, we 8983 // should not accept a root of 2. 8984 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8985 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8986 return ExitLimit(R, R, false, Predicates); 8987 } 8988 return getCouldNotCompute(); 8989 } 8990 8991 // Otherwise we can only handle this if it is affine. 8992 if (!AddRec->isAffine()) 8993 return getCouldNotCompute(); 8994 8995 // If this is an affine expression, the execution count of this branch is 8996 // the minimum unsigned root of the following equation: 8997 // 8998 // Start + Step*N = 0 (mod 2^BW) 8999 // 9000 // equivalent to: 9001 // 9002 // Step*N = -Start (mod 2^BW) 9003 // 9004 // where BW is the common bit width of Start and Step. 9005 9006 // Get the initial value for the loop. 9007 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9008 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9009 9010 // For now we handle only constant steps. 9011 // 9012 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9013 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9014 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9015 // We have not yet seen any such cases. 9016 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9017 if (!StepC || StepC->getValue()->isZero()) 9018 return getCouldNotCompute(); 9019 9020 // For positive steps (counting up until unsigned overflow): 9021 // N = -Start/Step (as unsigned) 9022 // For negative steps (counting down to zero): 9023 // N = Start/-Step 9024 // First compute the unsigned distance from zero in the direction of Step. 9025 bool CountDown = StepC->getAPInt().isNegative(); 9026 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9027 9028 // Handle unitary steps, which cannot wraparound. 9029 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9030 // N = Distance (as unsigned) 9031 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9032 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9033 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9034 if (MaxBECountBase.ult(MaxBECount)) 9035 MaxBECount = MaxBECountBase; 9036 9037 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9038 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9039 // case, and see if we can improve the bound. 9040 // 9041 // Explicitly handling this here is necessary because getUnsignedRange 9042 // isn't context-sensitive; it doesn't know that we only care about the 9043 // range inside the loop. 9044 const SCEV *Zero = getZero(Distance->getType()); 9045 const SCEV *One = getOne(Distance->getType()); 9046 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9047 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9048 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9049 // as "unsigned_max(Distance + 1) - 1". 9050 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9051 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9052 } 9053 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9054 } 9055 9056 // If the condition controls loop exit (the loop exits only if the expression 9057 // is true) and the addition is no-wrap we can use unsigned divide to 9058 // compute the backedge count. In this case, the step may not divide the 9059 // distance, but we don't care because if the condition is "missed" the loop 9060 // will have undefined behavior due to wrapping. 9061 if (ControlsExit && AddRec->hasNoSelfWrap() && 9062 loopHasNoAbnormalExits(AddRec->getLoop())) { 9063 const SCEV *Exact = 9064 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9065 const SCEV *Max = 9066 Exact == getCouldNotCompute() 9067 ? Exact 9068 : getConstant(getUnsignedRangeMax(Exact)); 9069 return ExitLimit(Exact, Max, false, Predicates); 9070 } 9071 9072 // Solve the general equation. 9073 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9074 getNegativeSCEV(Start), *this); 9075 const SCEV *M = E == getCouldNotCompute() 9076 ? E 9077 : getConstant(getUnsignedRangeMax(E)); 9078 return ExitLimit(E, M, false, Predicates); 9079 } 9080 9081 ScalarEvolution::ExitLimit 9082 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9083 // Loops that look like: while (X == 0) are very strange indeed. We don't 9084 // handle them yet except for the trivial case. This could be expanded in the 9085 // future as needed. 9086 9087 // If the value is a constant, check to see if it is known to be non-zero 9088 // already. If so, the backedge will execute zero times. 9089 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9090 if (!C->getValue()->isZero()) 9091 return getZero(C->getType()); 9092 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9093 } 9094 9095 // We could implement others, but I really doubt anyone writes loops like 9096 // this, and if they did, they would already be constant folded. 9097 return getCouldNotCompute(); 9098 } 9099 9100 std::pair<const BasicBlock *, const BasicBlock *> 9101 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9102 const { 9103 // If the block has a unique predecessor, then there is no path from the 9104 // predecessor to the block that does not go through the direct edge 9105 // from the predecessor to the block. 9106 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9107 return {Pred, BB}; 9108 9109 // A loop's header is defined to be a block that dominates the loop. 9110 // If the header has a unique predecessor outside the loop, it must be 9111 // a block that has exactly one successor that can reach the loop. 9112 if (const Loop *L = LI.getLoopFor(BB)) 9113 return {L->getLoopPredecessor(), L->getHeader()}; 9114 9115 return {nullptr, nullptr}; 9116 } 9117 9118 /// SCEV structural equivalence is usually sufficient for testing whether two 9119 /// expressions are equal, however for the purposes of looking for a condition 9120 /// guarding a loop, it can be useful to be a little more general, since a 9121 /// front-end may have replicated the controlling expression. 9122 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9123 // Quick check to see if they are the same SCEV. 9124 if (A == B) return true; 9125 9126 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9127 // Not all instructions that are "identical" compute the same value. For 9128 // instance, two distinct alloca instructions allocating the same type are 9129 // identical and do not read memory; but compute distinct values. 9130 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9131 }; 9132 9133 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9134 // two different instructions with the same value. Check for this case. 9135 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9136 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9137 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9138 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9139 if (ComputesEqualValues(AI, BI)) 9140 return true; 9141 9142 // Otherwise assume they may have a different value. 9143 return false; 9144 } 9145 9146 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9147 const SCEV *&LHS, const SCEV *&RHS, 9148 unsigned Depth) { 9149 bool Changed = false; 9150 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9151 // '0 != 0'. 9152 auto TrivialCase = [&](bool TriviallyTrue) { 9153 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9154 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9155 return true; 9156 }; 9157 // If we hit the max recursion limit bail out. 9158 if (Depth >= 3) 9159 return false; 9160 9161 // Canonicalize a constant to the right side. 9162 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9163 // Check for both operands constant. 9164 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9165 if (ConstantExpr::getICmp(Pred, 9166 LHSC->getValue(), 9167 RHSC->getValue())->isNullValue()) 9168 return TrivialCase(false); 9169 else 9170 return TrivialCase(true); 9171 } 9172 // Otherwise swap the operands to put the constant on the right. 9173 std::swap(LHS, RHS); 9174 Pred = ICmpInst::getSwappedPredicate(Pred); 9175 Changed = true; 9176 } 9177 9178 // If we're comparing an addrec with a value which is loop-invariant in the 9179 // addrec's loop, put the addrec on the left. Also make a dominance check, 9180 // as both operands could be addrecs loop-invariant in each other's loop. 9181 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9182 const Loop *L = AR->getLoop(); 9183 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9184 std::swap(LHS, RHS); 9185 Pred = ICmpInst::getSwappedPredicate(Pred); 9186 Changed = true; 9187 } 9188 } 9189 9190 // If there's a constant operand, canonicalize comparisons with boundary 9191 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9192 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9193 const APInt &RA = RC->getAPInt(); 9194 9195 bool SimplifiedByConstantRange = false; 9196 9197 if (!ICmpInst::isEquality(Pred)) { 9198 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9199 if (ExactCR.isFullSet()) 9200 return TrivialCase(true); 9201 else if (ExactCR.isEmptySet()) 9202 return TrivialCase(false); 9203 9204 APInt NewRHS; 9205 CmpInst::Predicate NewPred; 9206 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9207 ICmpInst::isEquality(NewPred)) { 9208 // We were able to convert an inequality to an equality. 9209 Pred = NewPred; 9210 RHS = getConstant(NewRHS); 9211 Changed = SimplifiedByConstantRange = true; 9212 } 9213 } 9214 9215 if (!SimplifiedByConstantRange) { 9216 switch (Pred) { 9217 default: 9218 break; 9219 case ICmpInst::ICMP_EQ: 9220 case ICmpInst::ICMP_NE: 9221 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9222 if (!RA) 9223 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9224 if (const SCEVMulExpr *ME = 9225 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9226 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9227 ME->getOperand(0)->isAllOnesValue()) { 9228 RHS = AE->getOperand(1); 9229 LHS = ME->getOperand(1); 9230 Changed = true; 9231 } 9232 break; 9233 9234 9235 // The "Should have been caught earlier!" messages refer to the fact 9236 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9237 // should have fired on the corresponding cases, and canonicalized the 9238 // check to trivial case. 9239 9240 case ICmpInst::ICMP_UGE: 9241 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9242 Pred = ICmpInst::ICMP_UGT; 9243 RHS = getConstant(RA - 1); 9244 Changed = true; 9245 break; 9246 case ICmpInst::ICMP_ULE: 9247 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9248 Pred = ICmpInst::ICMP_ULT; 9249 RHS = getConstant(RA + 1); 9250 Changed = true; 9251 break; 9252 case ICmpInst::ICMP_SGE: 9253 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9254 Pred = ICmpInst::ICMP_SGT; 9255 RHS = getConstant(RA - 1); 9256 Changed = true; 9257 break; 9258 case ICmpInst::ICMP_SLE: 9259 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9260 Pred = ICmpInst::ICMP_SLT; 9261 RHS = getConstant(RA + 1); 9262 Changed = true; 9263 break; 9264 } 9265 } 9266 } 9267 9268 // Check for obvious equality. 9269 if (HasSameValue(LHS, RHS)) { 9270 if (ICmpInst::isTrueWhenEqual(Pred)) 9271 return TrivialCase(true); 9272 if (ICmpInst::isFalseWhenEqual(Pred)) 9273 return TrivialCase(false); 9274 } 9275 9276 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9277 // adding or subtracting 1 from one of the operands. 9278 switch (Pred) { 9279 case ICmpInst::ICMP_SLE: 9280 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9281 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9282 SCEV::FlagNSW); 9283 Pred = ICmpInst::ICMP_SLT; 9284 Changed = true; 9285 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9286 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9287 SCEV::FlagNSW); 9288 Pred = ICmpInst::ICMP_SLT; 9289 Changed = true; 9290 } 9291 break; 9292 case ICmpInst::ICMP_SGE: 9293 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9294 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9295 SCEV::FlagNSW); 9296 Pred = ICmpInst::ICMP_SGT; 9297 Changed = true; 9298 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9299 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9300 SCEV::FlagNSW); 9301 Pred = ICmpInst::ICMP_SGT; 9302 Changed = true; 9303 } 9304 break; 9305 case ICmpInst::ICMP_ULE: 9306 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9307 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9308 SCEV::FlagNUW); 9309 Pred = ICmpInst::ICMP_ULT; 9310 Changed = true; 9311 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9312 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9313 Pred = ICmpInst::ICMP_ULT; 9314 Changed = true; 9315 } 9316 break; 9317 case ICmpInst::ICMP_UGE: 9318 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9319 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9320 Pred = ICmpInst::ICMP_UGT; 9321 Changed = true; 9322 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9323 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9324 SCEV::FlagNUW); 9325 Pred = ICmpInst::ICMP_UGT; 9326 Changed = true; 9327 } 9328 break; 9329 default: 9330 break; 9331 } 9332 9333 // TODO: More simplifications are possible here. 9334 9335 // Recursively simplify until we either hit a recursion limit or nothing 9336 // changes. 9337 if (Changed) 9338 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9339 9340 return Changed; 9341 } 9342 9343 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9344 return getSignedRangeMax(S).isNegative(); 9345 } 9346 9347 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9348 return getSignedRangeMin(S).isStrictlyPositive(); 9349 } 9350 9351 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9352 return !getSignedRangeMin(S).isNegative(); 9353 } 9354 9355 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9356 return !getSignedRangeMax(S).isStrictlyPositive(); 9357 } 9358 9359 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9360 return isKnownNegative(S) || isKnownPositive(S); 9361 } 9362 9363 std::pair<const SCEV *, const SCEV *> 9364 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9365 // Compute SCEV on entry of loop L. 9366 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9367 if (Start == getCouldNotCompute()) 9368 return { Start, Start }; 9369 // Compute post increment SCEV for loop L. 9370 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9371 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9372 return { Start, PostInc }; 9373 } 9374 9375 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9376 const SCEV *LHS, const SCEV *RHS) { 9377 // First collect all loops. 9378 SmallPtrSet<const Loop *, 8> LoopsUsed; 9379 getUsedLoops(LHS, LoopsUsed); 9380 getUsedLoops(RHS, LoopsUsed); 9381 9382 if (LoopsUsed.empty()) 9383 return false; 9384 9385 // Domination relationship must be a linear order on collected loops. 9386 #ifndef NDEBUG 9387 for (auto *L1 : LoopsUsed) 9388 for (auto *L2 : LoopsUsed) 9389 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9390 DT.dominates(L2->getHeader(), L1->getHeader())) && 9391 "Domination relationship is not a linear order"); 9392 #endif 9393 9394 const Loop *MDL = 9395 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9396 [&](const Loop *L1, const Loop *L2) { 9397 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9398 }); 9399 9400 // Get init and post increment value for LHS. 9401 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9402 // if LHS contains unknown non-invariant SCEV then bail out. 9403 if (SplitLHS.first == getCouldNotCompute()) 9404 return false; 9405 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9406 // Get init and post increment value for RHS. 9407 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9408 // if RHS contains unknown non-invariant SCEV then bail out. 9409 if (SplitRHS.first == getCouldNotCompute()) 9410 return false; 9411 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9412 // It is possible that init SCEV contains an invariant load but it does 9413 // not dominate MDL and is not available at MDL loop entry, so we should 9414 // check it here. 9415 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9416 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9417 return false; 9418 9419 // It seems backedge guard check is faster than entry one so in some cases 9420 // it can speed up whole estimation by short circuit 9421 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9422 SplitRHS.second) && 9423 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9424 } 9425 9426 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9427 const SCEV *LHS, const SCEV *RHS) { 9428 // Canonicalize the inputs first. 9429 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9430 9431 if (isKnownViaInduction(Pred, LHS, RHS)) 9432 return true; 9433 9434 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9435 return true; 9436 9437 // Otherwise see what can be done with some simple reasoning. 9438 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9439 } 9440 9441 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9442 const SCEV *LHS, const SCEV *RHS, 9443 const Instruction *Context) { 9444 // TODO: Analyze guards and assumes from Context's block. 9445 return isKnownPredicate(Pred, LHS, RHS) || 9446 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9447 } 9448 9449 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9450 const SCEVAddRecExpr *LHS, 9451 const SCEV *RHS) { 9452 const Loop *L = LHS->getLoop(); 9453 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9454 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9455 } 9456 9457 Optional<ScalarEvolution::MonotonicPredicateType> 9458 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9459 ICmpInst::Predicate Pred, 9460 Optional<const SCEV *> NumIter, 9461 const Instruction *Context) { 9462 assert((!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) && 9463 "provided number of iterations must be computable!"); 9464 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred, NumIter, Context); 9465 9466 #ifndef NDEBUG 9467 // Verify an invariant: inverting the predicate should turn a monotonically 9468 // increasing change to a monotonically decreasing one, and vice versa. 9469 if (Result) { 9470 auto ResultSwapped = getMonotonicPredicateTypeImpl( 9471 LHS, ICmpInst::getSwappedPredicate(Pred), NumIter, Context); 9472 9473 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9474 assert(ResultSwapped.getValue() != Result.getValue() && 9475 "monotonicity should flip as we flip the predicate"); 9476 } 9477 #endif 9478 9479 return Result; 9480 } 9481 9482 Optional<ScalarEvolution::MonotonicPredicateType> 9483 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9484 ICmpInst::Predicate Pred, 9485 Optional<const SCEV *> NumIter, 9486 const Instruction *Context) { 9487 // A zero step value for LHS means the induction variable is essentially a 9488 // loop invariant value. We don't really depend on the predicate actually 9489 // flipping from false to true (for increasing predicates, and the other way 9490 // around for decreasing predicates), all we care about is that *if* the 9491 // predicate changes then it only changes from false to true. 9492 // 9493 // A zero step value in itself is not very useful, but there may be places 9494 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9495 // as general as possible. 9496 9497 // Only handle LE/LT/GE/GT predicates. 9498 if (!ICmpInst::isRelational(Pred)) 9499 return None; 9500 9501 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9502 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9503 "Should be greater or less!"); 9504 9505 bool IsUnsigned = ICmpInst::isUnsigned(Pred); 9506 assert((IsUnsigned || ICmpInst::isSigned(Pred)) && 9507 "Should be either signed or unsigned!"); 9508 // Check if we can prove no-wrap in the relevant range. 9509 9510 const SCEV *Step = LHS->getStepRecurrence(*this); 9511 bool IsStepNonNegative = isKnownNonNegative(Step); 9512 bool IsStepNonPositive = isKnownNonPositive(Step); 9513 // We need to know which direction the iteration is going. 9514 if (!IsStepNonNegative && !IsStepNonPositive) 9515 return None; 9516 9517 auto ProvedNoWrap = [&]() { 9518 // If the AddRec already has the flag, we are done. 9519 if (IsUnsigned ? LHS->hasNoUnsignedWrap() : LHS->hasNoSignedWrap()) 9520 return true; 9521 9522 if (!NumIter) 9523 return false; 9524 // We could not prove no-wrap on all iteration space. Can we prove it for 9525 // first iterations? In order to achieve it, check that: 9526 // 1. The addrec does not self-wrap; 9527 // 2. start <= end for non-negative step and start >= end for non-positive 9528 // step. 9529 bool HasNoSelfWrap = LHS->hasNoSelfWrap(); 9530 if (!HasNoSelfWrap) 9531 // If num iter has same type as the AddRec, and step is +/- 1, even max 9532 // possible number of iterations is not enough to self-wrap. 9533 if (NumIter.getValue()->getType() == LHS->getType()) 9534 if (Step == getOne(LHS->getType()) || 9535 Step == getMinusOne(LHS->getType())) 9536 HasNoSelfWrap = true; 9537 if (!HasNoSelfWrap) 9538 return false; 9539 const SCEV *Start = LHS->getStart(); 9540 const SCEV *End = LHS->evaluateAtIteration(*NumIter, *this); 9541 ICmpInst::Predicate NoOverflowPred = 9542 IsStepNonNegative ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SGE; 9543 if (IsUnsigned) 9544 NoOverflowPred = ICmpInst::getUnsignedPredicate(NoOverflowPred); 9545 return isKnownPredicateAt(NoOverflowPred, Start, End, Context); 9546 }; 9547 9548 // If nothing worked, bail. 9549 if (!ProvedNoWrap()) 9550 return None; 9551 9552 if (IsUnsigned) 9553 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9554 else { 9555 if (IsStepNonNegative) 9556 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9557 9558 if (IsStepNonPositive) 9559 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9560 9561 return None; 9562 } 9563 } 9564 9565 Optional<ScalarEvolution::LoopInvariantPredicate> 9566 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9567 const SCEV *LHS, const SCEV *RHS, 9568 const Loop *L) { 9569 9570 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9571 if (!isLoopInvariant(RHS, L)) { 9572 if (!isLoopInvariant(LHS, L)) 9573 return None; 9574 9575 std::swap(LHS, RHS); 9576 Pred = ICmpInst::getSwappedPredicate(Pred); 9577 } 9578 9579 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9580 if (!ArLHS || ArLHS->getLoop() != L) 9581 return None; 9582 9583 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9584 if (!MonotonicType) 9585 return None; 9586 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9587 // true as the loop iterates, and the backedge is control dependent on 9588 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9589 // 9590 // * if the predicate was false in the first iteration then the predicate 9591 // is never evaluated again, since the loop exits without taking the 9592 // backedge. 9593 // * if the predicate was true in the first iteration then it will 9594 // continue to be true for all future iterations since it is 9595 // monotonically increasing. 9596 // 9597 // For both the above possibilities, we can replace the loop varying 9598 // predicate with its value on the first iteration of the loop (which is 9599 // loop invariant). 9600 // 9601 // A similar reasoning applies for a monotonically decreasing predicate, by 9602 // replacing true with false and false with true in the above two bullets. 9603 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9604 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9605 9606 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9607 return None; 9608 9609 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9610 } 9611 9612 Optional<ScalarEvolution::LoopInvariantPredicate> 9613 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9614 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9615 const Instruction *Context, const SCEV *MaxIter) { 9616 // Try to prove the following set of facts: 9617 // - The predicate is monotonic in the iteration space. 9618 // - If the check does not fail on the 1st iteration: 9619 // - It will not fail on the MaxIter'th iteration. 9620 // If the check does fail on the 1st iteration, we leave the loop and no 9621 // other checks matter. 9622 9623 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9624 if (!isLoopInvariant(RHS, L)) { 9625 if (!isLoopInvariant(LHS, L)) 9626 return None; 9627 9628 std::swap(LHS, RHS); 9629 Pred = ICmpInst::getSwappedPredicate(Pred); 9630 } 9631 9632 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9633 if (!AR || AR->getLoop() != L) 9634 return None; 9635 9636 if (!getMonotonicPredicateType(AR, Pred, MaxIter, Context)) 9637 return None; 9638 9639 // Value of IV on suggested last iteration. 9640 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9641 // Does it still meet the requirement? 9642 if (!isKnownPredicateAt(Pred, Last, RHS, Context)) 9643 return None; 9644 9645 // Everything is fine. 9646 return ScalarEvolution::LoopInvariantPredicate(Pred, AR->getStart(), RHS); 9647 } 9648 9649 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9650 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9651 if (HasSameValue(LHS, RHS)) 9652 return ICmpInst::isTrueWhenEqual(Pred); 9653 9654 // This code is split out from isKnownPredicate because it is called from 9655 // within isLoopEntryGuardedByCond. 9656 9657 auto CheckRanges = 9658 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9659 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9660 .contains(RangeLHS); 9661 }; 9662 9663 // The check at the top of the function catches the case where the values are 9664 // known to be equal. 9665 if (Pred == CmpInst::ICMP_EQ) 9666 return false; 9667 9668 if (Pred == CmpInst::ICMP_NE) 9669 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9670 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9671 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9672 9673 if (CmpInst::isSigned(Pred)) 9674 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9675 9676 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9677 } 9678 9679 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9680 const SCEV *LHS, 9681 const SCEV *RHS) { 9682 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9683 // Return Y via OutY. 9684 auto MatchBinaryAddToConst = 9685 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9686 SCEV::NoWrapFlags ExpectedFlags) { 9687 const SCEV *NonConstOp, *ConstOp; 9688 SCEV::NoWrapFlags FlagsPresent; 9689 9690 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9691 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9692 return false; 9693 9694 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9695 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9696 }; 9697 9698 APInt C; 9699 9700 switch (Pred) { 9701 default: 9702 break; 9703 9704 case ICmpInst::ICMP_SGE: 9705 std::swap(LHS, RHS); 9706 LLVM_FALLTHROUGH; 9707 case ICmpInst::ICMP_SLE: 9708 // X s<= (X + C)<nsw> if C >= 0 9709 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9710 return true; 9711 9712 // (X + C)<nsw> s<= X if C <= 0 9713 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9714 !C.isStrictlyPositive()) 9715 return true; 9716 break; 9717 9718 case ICmpInst::ICMP_SGT: 9719 std::swap(LHS, RHS); 9720 LLVM_FALLTHROUGH; 9721 case ICmpInst::ICMP_SLT: 9722 // X s< (X + C)<nsw> if C > 0 9723 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9724 C.isStrictlyPositive()) 9725 return true; 9726 9727 // (X + C)<nsw> s< X if C < 0 9728 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9729 return true; 9730 break; 9731 9732 case ICmpInst::ICMP_UGE: 9733 std::swap(LHS, RHS); 9734 LLVM_FALLTHROUGH; 9735 case ICmpInst::ICMP_ULE: 9736 // X u<= (X + C)<nuw> for any C 9737 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9738 return true; 9739 break; 9740 9741 case ICmpInst::ICMP_UGT: 9742 std::swap(LHS, RHS); 9743 LLVM_FALLTHROUGH; 9744 case ICmpInst::ICMP_ULT: 9745 // X u< (X + C)<nuw> if C != 0 9746 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9747 return true; 9748 break; 9749 } 9750 9751 return false; 9752 } 9753 9754 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9755 const SCEV *LHS, 9756 const SCEV *RHS) { 9757 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9758 return false; 9759 9760 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9761 // the stack can result in exponential time complexity. 9762 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9763 9764 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9765 // 9766 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9767 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9768 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9769 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9770 // use isKnownPredicate later if needed. 9771 return isKnownNonNegative(RHS) && 9772 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9773 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9774 } 9775 9776 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9777 ICmpInst::Predicate Pred, 9778 const SCEV *LHS, const SCEV *RHS) { 9779 // No need to even try if we know the module has no guards. 9780 if (!HasGuards) 9781 return false; 9782 9783 return any_of(*BB, [&](const Instruction &I) { 9784 using namespace llvm::PatternMatch; 9785 9786 Value *Condition; 9787 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9788 m_Value(Condition))) && 9789 isImpliedCond(Pred, LHS, RHS, Condition, false); 9790 }); 9791 } 9792 9793 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9794 /// protected by a conditional between LHS and RHS. This is used to 9795 /// to eliminate casts. 9796 bool 9797 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9798 ICmpInst::Predicate Pred, 9799 const SCEV *LHS, const SCEV *RHS) { 9800 // Interpret a null as meaning no loop, where there is obviously no guard 9801 // (interprocedural conditions notwithstanding). 9802 if (!L) return true; 9803 9804 if (VerifyIR) 9805 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9806 "This cannot be done on broken IR!"); 9807 9808 9809 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9810 return true; 9811 9812 BasicBlock *Latch = L->getLoopLatch(); 9813 if (!Latch) 9814 return false; 9815 9816 BranchInst *LoopContinuePredicate = 9817 dyn_cast<BranchInst>(Latch->getTerminator()); 9818 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9819 isImpliedCond(Pred, LHS, RHS, 9820 LoopContinuePredicate->getCondition(), 9821 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9822 return true; 9823 9824 // We don't want more than one activation of the following loops on the stack 9825 // -- that can lead to O(n!) time complexity. 9826 if (WalkingBEDominatingConds) 9827 return false; 9828 9829 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9830 9831 // See if we can exploit a trip count to prove the predicate. 9832 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9833 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9834 if (LatchBECount != getCouldNotCompute()) { 9835 // We know that Latch branches back to the loop header exactly 9836 // LatchBECount times. This means the backdege condition at Latch is 9837 // equivalent to "{0,+,1} u< LatchBECount". 9838 Type *Ty = LatchBECount->getType(); 9839 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9840 const SCEV *LoopCounter = 9841 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9842 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9843 LatchBECount)) 9844 return true; 9845 } 9846 9847 // Check conditions due to any @llvm.assume intrinsics. 9848 for (auto &AssumeVH : AC.assumptions()) { 9849 if (!AssumeVH) 9850 continue; 9851 auto *CI = cast<CallInst>(AssumeVH); 9852 if (!DT.dominates(CI, Latch->getTerminator())) 9853 continue; 9854 9855 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9856 return true; 9857 } 9858 9859 // If the loop is not reachable from the entry block, we risk running into an 9860 // infinite loop as we walk up into the dom tree. These loops do not matter 9861 // anyway, so we just return a conservative answer when we see them. 9862 if (!DT.isReachableFromEntry(L->getHeader())) 9863 return false; 9864 9865 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9866 return true; 9867 9868 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9869 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9870 assert(DTN && "should reach the loop header before reaching the root!"); 9871 9872 BasicBlock *BB = DTN->getBlock(); 9873 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9874 return true; 9875 9876 BasicBlock *PBB = BB->getSinglePredecessor(); 9877 if (!PBB) 9878 continue; 9879 9880 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9881 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9882 continue; 9883 9884 Value *Condition = ContinuePredicate->getCondition(); 9885 9886 // If we have an edge `E` within the loop body that dominates the only 9887 // latch, the condition guarding `E` also guards the backedge. This 9888 // reasoning works only for loops with a single latch. 9889 9890 BasicBlockEdge DominatingEdge(PBB, BB); 9891 if (DominatingEdge.isSingleEdge()) { 9892 // We're constructively (and conservatively) enumerating edges within the 9893 // loop body that dominate the latch. The dominator tree better agree 9894 // with us on this: 9895 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9896 9897 if (isImpliedCond(Pred, LHS, RHS, Condition, 9898 BB != ContinuePredicate->getSuccessor(0))) 9899 return true; 9900 } 9901 } 9902 9903 return false; 9904 } 9905 9906 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9907 ICmpInst::Predicate Pred, 9908 const SCEV *LHS, 9909 const SCEV *RHS) { 9910 if (VerifyIR) 9911 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9912 "This cannot be done on broken IR!"); 9913 9914 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9915 return true; 9916 9917 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9918 // the facts (a >= b && a != b) separately. A typical situation is when the 9919 // non-strict comparison is known from ranges and non-equality is known from 9920 // dominating predicates. If we are proving strict comparison, we always try 9921 // to prove non-equality and non-strict comparison separately. 9922 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9923 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9924 bool ProvedNonStrictComparison = false; 9925 bool ProvedNonEquality = false; 9926 9927 if (ProvingStrictComparison) { 9928 ProvedNonStrictComparison = 9929 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9930 ProvedNonEquality = 9931 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9932 if (ProvedNonStrictComparison && ProvedNonEquality) 9933 return true; 9934 } 9935 9936 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9937 auto ProveViaGuard = [&](const BasicBlock *Block) { 9938 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9939 return true; 9940 if (ProvingStrictComparison) { 9941 if (!ProvedNonStrictComparison) 9942 ProvedNonStrictComparison = 9943 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9944 if (!ProvedNonEquality) 9945 ProvedNonEquality = 9946 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9947 if (ProvedNonStrictComparison && ProvedNonEquality) 9948 return true; 9949 } 9950 return false; 9951 }; 9952 9953 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9954 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9955 const Instruction *Context = &BB->front(); 9956 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9957 return true; 9958 if (ProvingStrictComparison) { 9959 if (!ProvedNonStrictComparison) 9960 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9961 Condition, Inverse, Context); 9962 if (!ProvedNonEquality) 9963 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9964 Condition, Inverse, Context); 9965 if (ProvedNonStrictComparison && ProvedNonEquality) 9966 return true; 9967 } 9968 return false; 9969 }; 9970 9971 // Starting at the block's predecessor, climb up the predecessor chain, as long 9972 // as there are predecessors that can be found that have unique successors 9973 // leading to the original block. 9974 const Loop *ContainingLoop = LI.getLoopFor(BB); 9975 const BasicBlock *PredBB; 9976 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9977 PredBB = ContainingLoop->getLoopPredecessor(); 9978 else 9979 PredBB = BB->getSinglePredecessor(); 9980 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9981 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9982 if (ProveViaGuard(Pair.first)) 9983 return true; 9984 9985 const BranchInst *LoopEntryPredicate = 9986 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9987 if (!LoopEntryPredicate || 9988 LoopEntryPredicate->isUnconditional()) 9989 continue; 9990 9991 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9992 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9993 return true; 9994 } 9995 9996 // Check conditions due to any @llvm.assume intrinsics. 9997 for (auto &AssumeVH : AC.assumptions()) { 9998 if (!AssumeVH) 9999 continue; 10000 auto *CI = cast<CallInst>(AssumeVH); 10001 if (!DT.dominates(CI, BB)) 10002 continue; 10003 10004 if (ProveViaCond(CI->getArgOperand(0), false)) 10005 return true; 10006 } 10007 10008 return false; 10009 } 10010 10011 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10012 ICmpInst::Predicate Pred, 10013 const SCEV *LHS, 10014 const SCEV *RHS) { 10015 // Interpret a null as meaning no loop, where there is obviously no guard 10016 // (interprocedural conditions notwithstanding). 10017 if (!L) 10018 return false; 10019 10020 // Both LHS and RHS must be available at loop entry. 10021 assert(isAvailableAtLoopEntry(LHS, L) && 10022 "LHS is not available at Loop Entry"); 10023 assert(isAvailableAtLoopEntry(RHS, L) && 10024 "RHS is not available at Loop Entry"); 10025 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10026 } 10027 10028 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10029 const SCEV *RHS, 10030 const Value *FoundCondValue, bool Inverse, 10031 const Instruction *Context) { 10032 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10033 return false; 10034 10035 auto ClearOnExit = 10036 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10037 10038 // Recursively handle And and Or conditions. 10039 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 10040 if (BO->getOpcode() == Instruction::And) { 10041 if (!Inverse) 10042 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10043 Context) || 10044 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10045 Context); 10046 } else if (BO->getOpcode() == Instruction::Or) { 10047 if (Inverse) 10048 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10049 Context) || 10050 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10051 Context); 10052 } 10053 } 10054 10055 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10056 if (!ICI) return false; 10057 10058 // Now that we found a conditional branch that dominates the loop or controls 10059 // the loop latch. Check to see if it is the comparison we are looking for. 10060 ICmpInst::Predicate FoundPred; 10061 if (Inverse) 10062 FoundPred = ICI->getInversePredicate(); 10063 else 10064 FoundPred = ICI->getPredicate(); 10065 10066 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10067 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10068 10069 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10070 } 10071 10072 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10073 const SCEV *RHS, 10074 ICmpInst::Predicate FoundPred, 10075 const SCEV *FoundLHS, const SCEV *FoundRHS, 10076 const Instruction *Context) { 10077 // Balance the types. 10078 if (getTypeSizeInBits(LHS->getType()) < 10079 getTypeSizeInBits(FoundLHS->getType())) { 10080 // For unsigned and equality predicates, try to prove that both found 10081 // operands fit into narrow unsigned range. If so, try to prove facts in 10082 // narrow types. 10083 if (!CmpInst::isSigned(FoundPred)) { 10084 auto *NarrowType = LHS->getType(); 10085 auto *WideType = FoundLHS->getType(); 10086 auto BitWidth = getTypeSizeInBits(NarrowType); 10087 const SCEV *MaxValue = getZeroExtendExpr( 10088 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10089 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10090 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10091 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10092 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10093 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10094 TruncFoundRHS, Context)) 10095 return true; 10096 } 10097 } 10098 10099 if (CmpInst::isSigned(Pred)) { 10100 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10101 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10102 } else { 10103 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10104 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10105 } 10106 } else if (getTypeSizeInBits(LHS->getType()) > 10107 getTypeSizeInBits(FoundLHS->getType())) { 10108 if (CmpInst::isSigned(FoundPred)) { 10109 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10110 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10111 } else { 10112 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10113 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10114 } 10115 } 10116 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10117 FoundRHS, Context); 10118 } 10119 10120 bool ScalarEvolution::isImpliedCondBalancedTypes( 10121 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10122 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10123 const Instruction *Context) { 10124 assert(getTypeSizeInBits(LHS->getType()) == 10125 getTypeSizeInBits(FoundLHS->getType()) && 10126 "Types should be balanced!"); 10127 // Canonicalize the query to match the way instcombine will have 10128 // canonicalized the comparison. 10129 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10130 if (LHS == RHS) 10131 return CmpInst::isTrueWhenEqual(Pred); 10132 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10133 if (FoundLHS == FoundRHS) 10134 return CmpInst::isFalseWhenEqual(FoundPred); 10135 10136 // Check to see if we can make the LHS or RHS match. 10137 if (LHS == FoundRHS || RHS == FoundLHS) { 10138 if (isa<SCEVConstant>(RHS)) { 10139 std::swap(FoundLHS, FoundRHS); 10140 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10141 } else { 10142 std::swap(LHS, RHS); 10143 Pred = ICmpInst::getSwappedPredicate(Pred); 10144 } 10145 } 10146 10147 // Check whether the found predicate is the same as the desired predicate. 10148 if (FoundPred == Pred) 10149 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10150 10151 // Check whether swapping the found predicate makes it the same as the 10152 // desired predicate. 10153 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10154 if (isa<SCEVConstant>(RHS)) 10155 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10156 else 10157 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 10158 LHS, FoundLHS, FoundRHS, Context); 10159 } 10160 10161 // Unsigned comparison is the same as signed comparison when both the operands 10162 // are non-negative. 10163 if (CmpInst::isUnsigned(FoundPred) && 10164 CmpInst::getSignedPredicate(FoundPred) == Pred && 10165 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10166 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10167 10168 // Check if we can make progress by sharpening ranges. 10169 if (FoundPred == ICmpInst::ICMP_NE && 10170 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10171 10172 const SCEVConstant *C = nullptr; 10173 const SCEV *V = nullptr; 10174 10175 if (isa<SCEVConstant>(FoundLHS)) { 10176 C = cast<SCEVConstant>(FoundLHS); 10177 V = FoundRHS; 10178 } else { 10179 C = cast<SCEVConstant>(FoundRHS); 10180 V = FoundLHS; 10181 } 10182 10183 // The guarding predicate tells us that C != V. If the known range 10184 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10185 // range we consider has to correspond to same signedness as the 10186 // predicate we're interested in folding. 10187 10188 APInt Min = ICmpInst::isSigned(Pred) ? 10189 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10190 10191 if (Min == C->getAPInt()) { 10192 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10193 // This is true even if (Min + 1) wraps around -- in case of 10194 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10195 10196 APInt SharperMin = Min + 1; 10197 10198 switch (Pred) { 10199 case ICmpInst::ICMP_SGE: 10200 case ICmpInst::ICMP_UGE: 10201 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10202 // RHS, we're done. 10203 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10204 Context)) 10205 return true; 10206 LLVM_FALLTHROUGH; 10207 10208 case ICmpInst::ICMP_SGT: 10209 case ICmpInst::ICMP_UGT: 10210 // We know from the range information that (V `Pred` Min || 10211 // V == Min). We know from the guarding condition that !(V 10212 // == Min). This gives us 10213 // 10214 // V `Pred` Min || V == Min && !(V == Min) 10215 // => V `Pred` Min 10216 // 10217 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10218 10219 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10220 Context)) 10221 return true; 10222 break; 10223 10224 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10225 case ICmpInst::ICMP_SLE: 10226 case ICmpInst::ICMP_ULE: 10227 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10228 LHS, V, getConstant(SharperMin), Context)) 10229 return true; 10230 LLVM_FALLTHROUGH; 10231 10232 case ICmpInst::ICMP_SLT: 10233 case ICmpInst::ICMP_ULT: 10234 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10235 LHS, V, getConstant(Min), Context)) 10236 return true; 10237 break; 10238 10239 default: 10240 // No change 10241 break; 10242 } 10243 } 10244 } 10245 10246 // Check whether the actual condition is beyond sufficient. 10247 if (FoundPred == ICmpInst::ICMP_EQ) 10248 if (ICmpInst::isTrueWhenEqual(Pred)) 10249 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10250 return true; 10251 if (Pred == ICmpInst::ICMP_NE) 10252 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10253 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10254 Context)) 10255 return true; 10256 10257 // Otherwise assume the worst. 10258 return false; 10259 } 10260 10261 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10262 const SCEV *&L, const SCEV *&R, 10263 SCEV::NoWrapFlags &Flags) { 10264 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10265 if (!AE || AE->getNumOperands() != 2) 10266 return false; 10267 10268 L = AE->getOperand(0); 10269 R = AE->getOperand(1); 10270 Flags = AE->getNoWrapFlags(); 10271 return true; 10272 } 10273 10274 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10275 const SCEV *Less) { 10276 // We avoid subtracting expressions here because this function is usually 10277 // fairly deep in the call stack (i.e. is called many times). 10278 10279 // X - X = 0. 10280 if (More == Less) 10281 return APInt(getTypeSizeInBits(More->getType()), 0); 10282 10283 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10284 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10285 const auto *MAR = cast<SCEVAddRecExpr>(More); 10286 10287 if (LAR->getLoop() != MAR->getLoop()) 10288 return None; 10289 10290 // We look at affine expressions only; not for correctness but to keep 10291 // getStepRecurrence cheap. 10292 if (!LAR->isAffine() || !MAR->isAffine()) 10293 return None; 10294 10295 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10296 return None; 10297 10298 Less = LAR->getStart(); 10299 More = MAR->getStart(); 10300 10301 // fall through 10302 } 10303 10304 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10305 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10306 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10307 return M - L; 10308 } 10309 10310 SCEV::NoWrapFlags Flags; 10311 const SCEV *LLess = nullptr, *RLess = nullptr; 10312 const SCEV *LMore = nullptr, *RMore = nullptr; 10313 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10314 // Compare (X + C1) vs X. 10315 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10316 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10317 if (RLess == More) 10318 return -(C1->getAPInt()); 10319 10320 // Compare X vs (X + C2). 10321 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10322 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10323 if (RMore == Less) 10324 return C2->getAPInt(); 10325 10326 // Compare (X + C1) vs (X + C2). 10327 if (C1 && C2 && RLess == RMore) 10328 return C2->getAPInt() - C1->getAPInt(); 10329 10330 return None; 10331 } 10332 10333 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10334 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10335 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10336 // Try to recognize the following pattern: 10337 // 10338 // FoundRHS = ... 10339 // ... 10340 // loop: 10341 // FoundLHS = {Start,+,W} 10342 // context_bb: // Basic block from the same loop 10343 // known(Pred, FoundLHS, FoundRHS) 10344 // 10345 // If some predicate is known in the context of a loop, it is also known on 10346 // each iteration of this loop, including the first iteration. Therefore, in 10347 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10348 // prove the original pred using this fact. 10349 if (!Context) 10350 return false; 10351 const BasicBlock *ContextBB = Context->getParent(); 10352 // Make sure AR varies in the context block. 10353 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10354 const Loop *L = AR->getLoop(); 10355 // Make sure that context belongs to the loop and executes on 1st iteration 10356 // (if it ever executes at all). 10357 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10358 return false; 10359 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10360 return false; 10361 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10362 } 10363 10364 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10365 const Loop *L = AR->getLoop(); 10366 // Make sure that context belongs to the loop and executes on 1st iteration 10367 // (if it ever executes at all). 10368 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10369 return false; 10370 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10371 return false; 10372 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10373 } 10374 10375 return false; 10376 } 10377 10378 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10379 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10380 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10381 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10382 return false; 10383 10384 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10385 if (!AddRecLHS) 10386 return false; 10387 10388 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10389 if (!AddRecFoundLHS) 10390 return false; 10391 10392 // We'd like to let SCEV reason about control dependencies, so we constrain 10393 // both the inequalities to be about add recurrences on the same loop. This 10394 // way we can use isLoopEntryGuardedByCond later. 10395 10396 const Loop *L = AddRecFoundLHS->getLoop(); 10397 if (L != AddRecLHS->getLoop()) 10398 return false; 10399 10400 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10401 // 10402 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10403 // ... (2) 10404 // 10405 // Informal proof for (2), assuming (1) [*]: 10406 // 10407 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10408 // 10409 // Then 10410 // 10411 // FoundLHS s< FoundRHS s< INT_MIN - C 10412 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10413 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10414 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10415 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10416 // <=> FoundLHS + C s< FoundRHS + C 10417 // 10418 // [*]: (1) can be proved by ruling out overflow. 10419 // 10420 // [**]: This can be proved by analyzing all the four possibilities: 10421 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10422 // (A s>= 0, B s>= 0). 10423 // 10424 // Note: 10425 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10426 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10427 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10428 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10429 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10430 // C)". 10431 10432 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10433 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10434 if (!LDiff || !RDiff || *LDiff != *RDiff) 10435 return false; 10436 10437 if (LDiff->isMinValue()) 10438 return true; 10439 10440 APInt FoundRHSLimit; 10441 10442 if (Pred == CmpInst::ICMP_ULT) { 10443 FoundRHSLimit = -(*RDiff); 10444 } else { 10445 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10446 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10447 } 10448 10449 // Try to prove (1) or (2), as needed. 10450 return isAvailableAtLoopEntry(FoundRHS, L) && 10451 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10452 getConstant(FoundRHSLimit)); 10453 } 10454 10455 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10456 const SCEV *LHS, const SCEV *RHS, 10457 const SCEV *FoundLHS, 10458 const SCEV *FoundRHS, unsigned Depth) { 10459 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10460 10461 auto ClearOnExit = make_scope_exit([&]() { 10462 if (LPhi) { 10463 bool Erased = PendingMerges.erase(LPhi); 10464 assert(Erased && "Failed to erase LPhi!"); 10465 (void)Erased; 10466 } 10467 if (RPhi) { 10468 bool Erased = PendingMerges.erase(RPhi); 10469 assert(Erased && "Failed to erase RPhi!"); 10470 (void)Erased; 10471 } 10472 }); 10473 10474 // Find respective Phis and check that they are not being pending. 10475 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10476 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10477 if (!PendingMerges.insert(Phi).second) 10478 return false; 10479 LPhi = Phi; 10480 } 10481 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10482 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10483 // If we detect a loop of Phi nodes being processed by this method, for 10484 // example: 10485 // 10486 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10487 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10488 // 10489 // we don't want to deal with a case that complex, so return conservative 10490 // answer false. 10491 if (!PendingMerges.insert(Phi).second) 10492 return false; 10493 RPhi = Phi; 10494 } 10495 10496 // If none of LHS, RHS is a Phi, nothing to do here. 10497 if (!LPhi && !RPhi) 10498 return false; 10499 10500 // If there is a SCEVUnknown Phi we are interested in, make it left. 10501 if (!LPhi) { 10502 std::swap(LHS, RHS); 10503 std::swap(FoundLHS, FoundRHS); 10504 std::swap(LPhi, RPhi); 10505 Pred = ICmpInst::getSwappedPredicate(Pred); 10506 } 10507 10508 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10509 const BasicBlock *LBB = LPhi->getParent(); 10510 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10511 10512 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10513 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10514 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10515 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10516 }; 10517 10518 if (RPhi && RPhi->getParent() == LBB) { 10519 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10520 // If we compare two Phis from the same block, and for each entry block 10521 // the predicate is true for incoming values from this block, then the 10522 // predicate is also true for the Phis. 10523 for (const BasicBlock *IncBB : predecessors(LBB)) { 10524 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10525 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10526 if (!ProvedEasily(L, R)) 10527 return false; 10528 } 10529 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10530 // Case two: RHS is also a Phi from the same basic block, and it is an 10531 // AddRec. It means that there is a loop which has both AddRec and Unknown 10532 // PHIs, for it we can compare incoming values of AddRec from above the loop 10533 // and latch with their respective incoming values of LPhi. 10534 // TODO: Generalize to handle loops with many inputs in a header. 10535 if (LPhi->getNumIncomingValues() != 2) return false; 10536 10537 auto *RLoop = RAR->getLoop(); 10538 auto *Predecessor = RLoop->getLoopPredecessor(); 10539 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10540 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10541 if (!ProvedEasily(L1, RAR->getStart())) 10542 return false; 10543 auto *Latch = RLoop->getLoopLatch(); 10544 assert(Latch && "Loop with AddRec with no latch?"); 10545 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10546 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10547 return false; 10548 } else { 10549 // In all other cases go over inputs of LHS and compare each of them to RHS, 10550 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10551 // At this point RHS is either a non-Phi, or it is a Phi from some block 10552 // different from LBB. 10553 for (const BasicBlock *IncBB : predecessors(LBB)) { 10554 // Check that RHS is available in this block. 10555 if (!dominates(RHS, IncBB)) 10556 return false; 10557 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10558 if (!ProvedEasily(L, RHS)) 10559 return false; 10560 } 10561 } 10562 return true; 10563 } 10564 10565 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10566 const SCEV *LHS, const SCEV *RHS, 10567 const SCEV *FoundLHS, 10568 const SCEV *FoundRHS, 10569 const Instruction *Context) { 10570 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10571 return true; 10572 10573 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10574 return true; 10575 10576 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10577 Context)) 10578 return true; 10579 10580 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10581 FoundLHS, FoundRHS) || 10582 // ~x < ~y --> x > y 10583 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10584 getNotSCEV(FoundRHS), 10585 getNotSCEV(FoundLHS)); 10586 } 10587 10588 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10589 template <typename MinMaxExprType> 10590 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10591 const SCEV *Candidate) { 10592 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10593 if (!MinMaxExpr) 10594 return false; 10595 10596 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10597 } 10598 10599 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10600 ICmpInst::Predicate Pred, 10601 const SCEV *LHS, const SCEV *RHS) { 10602 // If both sides are affine addrecs for the same loop, with equal 10603 // steps, and we know the recurrences don't wrap, then we only 10604 // need to check the predicate on the starting values. 10605 10606 if (!ICmpInst::isRelational(Pred)) 10607 return false; 10608 10609 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10610 if (!LAR) 10611 return false; 10612 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10613 if (!RAR) 10614 return false; 10615 if (LAR->getLoop() != RAR->getLoop()) 10616 return false; 10617 if (!LAR->isAffine() || !RAR->isAffine()) 10618 return false; 10619 10620 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10621 return false; 10622 10623 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10624 SCEV::FlagNSW : SCEV::FlagNUW; 10625 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10626 return false; 10627 10628 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10629 } 10630 10631 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10632 /// expression? 10633 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10634 ICmpInst::Predicate Pred, 10635 const SCEV *LHS, const SCEV *RHS) { 10636 switch (Pred) { 10637 default: 10638 return false; 10639 10640 case ICmpInst::ICMP_SGE: 10641 std::swap(LHS, RHS); 10642 LLVM_FALLTHROUGH; 10643 case ICmpInst::ICMP_SLE: 10644 return 10645 // min(A, ...) <= A 10646 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10647 // A <= max(A, ...) 10648 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10649 10650 case ICmpInst::ICMP_UGE: 10651 std::swap(LHS, RHS); 10652 LLVM_FALLTHROUGH; 10653 case ICmpInst::ICMP_ULE: 10654 return 10655 // min(A, ...) <= A 10656 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10657 // A <= max(A, ...) 10658 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10659 } 10660 10661 llvm_unreachable("covered switch fell through?!"); 10662 } 10663 10664 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10665 const SCEV *LHS, const SCEV *RHS, 10666 const SCEV *FoundLHS, 10667 const SCEV *FoundRHS, 10668 unsigned Depth) { 10669 assert(getTypeSizeInBits(LHS->getType()) == 10670 getTypeSizeInBits(RHS->getType()) && 10671 "LHS and RHS have different sizes?"); 10672 assert(getTypeSizeInBits(FoundLHS->getType()) == 10673 getTypeSizeInBits(FoundRHS->getType()) && 10674 "FoundLHS and FoundRHS have different sizes?"); 10675 // We want to avoid hurting the compile time with analysis of too big trees. 10676 if (Depth > MaxSCEVOperationsImplicationDepth) 10677 return false; 10678 10679 // We only want to work with GT comparison so far. 10680 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10681 Pred = CmpInst::getSwappedPredicate(Pred); 10682 std::swap(LHS, RHS); 10683 std::swap(FoundLHS, FoundRHS); 10684 } 10685 10686 // For unsigned, try to reduce it to corresponding signed comparison. 10687 if (Pred == ICmpInst::ICMP_UGT) 10688 // We can replace unsigned predicate with its signed counterpart if all 10689 // involved values are non-negative. 10690 // TODO: We could have better support for unsigned. 10691 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10692 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10693 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10694 // use this fact to prove that LHS and RHS are non-negative. 10695 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10696 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10697 FoundRHS) && 10698 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10699 FoundRHS)) 10700 Pred = ICmpInst::ICMP_SGT; 10701 } 10702 10703 if (Pred != ICmpInst::ICMP_SGT) 10704 return false; 10705 10706 auto GetOpFromSExt = [&](const SCEV *S) { 10707 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10708 return Ext->getOperand(); 10709 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10710 // the constant in some cases. 10711 return S; 10712 }; 10713 10714 // Acquire values from extensions. 10715 auto *OrigLHS = LHS; 10716 auto *OrigFoundLHS = FoundLHS; 10717 LHS = GetOpFromSExt(LHS); 10718 FoundLHS = GetOpFromSExt(FoundLHS); 10719 10720 // Is the SGT predicate can be proved trivially or using the found context. 10721 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10722 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10723 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10724 FoundRHS, Depth + 1); 10725 }; 10726 10727 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10728 // We want to avoid creation of any new non-constant SCEV. Since we are 10729 // going to compare the operands to RHS, we should be certain that we don't 10730 // need any size extensions for this. So let's decline all cases when the 10731 // sizes of types of LHS and RHS do not match. 10732 // TODO: Maybe try to get RHS from sext to catch more cases? 10733 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10734 return false; 10735 10736 // Should not overflow. 10737 if (!LHSAddExpr->hasNoSignedWrap()) 10738 return false; 10739 10740 auto *LL = LHSAddExpr->getOperand(0); 10741 auto *LR = LHSAddExpr->getOperand(1); 10742 auto *MinusOne = getMinusOne(RHS->getType()); 10743 10744 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10745 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10746 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10747 }; 10748 // Try to prove the following rule: 10749 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10750 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10751 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10752 return true; 10753 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10754 Value *LL, *LR; 10755 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10756 10757 using namespace llvm::PatternMatch; 10758 10759 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10760 // Rules for division. 10761 // We are going to perform some comparisons with Denominator and its 10762 // derivative expressions. In general case, creating a SCEV for it may 10763 // lead to a complex analysis of the entire graph, and in particular it 10764 // can request trip count recalculation for the same loop. This would 10765 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10766 // this, we only want to create SCEVs that are constants in this section. 10767 // So we bail if Denominator is not a constant. 10768 if (!isa<ConstantInt>(LR)) 10769 return false; 10770 10771 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10772 10773 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10774 // then a SCEV for the numerator already exists and matches with FoundLHS. 10775 auto *Numerator = getExistingSCEV(LL); 10776 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10777 return false; 10778 10779 // Make sure that the numerator matches with FoundLHS and the denominator 10780 // is positive. 10781 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10782 return false; 10783 10784 auto *DTy = Denominator->getType(); 10785 auto *FRHSTy = FoundRHS->getType(); 10786 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10787 // One of types is a pointer and another one is not. We cannot extend 10788 // them properly to a wider type, so let us just reject this case. 10789 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10790 // to avoid this check. 10791 return false; 10792 10793 // Given that: 10794 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10795 auto *WTy = getWiderType(DTy, FRHSTy); 10796 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10797 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10798 10799 // Try to prove the following rule: 10800 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10801 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10802 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10803 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10804 if (isKnownNonPositive(RHS) && 10805 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10806 return true; 10807 10808 // Try to prove the following rule: 10809 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10810 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10811 // If we divide it by Denominator > 2, then: 10812 // 1. If FoundLHS is negative, then the result is 0. 10813 // 2. If FoundLHS is non-negative, then the result is non-negative. 10814 // Anyways, the result is non-negative. 10815 auto *MinusOne = getMinusOne(WTy); 10816 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10817 if (isKnownNegative(RHS) && 10818 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10819 return true; 10820 } 10821 } 10822 10823 // If our expression contained SCEVUnknown Phis, and we split it down and now 10824 // need to prove something for them, try to prove the predicate for every 10825 // possible incoming values of those Phis. 10826 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10827 return true; 10828 10829 return false; 10830 } 10831 10832 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10833 const SCEV *LHS, const SCEV *RHS) { 10834 // zext x u<= sext x, sext x s<= zext x 10835 switch (Pred) { 10836 case ICmpInst::ICMP_SGE: 10837 std::swap(LHS, RHS); 10838 LLVM_FALLTHROUGH; 10839 case ICmpInst::ICMP_SLE: { 10840 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10841 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10842 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10843 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10844 return true; 10845 break; 10846 } 10847 case ICmpInst::ICMP_UGE: 10848 std::swap(LHS, RHS); 10849 LLVM_FALLTHROUGH; 10850 case ICmpInst::ICMP_ULE: { 10851 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10852 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10853 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10854 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10855 return true; 10856 break; 10857 } 10858 default: 10859 break; 10860 }; 10861 return false; 10862 } 10863 10864 bool 10865 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10866 const SCEV *LHS, const SCEV *RHS) { 10867 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10868 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10869 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10870 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10871 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10872 } 10873 10874 bool 10875 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10876 const SCEV *LHS, const SCEV *RHS, 10877 const SCEV *FoundLHS, 10878 const SCEV *FoundRHS) { 10879 switch (Pred) { 10880 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10881 case ICmpInst::ICMP_EQ: 10882 case ICmpInst::ICMP_NE: 10883 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10884 return true; 10885 break; 10886 case ICmpInst::ICMP_SLT: 10887 case ICmpInst::ICMP_SLE: 10888 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10889 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10890 return true; 10891 break; 10892 case ICmpInst::ICMP_SGT: 10893 case ICmpInst::ICMP_SGE: 10894 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10895 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10896 return true; 10897 break; 10898 case ICmpInst::ICMP_ULT: 10899 case ICmpInst::ICMP_ULE: 10900 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10901 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10902 return true; 10903 break; 10904 case ICmpInst::ICMP_UGT: 10905 case ICmpInst::ICMP_UGE: 10906 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10907 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10908 return true; 10909 break; 10910 } 10911 10912 // Maybe it can be proved via operations? 10913 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10914 return true; 10915 10916 return false; 10917 } 10918 10919 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10920 const SCEV *LHS, 10921 const SCEV *RHS, 10922 const SCEV *FoundLHS, 10923 const SCEV *FoundRHS) { 10924 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10925 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10926 // reduce the compile time impact of this optimization. 10927 return false; 10928 10929 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10930 if (!Addend) 10931 return false; 10932 10933 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10934 10935 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10936 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10937 ConstantRange FoundLHSRange = 10938 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10939 10940 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10941 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10942 10943 // We can also compute the range of values for `LHS` that satisfy the 10944 // consequent, "`LHS` `Pred` `RHS`": 10945 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10946 ConstantRange SatisfyingLHSRange = 10947 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10948 10949 // The antecedent implies the consequent if every value of `LHS` that 10950 // satisfies the antecedent also satisfies the consequent. 10951 return SatisfyingLHSRange.contains(LHSRange); 10952 } 10953 10954 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10955 bool IsSigned, bool NoWrap) { 10956 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10957 10958 if (NoWrap) return false; 10959 10960 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10961 const SCEV *One = getOne(Stride->getType()); 10962 10963 if (IsSigned) { 10964 APInt MaxRHS = getSignedRangeMax(RHS); 10965 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10966 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10967 10968 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10969 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10970 } 10971 10972 APInt MaxRHS = getUnsignedRangeMax(RHS); 10973 APInt MaxValue = APInt::getMaxValue(BitWidth); 10974 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10975 10976 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10977 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10978 } 10979 10980 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10981 bool IsSigned, bool NoWrap) { 10982 if (NoWrap) return false; 10983 10984 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10985 const SCEV *One = getOne(Stride->getType()); 10986 10987 if (IsSigned) { 10988 APInt MinRHS = getSignedRangeMin(RHS); 10989 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10990 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10991 10992 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10993 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10994 } 10995 10996 APInt MinRHS = getUnsignedRangeMin(RHS); 10997 APInt MinValue = APInt::getMinValue(BitWidth); 10998 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10999 11000 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11001 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11002 } 11003 11004 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 11005 bool Equality) { 11006 const SCEV *One = getOne(Step->getType()); 11007 Delta = Equality ? getAddExpr(Delta, Step) 11008 : getAddExpr(Delta, getMinusSCEV(Step, One)); 11009 return getUDivExpr(Delta, Step); 11010 } 11011 11012 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11013 const SCEV *Stride, 11014 const SCEV *End, 11015 unsigned BitWidth, 11016 bool IsSigned) { 11017 11018 assert(!isKnownNonPositive(Stride) && 11019 "Stride is expected strictly positive!"); 11020 // Calculate the maximum backedge count based on the range of values 11021 // permitted by Start, End, and Stride. 11022 const SCEV *MaxBECount; 11023 APInt MinStart = 11024 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11025 11026 APInt StrideForMaxBECount = 11027 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11028 11029 // We already know that the stride is positive, so we paper over conservatism 11030 // in our range computation by forcing StrideForMaxBECount to be at least one. 11031 // In theory this is unnecessary, but we expect MaxBECount to be a 11032 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11033 // is nothing to constant fold it to). 11034 APInt One(BitWidth, 1, IsSigned); 11035 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11036 11037 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11038 : APInt::getMaxValue(BitWidth); 11039 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11040 11041 // Although End can be a MAX expression we estimate MaxEnd considering only 11042 // the case End = RHS of the loop termination condition. This is safe because 11043 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11044 // taken count. 11045 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11046 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11047 11048 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11049 getConstant(StrideForMaxBECount) /* Step */, 11050 false /* Equality */); 11051 11052 return MaxBECount; 11053 } 11054 11055 ScalarEvolution::ExitLimit 11056 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11057 const Loop *L, bool IsSigned, 11058 bool ControlsExit, bool AllowPredicates) { 11059 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11060 11061 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11062 bool PredicatedIV = false; 11063 11064 if (!IV && AllowPredicates) { 11065 // Try to make this an AddRec using runtime tests, in the first X 11066 // iterations of this loop, where X is the SCEV expression found by the 11067 // algorithm below. 11068 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11069 PredicatedIV = true; 11070 } 11071 11072 // Avoid weird loops 11073 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11074 return getCouldNotCompute(); 11075 11076 bool NoWrap = ControlsExit && 11077 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11078 11079 const SCEV *Stride = IV->getStepRecurrence(*this); 11080 11081 bool PositiveStride = isKnownPositive(Stride); 11082 11083 // Avoid negative or zero stride values. 11084 if (!PositiveStride) { 11085 // We can compute the correct backedge taken count for loops with unknown 11086 // strides if we can prove that the loop is not an infinite loop with side 11087 // effects. Here's the loop structure we are trying to handle - 11088 // 11089 // i = start 11090 // do { 11091 // A[i] = i; 11092 // i += s; 11093 // } while (i < end); 11094 // 11095 // The backedge taken count for such loops is evaluated as - 11096 // (max(end, start + stride) - start - 1) /u stride 11097 // 11098 // The additional preconditions that we need to check to prove correctness 11099 // of the above formula is as follows - 11100 // 11101 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11102 // NoWrap flag). 11103 // b) loop is single exit with no side effects. 11104 // 11105 // 11106 // Precondition a) implies that if the stride is negative, this is a single 11107 // trip loop. The backedge taken count formula reduces to zero in this case. 11108 // 11109 // Precondition b) implies that the unknown stride cannot be zero otherwise 11110 // we have UB. 11111 // 11112 // The positive stride case is the same as isKnownPositive(Stride) returning 11113 // true (original behavior of the function). 11114 // 11115 // We want to make sure that the stride is truly unknown as there are edge 11116 // cases where ScalarEvolution propagates no wrap flags to the 11117 // post-increment/decrement IV even though the increment/decrement operation 11118 // itself is wrapping. The computed backedge taken count may be wrong in 11119 // such cases. This is prevented by checking that the stride is not known to 11120 // be either positive or non-positive. For example, no wrap flags are 11121 // propagated to the post-increment IV of this loop with a trip count of 2 - 11122 // 11123 // unsigned char i; 11124 // for(i=127; i<128; i+=129) 11125 // A[i] = i; 11126 // 11127 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11128 !loopHasNoSideEffects(L)) 11129 return getCouldNotCompute(); 11130 } else if (!Stride->isOne() && 11131 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 11132 // Avoid proven overflow cases: this will ensure that the backedge taken 11133 // count will not generate any unsigned overflow. Relaxed no-overflow 11134 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11135 // undefined behaviors like the case of C language. 11136 return getCouldNotCompute(); 11137 11138 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11139 : ICmpInst::ICMP_ULT; 11140 const SCEV *Start = IV->getStart(); 11141 const SCEV *End = RHS; 11142 // When the RHS is not invariant, we do not know the end bound of the loop and 11143 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11144 // calculate the MaxBECount, given the start, stride and max value for the end 11145 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11146 // checked above). 11147 if (!isLoopInvariant(RHS, L)) { 11148 const SCEV *MaxBECount = computeMaxBECountForLT( 11149 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11150 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11151 false /*MaxOrZero*/, Predicates); 11152 } 11153 // If the backedge is taken at least once, then it will be taken 11154 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11155 // is the LHS value of the less-than comparison the first time it is evaluated 11156 // and End is the RHS. 11157 const SCEV *BECountIfBackedgeTaken = 11158 computeBECount(getMinusSCEV(End, Start), Stride, false); 11159 // If the loop entry is guarded by the result of the backedge test of the 11160 // first loop iteration, then we know the backedge will be taken at least 11161 // once and so the backedge taken count is as above. If not then we use the 11162 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11163 // as if the backedge is taken at least once max(End,Start) is End and so the 11164 // result is as above, and if not max(End,Start) is Start so we get a backedge 11165 // count of zero. 11166 const SCEV *BECount; 11167 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11168 BECount = BECountIfBackedgeTaken; 11169 else { 11170 // If we know that RHS >= Start in the context of loop, then we know that 11171 // max(RHS, Start) = RHS at this point. 11172 if (isLoopEntryGuardedByCond( 11173 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11174 End = RHS; 11175 else 11176 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11177 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 11178 } 11179 11180 const SCEV *MaxBECount; 11181 bool MaxOrZero = false; 11182 if (isa<SCEVConstant>(BECount)) 11183 MaxBECount = BECount; 11184 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11185 // If we know exactly how many times the backedge will be taken if it's 11186 // taken at least once, then the backedge count will either be that or 11187 // zero. 11188 MaxBECount = BECountIfBackedgeTaken; 11189 MaxOrZero = true; 11190 } else { 11191 MaxBECount = computeMaxBECountForLT( 11192 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11193 } 11194 11195 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11196 !isa<SCEVCouldNotCompute>(BECount)) 11197 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11198 11199 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11200 } 11201 11202 ScalarEvolution::ExitLimit 11203 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11204 const Loop *L, bool IsSigned, 11205 bool ControlsExit, bool AllowPredicates) { 11206 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11207 // We handle only IV > Invariant 11208 if (!isLoopInvariant(RHS, L)) 11209 return getCouldNotCompute(); 11210 11211 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11212 if (!IV && AllowPredicates) 11213 // Try to make this an AddRec using runtime tests, in the first X 11214 // iterations of this loop, where X is the SCEV expression found by the 11215 // algorithm below. 11216 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11217 11218 // Avoid weird loops 11219 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11220 return getCouldNotCompute(); 11221 11222 bool NoWrap = ControlsExit && 11223 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11224 11225 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11226 11227 // Avoid negative or zero stride values 11228 if (!isKnownPositive(Stride)) 11229 return getCouldNotCompute(); 11230 11231 // Avoid proven overflow cases: this will ensure that the backedge taken count 11232 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11233 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11234 // behaviors like the case of C language. 11235 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 11236 return getCouldNotCompute(); 11237 11238 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11239 : ICmpInst::ICMP_UGT; 11240 11241 const SCEV *Start = IV->getStart(); 11242 const SCEV *End = RHS; 11243 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11244 // If we know that Start >= RHS in the context of loop, then we know that 11245 // min(RHS, Start) = RHS at this point. 11246 if (isLoopEntryGuardedByCond( 11247 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11248 End = RHS; 11249 else 11250 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11251 } 11252 11253 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 11254 11255 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11256 : getUnsignedRangeMax(Start); 11257 11258 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11259 : getUnsignedRangeMin(Stride); 11260 11261 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11262 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11263 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11264 11265 // Although End can be a MIN expression we estimate MinEnd considering only 11266 // the case End = RHS. This is safe because in the other case (Start - End) 11267 // is zero, leading to a zero maximum backedge taken count. 11268 APInt MinEnd = 11269 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11270 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11271 11272 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11273 ? BECount 11274 : computeBECount(getConstant(MaxStart - MinEnd), 11275 getConstant(MinStride), false); 11276 11277 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11278 MaxBECount = BECount; 11279 11280 return ExitLimit(BECount, MaxBECount, false, Predicates); 11281 } 11282 11283 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11284 ScalarEvolution &SE) const { 11285 if (Range.isFullSet()) // Infinite loop. 11286 return SE.getCouldNotCompute(); 11287 11288 // If the start is a non-zero constant, shift the range to simplify things. 11289 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11290 if (!SC->getValue()->isZero()) { 11291 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 11292 Operands[0] = SE.getZero(SC->getType()); 11293 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11294 getNoWrapFlags(FlagNW)); 11295 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11296 return ShiftedAddRec->getNumIterationsInRange( 11297 Range.subtract(SC->getAPInt()), SE); 11298 // This is strange and shouldn't happen. 11299 return SE.getCouldNotCompute(); 11300 } 11301 11302 // The only time we can solve this is when we have all constant indices. 11303 // Otherwise, we cannot determine the overflow conditions. 11304 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11305 return SE.getCouldNotCompute(); 11306 11307 // Okay at this point we know that all elements of the chrec are constants and 11308 // that the start element is zero. 11309 11310 // First check to see if the range contains zero. If not, the first 11311 // iteration exits. 11312 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11313 if (!Range.contains(APInt(BitWidth, 0))) 11314 return SE.getZero(getType()); 11315 11316 if (isAffine()) { 11317 // If this is an affine expression then we have this situation: 11318 // Solve {0,+,A} in Range === Ax in Range 11319 11320 // We know that zero is in the range. If A is positive then we know that 11321 // the upper value of the range must be the first possible exit value. 11322 // If A is negative then the lower of the range is the last possible loop 11323 // value. Also note that we already checked for a full range. 11324 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11325 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11326 11327 // The exit value should be (End+A)/A. 11328 APInt ExitVal = (End + A).udiv(A); 11329 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11330 11331 // Evaluate at the exit value. If we really did fall out of the valid 11332 // range, then we computed our trip count, otherwise wrap around or other 11333 // things must have happened. 11334 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11335 if (Range.contains(Val->getValue())) 11336 return SE.getCouldNotCompute(); // Something strange happened 11337 11338 // Ensure that the previous value is in the range. This is a sanity check. 11339 assert(Range.contains( 11340 EvaluateConstantChrecAtConstant(this, 11341 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11342 "Linear scev computation is off in a bad way!"); 11343 return SE.getConstant(ExitValue); 11344 } 11345 11346 if (isQuadratic()) { 11347 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11348 return SE.getConstant(S.getValue()); 11349 } 11350 11351 return SE.getCouldNotCompute(); 11352 } 11353 11354 const SCEVAddRecExpr * 11355 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11356 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11357 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11358 // but in this case we cannot guarantee that the value returned will be an 11359 // AddRec because SCEV does not have a fixed point where it stops 11360 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11361 // may happen if we reach arithmetic depth limit while simplifying. So we 11362 // construct the returned value explicitly. 11363 SmallVector<const SCEV *, 3> Ops; 11364 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11365 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11366 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11367 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11368 // We know that the last operand is not a constant zero (otherwise it would 11369 // have been popped out earlier). This guarantees us that if the result has 11370 // the same last operand, then it will also not be popped out, meaning that 11371 // the returned value will be an AddRec. 11372 const SCEV *Last = getOperand(getNumOperands() - 1); 11373 assert(!Last->isZero() && "Recurrency with zero step?"); 11374 Ops.push_back(Last); 11375 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11376 SCEV::FlagAnyWrap)); 11377 } 11378 11379 // Return true when S contains at least an undef value. 11380 static inline bool containsUndefs(const SCEV *S) { 11381 return SCEVExprContains(S, [](const SCEV *S) { 11382 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11383 return isa<UndefValue>(SU->getValue()); 11384 return false; 11385 }); 11386 } 11387 11388 namespace { 11389 11390 // Collect all steps of SCEV expressions. 11391 struct SCEVCollectStrides { 11392 ScalarEvolution &SE; 11393 SmallVectorImpl<const SCEV *> &Strides; 11394 11395 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11396 : SE(SE), Strides(S) {} 11397 11398 bool follow(const SCEV *S) { 11399 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11400 Strides.push_back(AR->getStepRecurrence(SE)); 11401 return true; 11402 } 11403 11404 bool isDone() const { return false; } 11405 }; 11406 11407 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11408 struct SCEVCollectTerms { 11409 SmallVectorImpl<const SCEV *> &Terms; 11410 11411 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11412 11413 bool follow(const SCEV *S) { 11414 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11415 isa<SCEVSignExtendExpr>(S)) { 11416 if (!containsUndefs(S)) 11417 Terms.push_back(S); 11418 11419 // Stop recursion: once we collected a term, do not walk its operands. 11420 return false; 11421 } 11422 11423 // Keep looking. 11424 return true; 11425 } 11426 11427 bool isDone() const { return false; } 11428 }; 11429 11430 // Check if a SCEV contains an AddRecExpr. 11431 struct SCEVHasAddRec { 11432 bool &ContainsAddRec; 11433 11434 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11435 ContainsAddRec = false; 11436 } 11437 11438 bool follow(const SCEV *S) { 11439 if (isa<SCEVAddRecExpr>(S)) { 11440 ContainsAddRec = true; 11441 11442 // Stop recursion: once we collected a term, do not walk its operands. 11443 return false; 11444 } 11445 11446 // Keep looking. 11447 return true; 11448 } 11449 11450 bool isDone() const { return false; } 11451 }; 11452 11453 // Find factors that are multiplied with an expression that (possibly as a 11454 // subexpression) contains an AddRecExpr. In the expression: 11455 // 11456 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11457 // 11458 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11459 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11460 // parameters as they form a product with an induction variable. 11461 // 11462 // This collector expects all array size parameters to be in the same MulExpr. 11463 // It might be necessary to later add support for collecting parameters that are 11464 // spread over different nested MulExpr. 11465 struct SCEVCollectAddRecMultiplies { 11466 SmallVectorImpl<const SCEV *> &Terms; 11467 ScalarEvolution &SE; 11468 11469 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11470 : Terms(T), SE(SE) {} 11471 11472 bool follow(const SCEV *S) { 11473 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11474 bool HasAddRec = false; 11475 SmallVector<const SCEV *, 0> Operands; 11476 for (auto Op : Mul->operands()) { 11477 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11478 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11479 Operands.push_back(Op); 11480 } else if (Unknown) { 11481 HasAddRec = true; 11482 } else { 11483 bool ContainsAddRec = false; 11484 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11485 visitAll(Op, ContiansAddRec); 11486 HasAddRec |= ContainsAddRec; 11487 } 11488 } 11489 if (Operands.size() == 0) 11490 return true; 11491 11492 if (!HasAddRec) 11493 return false; 11494 11495 Terms.push_back(SE.getMulExpr(Operands)); 11496 // Stop recursion: once we collected a term, do not walk its operands. 11497 return false; 11498 } 11499 11500 // Keep looking. 11501 return true; 11502 } 11503 11504 bool isDone() const { return false; } 11505 }; 11506 11507 } // end anonymous namespace 11508 11509 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11510 /// two places: 11511 /// 1) The strides of AddRec expressions. 11512 /// 2) Unknowns that are multiplied with AddRec expressions. 11513 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11514 SmallVectorImpl<const SCEV *> &Terms) { 11515 SmallVector<const SCEV *, 4> Strides; 11516 SCEVCollectStrides StrideCollector(*this, Strides); 11517 visitAll(Expr, StrideCollector); 11518 11519 LLVM_DEBUG({ 11520 dbgs() << "Strides:\n"; 11521 for (const SCEV *S : Strides) 11522 dbgs() << *S << "\n"; 11523 }); 11524 11525 for (const SCEV *S : Strides) { 11526 SCEVCollectTerms TermCollector(Terms); 11527 visitAll(S, TermCollector); 11528 } 11529 11530 LLVM_DEBUG({ 11531 dbgs() << "Terms:\n"; 11532 for (const SCEV *T : Terms) 11533 dbgs() << *T << "\n"; 11534 }); 11535 11536 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11537 visitAll(Expr, MulCollector); 11538 } 11539 11540 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11541 SmallVectorImpl<const SCEV *> &Terms, 11542 SmallVectorImpl<const SCEV *> &Sizes) { 11543 int Last = Terms.size() - 1; 11544 const SCEV *Step = Terms[Last]; 11545 11546 // End of recursion. 11547 if (Last == 0) { 11548 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11549 SmallVector<const SCEV *, 2> Qs; 11550 for (const SCEV *Op : M->operands()) 11551 if (!isa<SCEVConstant>(Op)) 11552 Qs.push_back(Op); 11553 11554 Step = SE.getMulExpr(Qs); 11555 } 11556 11557 Sizes.push_back(Step); 11558 return true; 11559 } 11560 11561 for (const SCEV *&Term : Terms) { 11562 // Normalize the terms before the next call to findArrayDimensionsRec. 11563 const SCEV *Q, *R; 11564 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11565 11566 // Bail out when GCD does not evenly divide one of the terms. 11567 if (!R->isZero()) 11568 return false; 11569 11570 Term = Q; 11571 } 11572 11573 // Remove all SCEVConstants. 11574 Terms.erase( 11575 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11576 Terms.end()); 11577 11578 if (Terms.size() > 0) 11579 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11580 return false; 11581 11582 Sizes.push_back(Step); 11583 return true; 11584 } 11585 11586 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11587 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11588 for (const SCEV *T : Terms) 11589 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11590 return true; 11591 11592 return false; 11593 } 11594 11595 // Return the number of product terms in S. 11596 static inline int numberOfTerms(const SCEV *S) { 11597 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11598 return Expr->getNumOperands(); 11599 return 1; 11600 } 11601 11602 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11603 if (isa<SCEVConstant>(T)) 11604 return nullptr; 11605 11606 if (isa<SCEVUnknown>(T)) 11607 return T; 11608 11609 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11610 SmallVector<const SCEV *, 2> Factors; 11611 for (const SCEV *Op : M->operands()) 11612 if (!isa<SCEVConstant>(Op)) 11613 Factors.push_back(Op); 11614 11615 return SE.getMulExpr(Factors); 11616 } 11617 11618 return T; 11619 } 11620 11621 /// Return the size of an element read or written by Inst. 11622 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11623 Type *Ty; 11624 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11625 Ty = Store->getValueOperand()->getType(); 11626 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11627 Ty = Load->getType(); 11628 else 11629 return nullptr; 11630 11631 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11632 return getSizeOfExpr(ETy, Ty); 11633 } 11634 11635 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11636 SmallVectorImpl<const SCEV *> &Sizes, 11637 const SCEV *ElementSize) { 11638 if (Terms.size() < 1 || !ElementSize) 11639 return; 11640 11641 // Early return when Terms do not contain parameters: we do not delinearize 11642 // non parametric SCEVs. 11643 if (!containsParameters(Terms)) 11644 return; 11645 11646 LLVM_DEBUG({ 11647 dbgs() << "Terms:\n"; 11648 for (const SCEV *T : Terms) 11649 dbgs() << *T << "\n"; 11650 }); 11651 11652 // Remove duplicates. 11653 array_pod_sort(Terms.begin(), Terms.end()); 11654 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11655 11656 // Put larger terms first. 11657 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11658 return numberOfTerms(LHS) > numberOfTerms(RHS); 11659 }); 11660 11661 // Try to divide all terms by the element size. If term is not divisible by 11662 // element size, proceed with the original term. 11663 for (const SCEV *&Term : Terms) { 11664 const SCEV *Q, *R; 11665 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11666 if (!Q->isZero()) 11667 Term = Q; 11668 } 11669 11670 SmallVector<const SCEV *, 4> NewTerms; 11671 11672 // Remove constant factors. 11673 for (const SCEV *T : Terms) 11674 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11675 NewTerms.push_back(NewT); 11676 11677 LLVM_DEBUG({ 11678 dbgs() << "Terms after sorting:\n"; 11679 for (const SCEV *T : NewTerms) 11680 dbgs() << *T << "\n"; 11681 }); 11682 11683 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11684 Sizes.clear(); 11685 return; 11686 } 11687 11688 // The last element to be pushed into Sizes is the size of an element. 11689 Sizes.push_back(ElementSize); 11690 11691 LLVM_DEBUG({ 11692 dbgs() << "Sizes:\n"; 11693 for (const SCEV *S : Sizes) 11694 dbgs() << *S << "\n"; 11695 }); 11696 } 11697 11698 void ScalarEvolution::computeAccessFunctions( 11699 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11700 SmallVectorImpl<const SCEV *> &Sizes) { 11701 // Early exit in case this SCEV is not an affine multivariate function. 11702 if (Sizes.empty()) 11703 return; 11704 11705 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11706 if (!AR->isAffine()) 11707 return; 11708 11709 const SCEV *Res = Expr; 11710 int Last = Sizes.size() - 1; 11711 for (int i = Last; i >= 0; i--) { 11712 const SCEV *Q, *R; 11713 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11714 11715 LLVM_DEBUG({ 11716 dbgs() << "Res: " << *Res << "\n"; 11717 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11718 dbgs() << "Res divided by Sizes[i]:\n"; 11719 dbgs() << "Quotient: " << *Q << "\n"; 11720 dbgs() << "Remainder: " << *R << "\n"; 11721 }); 11722 11723 Res = Q; 11724 11725 // Do not record the last subscript corresponding to the size of elements in 11726 // the array. 11727 if (i == Last) { 11728 11729 // Bail out if the remainder is too complex. 11730 if (isa<SCEVAddRecExpr>(R)) { 11731 Subscripts.clear(); 11732 Sizes.clear(); 11733 return; 11734 } 11735 11736 continue; 11737 } 11738 11739 // Record the access function for the current subscript. 11740 Subscripts.push_back(R); 11741 } 11742 11743 // Also push in last position the remainder of the last division: it will be 11744 // the access function of the innermost dimension. 11745 Subscripts.push_back(Res); 11746 11747 std::reverse(Subscripts.begin(), Subscripts.end()); 11748 11749 LLVM_DEBUG({ 11750 dbgs() << "Subscripts:\n"; 11751 for (const SCEV *S : Subscripts) 11752 dbgs() << *S << "\n"; 11753 }); 11754 } 11755 11756 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11757 /// sizes of an array access. Returns the remainder of the delinearization that 11758 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11759 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11760 /// expressions in the stride and base of a SCEV corresponding to the 11761 /// computation of a GCD (greatest common divisor) of base and stride. When 11762 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11763 /// 11764 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11765 /// 11766 /// void foo(long n, long m, long o, double A[n][m][o]) { 11767 /// 11768 /// for (long i = 0; i < n; i++) 11769 /// for (long j = 0; j < m; j++) 11770 /// for (long k = 0; k < o; k++) 11771 /// A[i][j][k] = 1.0; 11772 /// } 11773 /// 11774 /// the delinearization input is the following AddRec SCEV: 11775 /// 11776 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11777 /// 11778 /// From this SCEV, we are able to say that the base offset of the access is %A 11779 /// because it appears as an offset that does not divide any of the strides in 11780 /// the loops: 11781 /// 11782 /// CHECK: Base offset: %A 11783 /// 11784 /// and then SCEV->delinearize determines the size of some of the dimensions of 11785 /// the array as these are the multiples by which the strides are happening: 11786 /// 11787 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11788 /// 11789 /// Note that the outermost dimension remains of UnknownSize because there are 11790 /// no strides that would help identifying the size of the last dimension: when 11791 /// the array has been statically allocated, one could compute the size of that 11792 /// dimension by dividing the overall size of the array by the size of the known 11793 /// dimensions: %m * %o * 8. 11794 /// 11795 /// Finally delinearize provides the access functions for the array reference 11796 /// that does correspond to A[i][j][k] of the above C testcase: 11797 /// 11798 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11799 /// 11800 /// The testcases are checking the output of a function pass: 11801 /// DelinearizationPass that walks through all loads and stores of a function 11802 /// asking for the SCEV of the memory access with respect to all enclosing 11803 /// loops, calling SCEV->delinearize on that and printing the results. 11804 void ScalarEvolution::delinearize(const SCEV *Expr, 11805 SmallVectorImpl<const SCEV *> &Subscripts, 11806 SmallVectorImpl<const SCEV *> &Sizes, 11807 const SCEV *ElementSize) { 11808 // First step: collect parametric terms. 11809 SmallVector<const SCEV *, 4> Terms; 11810 collectParametricTerms(Expr, Terms); 11811 11812 if (Terms.empty()) 11813 return; 11814 11815 // Second step: find subscript sizes. 11816 findArrayDimensions(Terms, Sizes, ElementSize); 11817 11818 if (Sizes.empty()) 11819 return; 11820 11821 // Third step: compute the access functions for each subscript. 11822 computeAccessFunctions(Expr, Subscripts, Sizes); 11823 11824 if (Subscripts.empty()) 11825 return; 11826 11827 LLVM_DEBUG({ 11828 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11829 dbgs() << "ArrayDecl[UnknownSize]"; 11830 for (const SCEV *S : Sizes) 11831 dbgs() << "[" << *S << "]"; 11832 11833 dbgs() << "\nArrayRef"; 11834 for (const SCEV *S : Subscripts) 11835 dbgs() << "[" << *S << "]"; 11836 dbgs() << "\n"; 11837 }); 11838 } 11839 11840 bool ScalarEvolution::getIndexExpressionsFromGEP( 11841 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11842 SmallVectorImpl<int> &Sizes) { 11843 assert(Subscripts.empty() && Sizes.empty() && 11844 "Expected output lists to be empty on entry to this function."); 11845 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11846 Type *Ty = GEP->getPointerOperandType(); 11847 bool DroppedFirstDim = false; 11848 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11849 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11850 if (i == 1) { 11851 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11852 Ty = PtrTy->getElementType(); 11853 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11854 Ty = ArrayTy->getElementType(); 11855 } else { 11856 Subscripts.clear(); 11857 Sizes.clear(); 11858 return false; 11859 } 11860 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11861 if (Const->getValue()->isZero()) { 11862 DroppedFirstDim = true; 11863 continue; 11864 } 11865 Subscripts.push_back(Expr); 11866 continue; 11867 } 11868 11869 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11870 if (!ArrayTy) { 11871 Subscripts.clear(); 11872 Sizes.clear(); 11873 return false; 11874 } 11875 11876 Subscripts.push_back(Expr); 11877 if (!(DroppedFirstDim && i == 2)) 11878 Sizes.push_back(ArrayTy->getNumElements()); 11879 11880 Ty = ArrayTy->getElementType(); 11881 } 11882 return !Subscripts.empty(); 11883 } 11884 11885 //===----------------------------------------------------------------------===// 11886 // SCEVCallbackVH Class Implementation 11887 //===----------------------------------------------------------------------===// 11888 11889 void ScalarEvolution::SCEVCallbackVH::deleted() { 11890 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11891 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11892 SE->ConstantEvolutionLoopExitValue.erase(PN); 11893 SE->eraseValueFromMap(getValPtr()); 11894 // this now dangles! 11895 } 11896 11897 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11898 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11899 11900 // Forget all the expressions associated with users of the old value, 11901 // so that future queries will recompute the expressions using the new 11902 // value. 11903 Value *Old = getValPtr(); 11904 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11905 SmallPtrSet<User *, 8> Visited; 11906 while (!Worklist.empty()) { 11907 User *U = Worklist.pop_back_val(); 11908 // Deleting the Old value will cause this to dangle. Postpone 11909 // that until everything else is done. 11910 if (U == Old) 11911 continue; 11912 if (!Visited.insert(U).second) 11913 continue; 11914 if (PHINode *PN = dyn_cast<PHINode>(U)) 11915 SE->ConstantEvolutionLoopExitValue.erase(PN); 11916 SE->eraseValueFromMap(U); 11917 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11918 } 11919 // Delete the Old value. 11920 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11921 SE->ConstantEvolutionLoopExitValue.erase(PN); 11922 SE->eraseValueFromMap(Old); 11923 // this now dangles! 11924 } 11925 11926 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11927 : CallbackVH(V), SE(se) {} 11928 11929 //===----------------------------------------------------------------------===// 11930 // ScalarEvolution Class Implementation 11931 //===----------------------------------------------------------------------===// 11932 11933 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11934 AssumptionCache &AC, DominatorTree &DT, 11935 LoopInfo &LI) 11936 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11937 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11938 LoopDispositions(64), BlockDispositions(64) { 11939 // To use guards for proving predicates, we need to scan every instruction in 11940 // relevant basic blocks, and not just terminators. Doing this is a waste of 11941 // time if the IR does not actually contain any calls to 11942 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11943 // 11944 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11945 // to _add_ guards to the module when there weren't any before, and wants 11946 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11947 // efficient in lieu of being smart in that rather obscure case. 11948 11949 auto *GuardDecl = F.getParent()->getFunction( 11950 Intrinsic::getName(Intrinsic::experimental_guard)); 11951 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11952 } 11953 11954 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11955 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11956 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11957 ValueExprMap(std::move(Arg.ValueExprMap)), 11958 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11959 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11960 PendingMerges(std::move(Arg.PendingMerges)), 11961 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11962 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11963 PredicatedBackedgeTakenCounts( 11964 std::move(Arg.PredicatedBackedgeTakenCounts)), 11965 ConstantEvolutionLoopExitValue( 11966 std::move(Arg.ConstantEvolutionLoopExitValue)), 11967 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11968 LoopDispositions(std::move(Arg.LoopDispositions)), 11969 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11970 BlockDispositions(std::move(Arg.BlockDispositions)), 11971 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11972 SignedRanges(std::move(Arg.SignedRanges)), 11973 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11974 UniquePreds(std::move(Arg.UniquePreds)), 11975 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11976 LoopUsers(std::move(Arg.LoopUsers)), 11977 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11978 FirstUnknown(Arg.FirstUnknown) { 11979 Arg.FirstUnknown = nullptr; 11980 } 11981 11982 ScalarEvolution::~ScalarEvolution() { 11983 // Iterate through all the SCEVUnknown instances and call their 11984 // destructors, so that they release their references to their values. 11985 for (SCEVUnknown *U = FirstUnknown; U;) { 11986 SCEVUnknown *Tmp = U; 11987 U = U->Next; 11988 Tmp->~SCEVUnknown(); 11989 } 11990 FirstUnknown = nullptr; 11991 11992 ExprValueMap.clear(); 11993 ValueExprMap.clear(); 11994 HasRecMap.clear(); 11995 11996 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11997 // that a loop had multiple computable exits. 11998 for (auto &BTCI : BackedgeTakenCounts) 11999 BTCI.second.clear(); 12000 for (auto &BTCI : PredicatedBackedgeTakenCounts) 12001 BTCI.second.clear(); 12002 12003 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12004 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12005 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12006 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12007 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12008 } 12009 12010 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12011 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12012 } 12013 12014 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12015 const Loop *L) { 12016 // Print all inner loops first 12017 for (Loop *I : *L) 12018 PrintLoopInfo(OS, SE, I); 12019 12020 OS << "Loop "; 12021 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12022 OS << ": "; 12023 12024 SmallVector<BasicBlock *, 8> ExitingBlocks; 12025 L->getExitingBlocks(ExitingBlocks); 12026 if (ExitingBlocks.size() != 1) 12027 OS << "<multiple exits> "; 12028 12029 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12030 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12031 else 12032 OS << "Unpredictable backedge-taken count.\n"; 12033 12034 if (ExitingBlocks.size() > 1) 12035 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12036 OS << " exit count for " << ExitingBlock->getName() << ": " 12037 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12038 } 12039 12040 OS << "Loop "; 12041 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12042 OS << ": "; 12043 12044 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12045 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12046 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12047 OS << ", actual taken count either this or zero."; 12048 } else { 12049 OS << "Unpredictable max backedge-taken count. "; 12050 } 12051 12052 OS << "\n" 12053 "Loop "; 12054 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12055 OS << ": "; 12056 12057 SCEVUnionPredicate Pred; 12058 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12059 if (!isa<SCEVCouldNotCompute>(PBT)) { 12060 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12061 OS << " Predicates:\n"; 12062 Pred.print(OS, 4); 12063 } else { 12064 OS << "Unpredictable predicated backedge-taken count. "; 12065 } 12066 OS << "\n"; 12067 12068 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12069 OS << "Loop "; 12070 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12071 OS << ": "; 12072 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12073 } 12074 } 12075 12076 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12077 switch (LD) { 12078 case ScalarEvolution::LoopVariant: 12079 return "Variant"; 12080 case ScalarEvolution::LoopInvariant: 12081 return "Invariant"; 12082 case ScalarEvolution::LoopComputable: 12083 return "Computable"; 12084 } 12085 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12086 } 12087 12088 void ScalarEvolution::print(raw_ostream &OS) const { 12089 // ScalarEvolution's implementation of the print method is to print 12090 // out SCEV values of all instructions that are interesting. Doing 12091 // this potentially causes it to create new SCEV objects though, 12092 // which technically conflicts with the const qualifier. This isn't 12093 // observable from outside the class though, so casting away the 12094 // const isn't dangerous. 12095 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12096 12097 if (ClassifyExpressions) { 12098 OS << "Classifying expressions for: "; 12099 F.printAsOperand(OS, /*PrintType=*/false); 12100 OS << "\n"; 12101 for (Instruction &I : instructions(F)) 12102 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12103 OS << I << '\n'; 12104 OS << " --> "; 12105 const SCEV *SV = SE.getSCEV(&I); 12106 SV->print(OS); 12107 if (!isa<SCEVCouldNotCompute>(SV)) { 12108 OS << " U: "; 12109 SE.getUnsignedRange(SV).print(OS); 12110 OS << " S: "; 12111 SE.getSignedRange(SV).print(OS); 12112 } 12113 12114 const Loop *L = LI.getLoopFor(I.getParent()); 12115 12116 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12117 if (AtUse != SV) { 12118 OS << " --> "; 12119 AtUse->print(OS); 12120 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12121 OS << " U: "; 12122 SE.getUnsignedRange(AtUse).print(OS); 12123 OS << " S: "; 12124 SE.getSignedRange(AtUse).print(OS); 12125 } 12126 } 12127 12128 if (L) { 12129 OS << "\t\t" "Exits: "; 12130 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12131 if (!SE.isLoopInvariant(ExitValue, L)) { 12132 OS << "<<Unknown>>"; 12133 } else { 12134 OS << *ExitValue; 12135 } 12136 12137 bool First = true; 12138 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12139 if (First) { 12140 OS << "\t\t" "LoopDispositions: { "; 12141 First = false; 12142 } else { 12143 OS << ", "; 12144 } 12145 12146 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12147 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12148 } 12149 12150 for (auto *InnerL : depth_first(L)) { 12151 if (InnerL == L) 12152 continue; 12153 if (First) { 12154 OS << "\t\t" "LoopDispositions: { "; 12155 First = false; 12156 } else { 12157 OS << ", "; 12158 } 12159 12160 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12161 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12162 } 12163 12164 OS << " }"; 12165 } 12166 12167 OS << "\n"; 12168 } 12169 } 12170 12171 OS << "Determining loop execution counts for: "; 12172 F.printAsOperand(OS, /*PrintType=*/false); 12173 OS << "\n"; 12174 for (Loop *I : LI) 12175 PrintLoopInfo(OS, &SE, I); 12176 } 12177 12178 ScalarEvolution::LoopDisposition 12179 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12180 auto &Values = LoopDispositions[S]; 12181 for (auto &V : Values) { 12182 if (V.getPointer() == L) 12183 return V.getInt(); 12184 } 12185 Values.emplace_back(L, LoopVariant); 12186 LoopDisposition D = computeLoopDisposition(S, L); 12187 auto &Values2 = LoopDispositions[S]; 12188 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12189 if (V.getPointer() == L) { 12190 V.setInt(D); 12191 break; 12192 } 12193 } 12194 return D; 12195 } 12196 12197 ScalarEvolution::LoopDisposition 12198 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12199 switch (S->getSCEVType()) { 12200 case scConstant: 12201 return LoopInvariant; 12202 case scPtrToInt: 12203 case scTruncate: 12204 case scZeroExtend: 12205 case scSignExtend: 12206 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12207 case scAddRecExpr: { 12208 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12209 12210 // If L is the addrec's loop, it's computable. 12211 if (AR->getLoop() == L) 12212 return LoopComputable; 12213 12214 // Add recurrences are never invariant in the function-body (null loop). 12215 if (!L) 12216 return LoopVariant; 12217 12218 // Everything that is not defined at loop entry is variant. 12219 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12220 return LoopVariant; 12221 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12222 " dominate the contained loop's header?"); 12223 12224 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12225 if (AR->getLoop()->contains(L)) 12226 return LoopInvariant; 12227 12228 // This recurrence is variant w.r.t. L if any of its operands 12229 // are variant. 12230 for (auto *Op : AR->operands()) 12231 if (!isLoopInvariant(Op, L)) 12232 return LoopVariant; 12233 12234 // Otherwise it's loop-invariant. 12235 return LoopInvariant; 12236 } 12237 case scAddExpr: 12238 case scMulExpr: 12239 case scUMaxExpr: 12240 case scSMaxExpr: 12241 case scUMinExpr: 12242 case scSMinExpr: { 12243 bool HasVarying = false; 12244 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12245 LoopDisposition D = getLoopDisposition(Op, L); 12246 if (D == LoopVariant) 12247 return LoopVariant; 12248 if (D == LoopComputable) 12249 HasVarying = true; 12250 } 12251 return HasVarying ? LoopComputable : LoopInvariant; 12252 } 12253 case scUDivExpr: { 12254 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12255 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12256 if (LD == LoopVariant) 12257 return LoopVariant; 12258 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12259 if (RD == LoopVariant) 12260 return LoopVariant; 12261 return (LD == LoopInvariant && RD == LoopInvariant) ? 12262 LoopInvariant : LoopComputable; 12263 } 12264 case scUnknown: 12265 // All non-instruction values are loop invariant. All instructions are loop 12266 // invariant if they are not contained in the specified loop. 12267 // Instructions are never considered invariant in the function body 12268 // (null loop) because they are defined within the "loop". 12269 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12270 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12271 return LoopInvariant; 12272 case scCouldNotCompute: 12273 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12274 } 12275 llvm_unreachable("Unknown SCEV kind!"); 12276 } 12277 12278 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12279 return getLoopDisposition(S, L) == LoopInvariant; 12280 } 12281 12282 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12283 return getLoopDisposition(S, L) == LoopComputable; 12284 } 12285 12286 ScalarEvolution::BlockDisposition 12287 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12288 auto &Values = BlockDispositions[S]; 12289 for (auto &V : Values) { 12290 if (V.getPointer() == BB) 12291 return V.getInt(); 12292 } 12293 Values.emplace_back(BB, DoesNotDominateBlock); 12294 BlockDisposition D = computeBlockDisposition(S, BB); 12295 auto &Values2 = BlockDispositions[S]; 12296 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12297 if (V.getPointer() == BB) { 12298 V.setInt(D); 12299 break; 12300 } 12301 } 12302 return D; 12303 } 12304 12305 ScalarEvolution::BlockDisposition 12306 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12307 switch (S->getSCEVType()) { 12308 case scConstant: 12309 return ProperlyDominatesBlock; 12310 case scPtrToInt: 12311 case scTruncate: 12312 case scZeroExtend: 12313 case scSignExtend: 12314 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12315 case scAddRecExpr: { 12316 // This uses a "dominates" query instead of "properly dominates" query 12317 // to test for proper dominance too, because the instruction which 12318 // produces the addrec's value is a PHI, and a PHI effectively properly 12319 // dominates its entire containing block. 12320 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12321 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12322 return DoesNotDominateBlock; 12323 12324 // Fall through into SCEVNAryExpr handling. 12325 LLVM_FALLTHROUGH; 12326 } 12327 case scAddExpr: 12328 case scMulExpr: 12329 case scUMaxExpr: 12330 case scSMaxExpr: 12331 case scUMinExpr: 12332 case scSMinExpr: { 12333 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12334 bool Proper = true; 12335 for (const SCEV *NAryOp : NAry->operands()) { 12336 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12337 if (D == DoesNotDominateBlock) 12338 return DoesNotDominateBlock; 12339 if (D == DominatesBlock) 12340 Proper = false; 12341 } 12342 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12343 } 12344 case scUDivExpr: { 12345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12346 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12347 BlockDisposition LD = getBlockDisposition(LHS, BB); 12348 if (LD == DoesNotDominateBlock) 12349 return DoesNotDominateBlock; 12350 BlockDisposition RD = getBlockDisposition(RHS, BB); 12351 if (RD == DoesNotDominateBlock) 12352 return DoesNotDominateBlock; 12353 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12354 ProperlyDominatesBlock : DominatesBlock; 12355 } 12356 case scUnknown: 12357 if (Instruction *I = 12358 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12359 if (I->getParent() == BB) 12360 return DominatesBlock; 12361 if (DT.properlyDominates(I->getParent(), BB)) 12362 return ProperlyDominatesBlock; 12363 return DoesNotDominateBlock; 12364 } 12365 return ProperlyDominatesBlock; 12366 case scCouldNotCompute: 12367 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12368 } 12369 llvm_unreachable("Unknown SCEV kind!"); 12370 } 12371 12372 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12373 return getBlockDisposition(S, BB) >= DominatesBlock; 12374 } 12375 12376 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12377 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12378 } 12379 12380 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12381 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12382 } 12383 12384 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 12385 auto IsS = [&](const SCEV *X) { return S == X; }; 12386 auto ContainsS = [&](const SCEV *X) { 12387 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12388 }; 12389 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12390 } 12391 12392 void 12393 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12394 ValuesAtScopes.erase(S); 12395 LoopDispositions.erase(S); 12396 BlockDispositions.erase(S); 12397 UnsignedRanges.erase(S); 12398 SignedRanges.erase(S); 12399 ExprValueMap.erase(S); 12400 HasRecMap.erase(S); 12401 MinTrailingZerosCache.erase(S); 12402 12403 for (auto I = PredicatedSCEVRewrites.begin(); 12404 I != PredicatedSCEVRewrites.end();) { 12405 std::pair<const SCEV *, const Loop *> Entry = I->first; 12406 if (Entry.first == S) 12407 PredicatedSCEVRewrites.erase(I++); 12408 else 12409 ++I; 12410 } 12411 12412 auto RemoveSCEVFromBackedgeMap = 12413 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12414 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12415 BackedgeTakenInfo &BEInfo = I->second; 12416 if (BEInfo.hasOperand(S, this)) { 12417 BEInfo.clear(); 12418 Map.erase(I++); 12419 } else 12420 ++I; 12421 } 12422 }; 12423 12424 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12425 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12426 } 12427 12428 void 12429 ScalarEvolution::getUsedLoops(const SCEV *S, 12430 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12431 struct FindUsedLoops { 12432 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12433 : LoopsUsed(LoopsUsed) {} 12434 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12435 bool follow(const SCEV *S) { 12436 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12437 LoopsUsed.insert(AR->getLoop()); 12438 return true; 12439 } 12440 12441 bool isDone() const { return false; } 12442 }; 12443 12444 FindUsedLoops F(LoopsUsed); 12445 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12446 } 12447 12448 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12449 SmallPtrSet<const Loop *, 8> LoopsUsed; 12450 getUsedLoops(S, LoopsUsed); 12451 for (auto *L : LoopsUsed) 12452 LoopUsers[L].push_back(S); 12453 } 12454 12455 void ScalarEvolution::verify() const { 12456 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12457 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12458 12459 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12460 12461 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12462 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12463 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12464 12465 const SCEV *visitConstant(const SCEVConstant *Constant) { 12466 return SE.getConstant(Constant->getAPInt()); 12467 } 12468 12469 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12470 return SE.getUnknown(Expr->getValue()); 12471 } 12472 12473 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12474 return SE.getCouldNotCompute(); 12475 } 12476 }; 12477 12478 SCEVMapper SCM(SE2); 12479 12480 while (!LoopStack.empty()) { 12481 auto *L = LoopStack.pop_back_val(); 12482 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12483 12484 auto *CurBECount = SCM.visit( 12485 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12486 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12487 12488 if (CurBECount == SE2.getCouldNotCompute() || 12489 NewBECount == SE2.getCouldNotCompute()) { 12490 // NB! This situation is legal, but is very suspicious -- whatever pass 12491 // change the loop to make a trip count go from could not compute to 12492 // computable or vice-versa *should have* invalidated SCEV. However, we 12493 // choose not to assert here (for now) since we don't want false 12494 // positives. 12495 continue; 12496 } 12497 12498 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12499 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12500 // not propagate undef aggressively). This means we can (and do) fail 12501 // verification in cases where a transform makes the trip count of a loop 12502 // go from "undef" to "undef+1" (say). The transform is fine, since in 12503 // both cases the loop iterates "undef" times, but SCEV thinks we 12504 // increased the trip count of the loop by 1 incorrectly. 12505 continue; 12506 } 12507 12508 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12509 SE.getTypeSizeInBits(NewBECount->getType())) 12510 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12511 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12512 SE.getTypeSizeInBits(NewBECount->getType())) 12513 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12514 12515 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12516 12517 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12518 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12519 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12520 dbgs() << "Old: " << *CurBECount << "\n"; 12521 dbgs() << "New: " << *NewBECount << "\n"; 12522 dbgs() << "Delta: " << *Delta << "\n"; 12523 std::abort(); 12524 } 12525 } 12526 12527 // Collect all valid loops currently in LoopInfo. 12528 SmallPtrSet<Loop *, 32> ValidLoops; 12529 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12530 while (!Worklist.empty()) { 12531 Loop *L = Worklist.pop_back_val(); 12532 if (ValidLoops.contains(L)) 12533 continue; 12534 ValidLoops.insert(L); 12535 Worklist.append(L->begin(), L->end()); 12536 } 12537 // Check for SCEV expressions referencing invalid/deleted loops. 12538 for (auto &KV : ValueExprMap) { 12539 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12540 if (!AR) 12541 continue; 12542 assert(ValidLoops.contains(AR->getLoop()) && 12543 "AddRec references invalid loop"); 12544 } 12545 } 12546 12547 bool ScalarEvolution::invalidate( 12548 Function &F, const PreservedAnalyses &PA, 12549 FunctionAnalysisManager::Invalidator &Inv) { 12550 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12551 // of its dependencies is invalidated. 12552 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12553 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12554 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12555 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12556 Inv.invalidate<LoopAnalysis>(F, PA); 12557 } 12558 12559 AnalysisKey ScalarEvolutionAnalysis::Key; 12560 12561 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12562 FunctionAnalysisManager &AM) { 12563 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12564 AM.getResult<AssumptionAnalysis>(F), 12565 AM.getResult<DominatorTreeAnalysis>(F), 12566 AM.getResult<LoopAnalysis>(F)); 12567 } 12568 12569 PreservedAnalyses 12570 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12571 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12572 return PreservedAnalyses::all(); 12573 } 12574 12575 PreservedAnalyses 12576 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12577 // For compatibility with opt's -analyze feature under legacy pass manager 12578 // which was not ported to NPM. This keeps tests using 12579 // update_analyze_test_checks.py working. 12580 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12581 << F.getName() << "':\n"; 12582 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12583 return PreservedAnalyses::all(); 12584 } 12585 12586 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12587 "Scalar Evolution Analysis", false, true) 12588 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12589 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12590 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12591 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12592 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12593 "Scalar Evolution Analysis", false, true) 12594 12595 char ScalarEvolutionWrapperPass::ID = 0; 12596 12597 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12598 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12599 } 12600 12601 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12602 SE.reset(new ScalarEvolution( 12603 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12604 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12605 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12606 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12607 return false; 12608 } 12609 12610 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12611 12612 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12613 SE->print(OS); 12614 } 12615 12616 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12617 if (!VerifySCEV) 12618 return; 12619 12620 SE->verify(); 12621 } 12622 12623 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12624 AU.setPreservesAll(); 12625 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12626 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12627 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12628 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12629 } 12630 12631 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12632 const SCEV *RHS) { 12633 FoldingSetNodeID ID; 12634 assert(LHS->getType() == RHS->getType() && 12635 "Type mismatch between LHS and RHS"); 12636 // Unique this node based on the arguments 12637 ID.AddInteger(SCEVPredicate::P_Equal); 12638 ID.AddPointer(LHS); 12639 ID.AddPointer(RHS); 12640 void *IP = nullptr; 12641 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12642 return S; 12643 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12644 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12645 UniquePreds.InsertNode(Eq, IP); 12646 return Eq; 12647 } 12648 12649 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12650 const SCEVAddRecExpr *AR, 12651 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12652 FoldingSetNodeID ID; 12653 // Unique this node based on the arguments 12654 ID.AddInteger(SCEVPredicate::P_Wrap); 12655 ID.AddPointer(AR); 12656 ID.AddInteger(AddedFlags); 12657 void *IP = nullptr; 12658 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12659 return S; 12660 auto *OF = new (SCEVAllocator) 12661 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12662 UniquePreds.InsertNode(OF, IP); 12663 return OF; 12664 } 12665 12666 namespace { 12667 12668 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12669 public: 12670 12671 /// Rewrites \p S in the context of a loop L and the SCEV predication 12672 /// infrastructure. 12673 /// 12674 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12675 /// equivalences present in \p Pred. 12676 /// 12677 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12678 /// \p NewPreds such that the result will be an AddRecExpr. 12679 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12680 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12681 SCEVUnionPredicate *Pred) { 12682 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12683 return Rewriter.visit(S); 12684 } 12685 12686 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12687 if (Pred) { 12688 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12689 for (auto *Pred : ExprPreds) 12690 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12691 if (IPred->getLHS() == Expr) 12692 return IPred->getRHS(); 12693 } 12694 return convertToAddRecWithPreds(Expr); 12695 } 12696 12697 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12698 const SCEV *Operand = visit(Expr->getOperand()); 12699 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12700 if (AR && AR->getLoop() == L && AR->isAffine()) { 12701 // This couldn't be folded because the operand didn't have the nuw 12702 // flag. Add the nusw flag as an assumption that we could make. 12703 const SCEV *Step = AR->getStepRecurrence(SE); 12704 Type *Ty = Expr->getType(); 12705 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12706 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12707 SE.getSignExtendExpr(Step, Ty), L, 12708 AR->getNoWrapFlags()); 12709 } 12710 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12711 } 12712 12713 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12714 const SCEV *Operand = visit(Expr->getOperand()); 12715 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12716 if (AR && AR->getLoop() == L && AR->isAffine()) { 12717 // This couldn't be folded because the operand didn't have the nsw 12718 // flag. Add the nssw flag as an assumption that we could make. 12719 const SCEV *Step = AR->getStepRecurrence(SE); 12720 Type *Ty = Expr->getType(); 12721 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12722 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12723 SE.getSignExtendExpr(Step, Ty), L, 12724 AR->getNoWrapFlags()); 12725 } 12726 return SE.getSignExtendExpr(Operand, Expr->getType()); 12727 } 12728 12729 private: 12730 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12731 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12732 SCEVUnionPredicate *Pred) 12733 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12734 12735 bool addOverflowAssumption(const SCEVPredicate *P) { 12736 if (!NewPreds) { 12737 // Check if we've already made this assumption. 12738 return Pred && Pred->implies(P); 12739 } 12740 NewPreds->insert(P); 12741 return true; 12742 } 12743 12744 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12745 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12746 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12747 return addOverflowAssumption(A); 12748 } 12749 12750 // If \p Expr represents a PHINode, we try to see if it can be represented 12751 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12752 // to add this predicate as a runtime overflow check, we return the AddRec. 12753 // If \p Expr does not meet these conditions (is not a PHI node, or we 12754 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12755 // return \p Expr. 12756 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12757 if (!isa<PHINode>(Expr->getValue())) 12758 return Expr; 12759 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12760 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12761 if (!PredicatedRewrite) 12762 return Expr; 12763 for (auto *P : PredicatedRewrite->second){ 12764 // Wrap predicates from outer loops are not supported. 12765 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12766 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12767 if (L != AR->getLoop()) 12768 return Expr; 12769 } 12770 if (!addOverflowAssumption(P)) 12771 return Expr; 12772 } 12773 return PredicatedRewrite->first; 12774 } 12775 12776 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12777 SCEVUnionPredicate *Pred; 12778 const Loop *L; 12779 }; 12780 12781 } // end anonymous namespace 12782 12783 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12784 SCEVUnionPredicate &Preds) { 12785 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12786 } 12787 12788 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12789 const SCEV *S, const Loop *L, 12790 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12791 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12792 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12793 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12794 12795 if (!AddRec) 12796 return nullptr; 12797 12798 // Since the transformation was successful, we can now transfer the SCEV 12799 // predicates. 12800 for (auto *P : TransformPreds) 12801 Preds.insert(P); 12802 12803 return AddRec; 12804 } 12805 12806 /// SCEV predicates 12807 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12808 SCEVPredicateKind Kind) 12809 : FastID(ID), Kind(Kind) {} 12810 12811 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12812 const SCEV *LHS, const SCEV *RHS) 12813 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12814 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12815 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12816 } 12817 12818 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12819 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12820 12821 if (!Op) 12822 return false; 12823 12824 return Op->LHS == LHS && Op->RHS == RHS; 12825 } 12826 12827 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12828 12829 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12830 12831 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12832 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12833 } 12834 12835 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12836 const SCEVAddRecExpr *AR, 12837 IncrementWrapFlags Flags) 12838 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12839 12840 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12841 12842 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12843 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12844 12845 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12846 } 12847 12848 bool SCEVWrapPredicate::isAlwaysTrue() const { 12849 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12850 IncrementWrapFlags IFlags = Flags; 12851 12852 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12853 IFlags = clearFlags(IFlags, IncrementNSSW); 12854 12855 return IFlags == IncrementAnyWrap; 12856 } 12857 12858 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12859 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12860 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12861 OS << "<nusw>"; 12862 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12863 OS << "<nssw>"; 12864 OS << "\n"; 12865 } 12866 12867 SCEVWrapPredicate::IncrementWrapFlags 12868 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12869 ScalarEvolution &SE) { 12870 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12871 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12872 12873 // We can safely transfer the NSW flag as NSSW. 12874 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12875 ImpliedFlags = IncrementNSSW; 12876 12877 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12878 // If the increment is positive, the SCEV NUW flag will also imply the 12879 // WrapPredicate NUSW flag. 12880 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12881 if (Step->getValue()->getValue().isNonNegative()) 12882 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12883 } 12884 12885 return ImpliedFlags; 12886 } 12887 12888 /// Union predicates don't get cached so create a dummy set ID for it. 12889 SCEVUnionPredicate::SCEVUnionPredicate() 12890 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12891 12892 bool SCEVUnionPredicate::isAlwaysTrue() const { 12893 return all_of(Preds, 12894 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12895 } 12896 12897 ArrayRef<const SCEVPredicate *> 12898 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12899 auto I = SCEVToPreds.find(Expr); 12900 if (I == SCEVToPreds.end()) 12901 return ArrayRef<const SCEVPredicate *>(); 12902 return I->second; 12903 } 12904 12905 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12906 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12907 return all_of(Set->Preds, 12908 [this](const SCEVPredicate *I) { return this->implies(I); }); 12909 12910 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12911 if (ScevPredsIt == SCEVToPreds.end()) 12912 return false; 12913 auto &SCEVPreds = ScevPredsIt->second; 12914 12915 return any_of(SCEVPreds, 12916 [N](const SCEVPredicate *I) { return I->implies(N); }); 12917 } 12918 12919 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12920 12921 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12922 for (auto Pred : Preds) 12923 Pred->print(OS, Depth); 12924 } 12925 12926 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12927 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12928 for (auto Pred : Set->Preds) 12929 add(Pred); 12930 return; 12931 } 12932 12933 if (implies(N)) 12934 return; 12935 12936 const SCEV *Key = N->getExpr(); 12937 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12938 " associated expression!"); 12939 12940 SCEVToPreds[Key].push_back(N); 12941 Preds.push_back(N); 12942 } 12943 12944 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12945 Loop &L) 12946 : SE(SE), L(L) {} 12947 12948 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12949 const SCEV *Expr = SE.getSCEV(V); 12950 RewriteEntry &Entry = RewriteMap[Expr]; 12951 12952 // If we already have an entry and the version matches, return it. 12953 if (Entry.second && Generation == Entry.first) 12954 return Entry.second; 12955 12956 // We found an entry but it's stale. Rewrite the stale entry 12957 // according to the current predicate. 12958 if (Entry.second) 12959 Expr = Entry.second; 12960 12961 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12962 Entry = {Generation, NewSCEV}; 12963 12964 return NewSCEV; 12965 } 12966 12967 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12968 if (!BackedgeCount) { 12969 SCEVUnionPredicate BackedgePred; 12970 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12971 addPredicate(BackedgePred); 12972 } 12973 return BackedgeCount; 12974 } 12975 12976 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12977 if (Preds.implies(&Pred)) 12978 return; 12979 Preds.add(&Pred); 12980 updateGeneration(); 12981 } 12982 12983 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12984 return Preds; 12985 } 12986 12987 void PredicatedScalarEvolution::updateGeneration() { 12988 // If the generation number wrapped recompute everything. 12989 if (++Generation == 0) { 12990 for (auto &II : RewriteMap) { 12991 const SCEV *Rewritten = II.second.second; 12992 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12993 } 12994 } 12995 } 12996 12997 void PredicatedScalarEvolution::setNoOverflow( 12998 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12999 const SCEV *Expr = getSCEV(V); 13000 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13001 13002 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13003 13004 // Clear the statically implied flags. 13005 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13006 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13007 13008 auto II = FlagsMap.insert({V, Flags}); 13009 if (!II.second) 13010 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13011 } 13012 13013 bool PredicatedScalarEvolution::hasNoOverflow( 13014 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13015 const SCEV *Expr = getSCEV(V); 13016 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13017 13018 Flags = SCEVWrapPredicate::clearFlags( 13019 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13020 13021 auto II = FlagsMap.find(V); 13022 13023 if (II != FlagsMap.end()) 13024 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13025 13026 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13027 } 13028 13029 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13030 const SCEV *Expr = this->getSCEV(V); 13031 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13032 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13033 13034 if (!New) 13035 return nullptr; 13036 13037 for (auto *P : NewPreds) 13038 Preds.add(P); 13039 13040 updateGeneration(); 13041 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13042 return New; 13043 } 13044 13045 PredicatedScalarEvolution::PredicatedScalarEvolution( 13046 const PredicatedScalarEvolution &Init) 13047 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13048 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13049 for (auto I : Init.FlagsMap) 13050 FlagsMap.insert(I); 13051 } 13052 13053 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13054 // For each block. 13055 for (auto *BB : L.getBlocks()) 13056 for (auto &I : *BB) { 13057 if (!SE.isSCEVable(I.getType())) 13058 continue; 13059 13060 auto *Expr = SE.getSCEV(&I); 13061 auto II = RewriteMap.find(Expr); 13062 13063 if (II == RewriteMap.end()) 13064 continue; 13065 13066 // Don't print things that are not interesting. 13067 if (II->second.second == Expr) 13068 continue; 13069 13070 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13071 OS.indent(Depth + 2) << *Expr << "\n"; 13072 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13073 } 13074 } 13075 13076 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13077 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13078 // for URem with constant power-of-2 second operands. 13079 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13080 // 4, A / B becomes X / 8). 13081 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13082 const SCEV *&RHS) { 13083 // Try to match 'zext (trunc A to iB) to iY', which is used 13084 // for URem with constant power-of-2 second operands. Make sure the size of 13085 // the operand A matches the size of the whole expressions. 13086 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13087 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13088 LHS = Trunc->getOperand(); 13089 if (LHS->getType() != Expr->getType()) 13090 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13091 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13092 << getTypeSizeInBits(Trunc->getType())); 13093 return true; 13094 } 13095 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13096 if (Add == nullptr || Add->getNumOperands() != 2) 13097 return false; 13098 13099 const SCEV *A = Add->getOperand(1); 13100 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13101 13102 if (Mul == nullptr) 13103 return false; 13104 13105 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13106 // (SomeExpr + (-(SomeExpr / B) * B)). 13107 if (Expr == getURemExpr(A, B)) { 13108 LHS = A; 13109 RHS = B; 13110 return true; 13111 } 13112 return false; 13113 }; 13114 13115 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13116 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13117 return MatchURemWithDivisor(Mul->getOperand(1)) || 13118 MatchURemWithDivisor(Mul->getOperand(2)); 13119 13120 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13121 if (Mul->getNumOperands() == 2) 13122 return MatchURemWithDivisor(Mul->getOperand(1)) || 13123 MatchURemWithDivisor(Mul->getOperand(0)) || 13124 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13125 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13126 return false; 13127 } 13128 13129 const SCEV * 13130 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13131 SmallVector<BasicBlock*, 16> ExitingBlocks; 13132 L->getExitingBlocks(ExitingBlocks); 13133 13134 // Form an expression for the maximum exit count possible for this loop. We 13135 // merge the max and exact information to approximate a version of 13136 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13137 SmallVector<const SCEV*, 4> ExitCounts; 13138 for (BasicBlock *ExitingBB : ExitingBlocks) { 13139 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13140 if (isa<SCEVCouldNotCompute>(ExitCount)) 13141 ExitCount = getExitCount(L, ExitingBB, 13142 ScalarEvolution::ConstantMaximum); 13143 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13144 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13145 "We should only have known counts for exiting blocks that " 13146 "dominate latch!"); 13147 ExitCounts.push_back(ExitCount); 13148 } 13149 } 13150 if (ExitCounts.empty()) 13151 return getCouldNotCompute(); 13152 return getUMinFromMismatchedTypes(ExitCounts); 13153 } 13154 13155 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13156 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13157 /// we cannot guarantee that the replacement is loop invariant in the loop of 13158 /// the AddRec. 13159 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13160 ValueToSCEVMapTy ⤅ 13161 13162 public: 13163 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13164 : SCEVRewriteVisitor(SE), Map(M) {} 13165 13166 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13167 13168 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13169 auto I = Map.find(Expr->getValue()); 13170 if (I == Map.end()) 13171 return Expr; 13172 return I->second; 13173 } 13174 }; 13175 13176 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13177 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13178 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13179 if (!isa<SCEVUnknown>(LHS)) { 13180 std::swap(LHS, RHS); 13181 Predicate = CmpInst::getSwappedPredicate(Predicate); 13182 } 13183 13184 // For now, limit to conditions that provide information about unknown 13185 // expressions. 13186 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13187 if (!LHSUnknown) 13188 return; 13189 13190 // TODO: use information from more predicates. 13191 switch (Predicate) { 13192 case CmpInst::ICMP_ULT: { 13193 if (!containsAddRecurrence(RHS)) { 13194 const SCEV *Base = LHS; 13195 auto I = RewriteMap.find(LHSUnknown->getValue()); 13196 if (I != RewriteMap.end()) 13197 Base = I->second; 13198 13199 RewriteMap[LHSUnknown->getValue()] = 13200 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 13201 } 13202 break; 13203 } 13204 case CmpInst::ICMP_ULE: { 13205 if (!containsAddRecurrence(RHS)) { 13206 const SCEV *Base = LHS; 13207 auto I = RewriteMap.find(LHSUnknown->getValue()); 13208 if (I != RewriteMap.end()) 13209 Base = I->second; 13210 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 13211 } 13212 break; 13213 } 13214 case CmpInst::ICMP_EQ: 13215 if (isa<SCEVConstant>(RHS)) 13216 RewriteMap[LHSUnknown->getValue()] = RHS; 13217 break; 13218 case CmpInst::ICMP_NE: 13219 if (isa<SCEVConstant>(RHS) && 13220 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13221 RewriteMap[LHSUnknown->getValue()] = 13222 getUMaxExpr(LHS, getOne(RHS->getType())); 13223 break; 13224 default: 13225 break; 13226 } 13227 }; 13228 // Starting at the loop predecessor, climb up the predecessor chain, as long 13229 // as there are predecessors that can be found that have unique successors 13230 // leading to the original header. 13231 // TODO: share this logic with isLoopEntryGuardedByCond. 13232 ValueToSCEVMapTy RewriteMap; 13233 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13234 L->getLoopPredecessor(), L->getHeader()); 13235 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13236 13237 const BranchInst *LoopEntryPredicate = 13238 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13239 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13240 continue; 13241 13242 // TODO: use information from more complex conditions, e.g. AND expressions. 13243 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 13244 if (!Cmp) 13245 continue; 13246 13247 auto Predicate = Cmp->getPredicate(); 13248 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 13249 Predicate = CmpInst::getInversePredicate(Predicate); 13250 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13251 getSCEV(Cmp->getOperand(1)), RewriteMap); 13252 } 13253 13254 // Also collect information from assumptions dominating the loop. 13255 for (auto &AssumeVH : AC.assumptions()) { 13256 if (!AssumeVH) 13257 continue; 13258 auto *AssumeI = cast<CallInst>(AssumeVH); 13259 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13260 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13261 continue; 13262 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13263 getSCEV(Cmp->getOperand(1)), RewriteMap); 13264 } 13265 13266 if (RewriteMap.empty()) 13267 return Expr; 13268 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13269 return Rewriter.visit(Expr); 13270 } 13271