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 (!AR->hasNoUnsignedWrap()) { 1592 auto NewFlags = proveNoWrapViaInduction(AR); 1593 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1594 } 1595 1596 // If we have special knowledge that this addrec won't overflow, 1597 // we don't need to do any further analysis. 1598 if (AR->hasNoUnsignedWrap()) 1599 return getAddRecExpr( 1600 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1601 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1602 1603 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1604 // Note that this serves two purposes: It filters out loops that are 1605 // simply not analyzable, and it covers the case where this code is 1606 // being called from within backedge-taken count analysis, such that 1607 // attempting to ask for the backedge-taken count would likely result 1608 // in infinite recursion. In the later case, the analysis code will 1609 // cope with a conservative value, and it will take care to purge 1610 // that value once it has finished. 1611 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1612 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1613 // Manually compute the final value for AR, checking for 1614 // overflow. 1615 1616 // Check whether the backedge-taken count can be losslessly casted to 1617 // the addrec's type. The count is always unsigned. 1618 const SCEV *CastedMaxBECount = 1619 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1620 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1621 CastedMaxBECount, MaxBECount->getType(), Depth); 1622 if (MaxBECount == RecastedMaxBECount) { 1623 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1624 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1625 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1626 SCEV::FlagAnyWrap, Depth + 1); 1627 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1628 SCEV::FlagAnyWrap, 1629 Depth + 1), 1630 WideTy, Depth + 1); 1631 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1632 const SCEV *WideMaxBECount = 1633 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1634 const SCEV *OperandExtendedAdd = 1635 getAddExpr(WideStart, 1636 getMulExpr(WideMaxBECount, 1637 getZeroExtendExpr(Step, WideTy, Depth + 1), 1638 SCEV::FlagAnyWrap, Depth + 1), 1639 SCEV::FlagAnyWrap, Depth + 1); 1640 if (ZAdd == OperandExtendedAdd) { 1641 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1642 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1643 // Return the expression with the addrec on the outside. 1644 return getAddRecExpr( 1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1646 Depth + 1), 1647 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1648 AR->getNoWrapFlags()); 1649 } 1650 // Similar to above, only this time treat the step value as signed. 1651 // This covers loops that count down. 1652 OperandExtendedAdd = 1653 getAddExpr(WideStart, 1654 getMulExpr(WideMaxBECount, 1655 getSignExtendExpr(Step, WideTy, Depth + 1), 1656 SCEV::FlagAnyWrap, Depth + 1), 1657 SCEV::FlagAnyWrap, Depth + 1); 1658 if (ZAdd == OperandExtendedAdd) { 1659 // Cache knowledge of AR NW, which is propagated to this AddRec. 1660 // Negative step causes unsigned wrap, but it still can't self-wrap. 1661 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1662 // Return the expression with the addrec on the outside. 1663 return getAddRecExpr( 1664 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1665 Depth + 1), 1666 getSignExtendExpr(Step, Ty, Depth + 1), L, 1667 AR->getNoWrapFlags()); 1668 } 1669 } 1670 } 1671 1672 // Normally, in the cases we can prove no-overflow via a 1673 // backedge guarding condition, we can also compute a backedge 1674 // taken count for the loop. The exceptions are assumptions and 1675 // guards present in the loop -- SCEV is not great at exploiting 1676 // these to compute max backedge taken counts, but can still use 1677 // these to prove lack of overflow. Use this fact to avoid 1678 // doing extra work that may not pay off. 1679 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1680 !AC.assumptions().empty()) { 1681 // For a negative step, we can extend the operands iff doing so only 1682 // traverses values in the range zext([0,UINT_MAX]). 1683 if (isKnownNegative(Step)) { 1684 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1685 getSignedRangeMin(Step)); 1686 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1687 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1688 // Note: We've proven NW here, but that's already done above too. 1689 // Return the expression with the addrec on the outside. 1690 return getAddRecExpr( 1691 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1692 Depth + 1), 1693 getSignExtendExpr(Step, Ty, Depth + 1), L, 1694 AR->getNoWrapFlags()); 1695 } 1696 } 1697 } 1698 1699 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1700 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1701 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1702 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1703 const APInt &C = SC->getAPInt(); 1704 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1705 if (D != 0) { 1706 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1707 const SCEV *SResidual = 1708 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1709 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1710 return getAddExpr(SZExtD, SZExtR, 1711 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1712 Depth + 1); 1713 } 1714 } 1715 1716 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1717 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1718 return getAddRecExpr( 1719 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1720 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1721 } 1722 } 1723 1724 // zext(A % B) --> zext(A) % zext(B) 1725 { 1726 const SCEV *LHS; 1727 const SCEV *RHS; 1728 if (matchURem(Op, LHS, RHS)) 1729 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1730 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1731 } 1732 1733 // zext(A / B) --> zext(A) / zext(B). 1734 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1735 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1736 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1737 1738 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1739 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1740 if (SA->hasNoUnsignedWrap()) { 1741 // If the addition does not unsign overflow then we can, by definition, 1742 // commute the zero extension with the addition operation. 1743 SmallVector<const SCEV *, 4> Ops; 1744 for (const auto *Op : SA->operands()) 1745 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1746 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1747 } 1748 1749 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1750 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1751 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1752 // 1753 // Often address arithmetics contain expressions like 1754 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1755 // This transformation is useful while proving that such expressions are 1756 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1757 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1758 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1759 if (D != 0) { 1760 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1761 const SCEV *SResidual = 1762 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1763 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1764 return getAddExpr(SZExtD, SZExtR, 1765 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1766 Depth + 1); 1767 } 1768 } 1769 } 1770 1771 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1772 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1773 if (SM->hasNoUnsignedWrap()) { 1774 // If the multiply does not unsign overflow then we can, by definition, 1775 // commute the zero extension with the multiply operation. 1776 SmallVector<const SCEV *, 4> Ops; 1777 for (const auto *Op : SM->operands()) 1778 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1779 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1780 } 1781 1782 // zext(2^K * (trunc X to iN)) to iM -> 1783 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1784 // 1785 // Proof: 1786 // 1787 // zext(2^K * (trunc X to iN)) to iM 1788 // = zext((trunc X to iN) << K) to iM 1789 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1790 // (because shl removes the top K bits) 1791 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1792 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1793 // 1794 if (SM->getNumOperands() == 2) 1795 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1796 if (MulLHS->getAPInt().isPowerOf2()) 1797 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1798 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1799 MulLHS->getAPInt().logBase2(); 1800 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1801 return getMulExpr( 1802 getZeroExtendExpr(MulLHS, Ty), 1803 getZeroExtendExpr( 1804 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1805 SCEV::FlagNUW, Depth + 1); 1806 } 1807 } 1808 1809 // The cast wasn't folded; create an explicit cast node. 1810 // Recompute the insert position, as it may have been invalidated. 1811 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1812 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1813 Op, Ty); 1814 UniqueSCEVs.InsertNode(S, IP); 1815 addToLoopUseLists(S); 1816 return S; 1817 } 1818 1819 const SCEV * 1820 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1821 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1822 "This is not an extending conversion!"); 1823 assert(isSCEVable(Ty) && 1824 "This is not a conversion to a SCEVable type!"); 1825 Ty = getEffectiveSCEVType(Ty); 1826 1827 // Fold if the operand is constant. 1828 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1829 return getConstant( 1830 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1831 1832 // sext(sext(x)) --> sext(x) 1833 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1834 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1835 1836 // sext(zext(x)) --> zext(x) 1837 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1838 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1839 1840 // Before doing any expensive analysis, check to see if we've already 1841 // computed a SCEV for this Op and Ty. 1842 FoldingSetNodeID ID; 1843 ID.AddInteger(scSignExtend); 1844 ID.AddPointer(Op); 1845 ID.AddPointer(Ty); 1846 void *IP = nullptr; 1847 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1848 // Limit recursion depth. 1849 if (Depth > MaxCastDepth) { 1850 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1851 Op, Ty); 1852 UniqueSCEVs.InsertNode(S, IP); 1853 addToLoopUseLists(S); 1854 return S; 1855 } 1856 1857 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1858 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1859 // It's possible the bits taken off by the truncate were all sign bits. If 1860 // so, we should be able to simplify this further. 1861 const SCEV *X = ST->getOperand(); 1862 ConstantRange CR = getSignedRange(X); 1863 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1864 unsigned NewBits = getTypeSizeInBits(Ty); 1865 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1866 CR.sextOrTrunc(NewBits))) 1867 return getTruncateOrSignExtend(X, Ty, Depth); 1868 } 1869 1870 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1871 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1872 if (SA->hasNoSignedWrap()) { 1873 // If the addition does not sign overflow then we can, by definition, 1874 // commute the sign extension with the addition operation. 1875 SmallVector<const SCEV *, 4> Ops; 1876 for (const auto *Op : SA->operands()) 1877 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1878 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1879 } 1880 1881 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1882 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1883 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1884 // 1885 // For instance, this will bring two seemingly different expressions: 1886 // 1 + sext(5 + 20 * %x + 24 * %y) and 1887 // sext(6 + 20 * %x + 24 * %y) 1888 // to the same form: 1889 // 2 + sext(4 + 20 * %x + 24 * %y) 1890 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1891 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1892 if (D != 0) { 1893 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1894 const SCEV *SResidual = 1895 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1896 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1897 return getAddExpr(SSExtD, SSExtR, 1898 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1899 Depth + 1); 1900 } 1901 } 1902 } 1903 // If the input value is a chrec scev, and we can prove that the value 1904 // did not overflow the old, smaller, value, we can sign extend all of the 1905 // operands (often constants). This allows analysis of something like 1906 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1907 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1908 if (AR->isAffine()) { 1909 const SCEV *Start = AR->getStart(); 1910 const SCEV *Step = AR->getStepRecurrence(*this); 1911 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1912 const Loop *L = AR->getLoop(); 1913 1914 if (!AR->hasNoSignedWrap()) { 1915 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1916 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1917 } 1918 1919 if (!AR->hasNoSignedWrap()) { 1920 auto NewFlags = proveNoWrapViaInduction(AR); 1921 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1922 } 1923 1924 // If we have special knowledge that this addrec won't overflow, 1925 // we don't need to do any further analysis. 1926 if (AR->hasNoSignedWrap()) 1927 return getAddRecExpr( 1928 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1929 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1930 1931 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1932 // Note that this serves two purposes: It filters out loops that are 1933 // simply not analyzable, and it covers the case where this code is 1934 // being called from within backedge-taken count analysis, such that 1935 // attempting to ask for the backedge-taken count would likely result 1936 // in infinite recursion. In the later case, the analysis code will 1937 // cope with a conservative value, and it will take care to purge 1938 // that value once it has finished. 1939 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1940 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1941 // Manually compute the final value for AR, checking for 1942 // overflow. 1943 1944 // Check whether the backedge-taken count can be losslessly casted to 1945 // the addrec's type. The count is always unsigned. 1946 const SCEV *CastedMaxBECount = 1947 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1948 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1949 CastedMaxBECount, MaxBECount->getType(), Depth); 1950 if (MaxBECount == RecastedMaxBECount) { 1951 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1952 // Check whether Start+Step*MaxBECount has no signed overflow. 1953 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1954 SCEV::FlagAnyWrap, Depth + 1); 1955 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1956 SCEV::FlagAnyWrap, 1957 Depth + 1), 1958 WideTy, Depth + 1); 1959 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1960 const SCEV *WideMaxBECount = 1961 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1962 const SCEV *OperandExtendedAdd = 1963 getAddExpr(WideStart, 1964 getMulExpr(WideMaxBECount, 1965 getSignExtendExpr(Step, WideTy, Depth + 1), 1966 SCEV::FlagAnyWrap, Depth + 1), 1967 SCEV::FlagAnyWrap, Depth + 1); 1968 if (SAdd == OperandExtendedAdd) { 1969 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1970 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 1971 // Return the expression with the addrec on the outside. 1972 return getAddRecExpr( 1973 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1974 Depth + 1), 1975 getSignExtendExpr(Step, Ty, Depth + 1), L, 1976 AR->getNoWrapFlags()); 1977 } 1978 // Similar to above, only this time treat the step value as unsigned. 1979 // This covers loops that count up with an unsigned step. 1980 OperandExtendedAdd = 1981 getAddExpr(WideStart, 1982 getMulExpr(WideMaxBECount, 1983 getZeroExtendExpr(Step, WideTy, Depth + 1), 1984 SCEV::FlagAnyWrap, Depth + 1), 1985 SCEV::FlagAnyWrap, Depth + 1); 1986 if (SAdd == OperandExtendedAdd) { 1987 // If AR wraps around then 1988 // 1989 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1990 // => SAdd != OperandExtendedAdd 1991 // 1992 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1993 // (SAdd == OperandExtendedAdd => AR is NW) 1994 1995 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1996 1997 // Return the expression with the addrec on the outside. 1998 return getAddRecExpr( 1999 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2000 Depth + 1), 2001 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2002 AR->getNoWrapFlags()); 2003 } 2004 } 2005 } 2006 2007 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2008 // if D + (C - D + Step * n) could be proven to not signed wrap 2009 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2010 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2011 const APInt &C = SC->getAPInt(); 2012 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2013 if (D != 0) { 2014 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2015 const SCEV *SResidual = 2016 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2017 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2018 return getAddExpr(SSExtD, SSExtR, 2019 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2020 Depth + 1); 2021 } 2022 } 2023 2024 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2025 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2026 return getAddRecExpr( 2027 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2028 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2029 } 2030 } 2031 2032 // If the input value is provably positive and we could not simplify 2033 // away the sext build a zext instead. 2034 if (isKnownNonNegative(Op)) 2035 return getZeroExtendExpr(Op, Ty, Depth + 1); 2036 2037 // The cast wasn't folded; create an explicit cast node. 2038 // Recompute the insert position, as it may have been invalidated. 2039 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2040 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2041 Op, Ty); 2042 UniqueSCEVs.InsertNode(S, IP); 2043 addToLoopUseLists(S); 2044 return S; 2045 } 2046 2047 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2048 /// unspecified bits out to the given type. 2049 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2050 Type *Ty) { 2051 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2052 "This is not an extending conversion!"); 2053 assert(isSCEVable(Ty) && 2054 "This is not a conversion to a SCEVable type!"); 2055 Ty = getEffectiveSCEVType(Ty); 2056 2057 // Sign-extend negative constants. 2058 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2059 if (SC->getAPInt().isNegative()) 2060 return getSignExtendExpr(Op, Ty); 2061 2062 // Peel off a truncate cast. 2063 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2064 const SCEV *NewOp = T->getOperand(); 2065 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2066 return getAnyExtendExpr(NewOp, Ty); 2067 return getTruncateOrNoop(NewOp, Ty); 2068 } 2069 2070 // Next try a zext cast. If the cast is folded, use it. 2071 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2072 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2073 return ZExt; 2074 2075 // Next try a sext cast. If the cast is folded, use it. 2076 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2077 if (!isa<SCEVSignExtendExpr>(SExt)) 2078 return SExt; 2079 2080 // Force the cast to be folded into the operands of an addrec. 2081 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2082 SmallVector<const SCEV *, 4> Ops; 2083 for (const SCEV *Op : AR->operands()) 2084 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2085 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2086 } 2087 2088 // If the expression is obviously signed, use the sext cast value. 2089 if (isa<SCEVSMaxExpr>(Op)) 2090 return SExt; 2091 2092 // Absent any other information, use the zext cast value. 2093 return ZExt; 2094 } 2095 2096 /// Process the given Ops list, which is a list of operands to be added under 2097 /// the given scale, update the given map. This is a helper function for 2098 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2099 /// that would form an add expression like this: 2100 /// 2101 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2102 /// 2103 /// where A and B are constants, update the map with these values: 2104 /// 2105 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2106 /// 2107 /// and add 13 + A*B*29 to AccumulatedConstant. 2108 /// This will allow getAddRecExpr to produce this: 2109 /// 2110 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2111 /// 2112 /// This form often exposes folding opportunities that are hidden in 2113 /// the original operand list. 2114 /// 2115 /// Return true iff it appears that any interesting folding opportunities 2116 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2117 /// the common case where no interesting opportunities are present, and 2118 /// is also used as a check to avoid infinite recursion. 2119 static bool 2120 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2121 SmallVectorImpl<const SCEV *> &NewOps, 2122 APInt &AccumulatedConstant, 2123 const SCEV *const *Ops, size_t NumOperands, 2124 const APInt &Scale, 2125 ScalarEvolution &SE) { 2126 bool Interesting = false; 2127 2128 // Iterate over the add operands. They are sorted, with constants first. 2129 unsigned i = 0; 2130 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2131 ++i; 2132 // Pull a buried constant out to the outside. 2133 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2134 Interesting = true; 2135 AccumulatedConstant += Scale * C->getAPInt(); 2136 } 2137 2138 // Next comes everything else. We're especially interested in multiplies 2139 // here, but they're in the middle, so just visit the rest with one loop. 2140 for (; i != NumOperands; ++i) { 2141 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2142 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2143 APInt NewScale = 2144 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2145 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2146 // A multiplication of a constant with another add; recurse. 2147 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2148 Interesting |= 2149 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2150 Add->op_begin(), Add->getNumOperands(), 2151 NewScale, SE); 2152 } else { 2153 // A multiplication of a constant with some other value. Update 2154 // the map. 2155 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2156 const SCEV *Key = SE.getMulExpr(MulOps); 2157 auto Pair = M.insert({Key, NewScale}); 2158 if (Pair.second) { 2159 NewOps.push_back(Pair.first->first); 2160 } else { 2161 Pair.first->second += NewScale; 2162 // The map already had an entry for this value, which may indicate 2163 // a folding opportunity. 2164 Interesting = true; 2165 } 2166 } 2167 } else { 2168 // An ordinary operand. Update the map. 2169 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2170 M.insert({Ops[i], Scale}); 2171 if (Pair.second) { 2172 NewOps.push_back(Pair.first->first); 2173 } else { 2174 Pair.first->second += Scale; 2175 // The map already had an entry for this value, which may indicate 2176 // a folding opportunity. 2177 Interesting = true; 2178 } 2179 } 2180 } 2181 2182 return Interesting; 2183 } 2184 2185 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2186 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2187 // can't-overflow flags for the operation if possible. 2188 static SCEV::NoWrapFlags 2189 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2190 const ArrayRef<const SCEV *> Ops, 2191 SCEV::NoWrapFlags Flags) { 2192 using namespace std::placeholders; 2193 2194 using OBO = OverflowingBinaryOperator; 2195 2196 bool CanAnalyze = 2197 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2198 (void)CanAnalyze; 2199 assert(CanAnalyze && "don't call from other places!"); 2200 2201 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2202 SCEV::NoWrapFlags SignOrUnsignWrap = 2203 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2204 2205 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2206 auto IsKnownNonNegative = [&](const SCEV *S) { 2207 return SE->isKnownNonNegative(S); 2208 }; 2209 2210 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2211 Flags = 2212 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2213 2214 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2215 2216 if (SignOrUnsignWrap != SignOrUnsignMask && 2217 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2218 isa<SCEVConstant>(Ops[0])) { 2219 2220 auto Opcode = [&] { 2221 switch (Type) { 2222 case scAddExpr: 2223 return Instruction::Add; 2224 case scMulExpr: 2225 return Instruction::Mul; 2226 default: 2227 llvm_unreachable("Unexpected SCEV op."); 2228 } 2229 }(); 2230 2231 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2232 2233 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2234 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2235 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2236 Opcode, C, OBO::NoSignedWrap); 2237 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2238 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2239 } 2240 2241 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2242 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2243 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2244 Opcode, C, OBO::NoUnsignedWrap); 2245 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2246 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2247 } 2248 } 2249 2250 return Flags; 2251 } 2252 2253 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2254 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2255 } 2256 2257 /// Get a canonical add expression, or something simpler if possible. 2258 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2259 SCEV::NoWrapFlags OrigFlags, 2260 unsigned Depth) { 2261 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2262 "only nuw or nsw allowed"); 2263 assert(!Ops.empty() && "Cannot get empty add!"); 2264 if (Ops.size() == 1) return Ops[0]; 2265 #ifndef NDEBUG 2266 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2267 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2268 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2269 "SCEVAddExpr operand types don't match!"); 2270 #endif 2271 2272 // Sort by complexity, this groups all similar expression types together. 2273 GroupByComplexity(Ops, &LI, DT); 2274 2275 // If there are any constants, fold them together. 2276 unsigned Idx = 0; 2277 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2278 ++Idx; 2279 assert(Idx < Ops.size()); 2280 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2281 // We found two constants, fold them together! 2282 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2283 if (Ops.size() == 2) return Ops[0]; 2284 Ops.erase(Ops.begin()+1); // Erase the folded element 2285 LHSC = cast<SCEVConstant>(Ops[0]); 2286 } 2287 2288 // If we are left with a constant zero being added, strip it off. 2289 if (LHSC->getValue()->isZero()) { 2290 Ops.erase(Ops.begin()); 2291 --Idx; 2292 } 2293 2294 if (Ops.size() == 1) return Ops[0]; 2295 } 2296 2297 // Delay expensive flag strengthening until necessary. 2298 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2299 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2300 }; 2301 2302 // Limit recursion calls depth. 2303 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2304 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2305 2306 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2307 // Don't strengthen flags if we have no new information. 2308 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2309 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2310 Add->setNoWrapFlags(ComputeFlags(Ops)); 2311 return S; 2312 } 2313 2314 // Okay, check to see if the same value occurs in the operand list more than 2315 // once. If so, merge them together into an multiply expression. Since we 2316 // sorted the list, these values are required to be adjacent. 2317 Type *Ty = Ops[0]->getType(); 2318 bool FoundMatch = false; 2319 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2320 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2321 // Scan ahead to count how many equal operands there are. 2322 unsigned Count = 2; 2323 while (i+Count != e && Ops[i+Count] == Ops[i]) 2324 ++Count; 2325 // Merge the values into a multiply. 2326 const SCEV *Scale = getConstant(Ty, Count); 2327 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2328 if (Ops.size() == Count) 2329 return Mul; 2330 Ops[i] = Mul; 2331 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2332 --i; e -= Count - 1; 2333 FoundMatch = true; 2334 } 2335 if (FoundMatch) 2336 return getAddExpr(Ops, OrigFlags, Depth + 1); 2337 2338 // Check for truncates. If all the operands are truncated from the same 2339 // type, see if factoring out the truncate would permit the result to be 2340 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2341 // if the contents of the resulting outer trunc fold to something simple. 2342 auto FindTruncSrcType = [&]() -> Type * { 2343 // We're ultimately looking to fold an addrec of truncs and muls of only 2344 // constants and truncs, so if we find any other types of SCEV 2345 // as operands of the addrec then we bail and return nullptr here. 2346 // Otherwise, we return the type of the operand of a trunc that we find. 2347 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2348 return T->getOperand()->getType(); 2349 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2350 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2351 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2352 return T->getOperand()->getType(); 2353 } 2354 return nullptr; 2355 }; 2356 if (auto *SrcType = FindTruncSrcType()) { 2357 SmallVector<const SCEV *, 8> LargeOps; 2358 bool Ok = true; 2359 // Check all the operands to see if they can be represented in the 2360 // source type of the truncate. 2361 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2362 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2363 if (T->getOperand()->getType() != SrcType) { 2364 Ok = false; 2365 break; 2366 } 2367 LargeOps.push_back(T->getOperand()); 2368 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2369 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2370 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2371 SmallVector<const SCEV *, 8> LargeMulOps; 2372 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2373 if (const SCEVTruncateExpr *T = 2374 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2375 if (T->getOperand()->getType() != SrcType) { 2376 Ok = false; 2377 break; 2378 } 2379 LargeMulOps.push_back(T->getOperand()); 2380 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2381 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2382 } else { 2383 Ok = false; 2384 break; 2385 } 2386 } 2387 if (Ok) 2388 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2389 } else { 2390 Ok = false; 2391 break; 2392 } 2393 } 2394 if (Ok) { 2395 // Evaluate the expression in the larger type. 2396 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2397 // If it folds to something simple, use it. Otherwise, don't. 2398 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2399 return getTruncateExpr(Fold, Ty); 2400 } 2401 } 2402 2403 // Skip past any other cast SCEVs. 2404 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2405 ++Idx; 2406 2407 // If there are add operands they would be next. 2408 if (Idx < Ops.size()) { 2409 bool DeletedAdd = false; 2410 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2411 if (Ops.size() > AddOpsInlineThreshold || 2412 Add->getNumOperands() > AddOpsInlineThreshold) 2413 break; 2414 // If we have an add, expand the add operands onto the end of the operands 2415 // list. 2416 Ops.erase(Ops.begin()+Idx); 2417 Ops.append(Add->op_begin(), Add->op_end()); 2418 DeletedAdd = true; 2419 } 2420 2421 // If we deleted at least one add, we added operands to the end of the list, 2422 // and they are not necessarily sorted. Recurse to resort and resimplify 2423 // any operands we just acquired. 2424 if (DeletedAdd) 2425 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2426 } 2427 2428 // Skip over the add expression until we get to a multiply. 2429 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2430 ++Idx; 2431 2432 // Check to see if there are any folding opportunities present with 2433 // operands multiplied by constant values. 2434 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2435 uint64_t BitWidth = getTypeSizeInBits(Ty); 2436 DenseMap<const SCEV *, APInt> M; 2437 SmallVector<const SCEV *, 8> NewOps; 2438 APInt AccumulatedConstant(BitWidth, 0); 2439 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2440 Ops.data(), Ops.size(), 2441 APInt(BitWidth, 1), *this)) { 2442 struct APIntCompare { 2443 bool operator()(const APInt &LHS, const APInt &RHS) const { 2444 return LHS.ult(RHS); 2445 } 2446 }; 2447 2448 // Some interesting folding opportunity is present, so its worthwhile to 2449 // re-generate the operands list. Group the operands by constant scale, 2450 // to avoid multiplying by the same constant scale multiple times. 2451 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2452 for (const SCEV *NewOp : NewOps) 2453 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2454 // Re-generate the operands list. 2455 Ops.clear(); 2456 if (AccumulatedConstant != 0) 2457 Ops.push_back(getConstant(AccumulatedConstant)); 2458 for (auto &MulOp : MulOpLists) 2459 if (MulOp.first != 0) 2460 Ops.push_back(getMulExpr( 2461 getConstant(MulOp.first), 2462 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2463 SCEV::FlagAnyWrap, Depth + 1)); 2464 if (Ops.empty()) 2465 return getZero(Ty); 2466 if (Ops.size() == 1) 2467 return Ops[0]; 2468 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2469 } 2470 } 2471 2472 // If we are adding something to a multiply expression, make sure the 2473 // something is not already an operand of the multiply. If so, merge it into 2474 // the multiply. 2475 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2476 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2477 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2478 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2479 if (isa<SCEVConstant>(MulOpSCEV)) 2480 continue; 2481 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2482 if (MulOpSCEV == Ops[AddOp]) { 2483 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2484 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2485 if (Mul->getNumOperands() != 2) { 2486 // If the multiply has more than two operands, we must get the 2487 // Y*Z term. 2488 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2489 Mul->op_begin()+MulOp); 2490 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2491 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2492 } 2493 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2494 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2495 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2496 SCEV::FlagAnyWrap, Depth + 1); 2497 if (Ops.size() == 2) return OuterMul; 2498 if (AddOp < Idx) { 2499 Ops.erase(Ops.begin()+AddOp); 2500 Ops.erase(Ops.begin()+Idx-1); 2501 } else { 2502 Ops.erase(Ops.begin()+Idx); 2503 Ops.erase(Ops.begin()+AddOp-1); 2504 } 2505 Ops.push_back(OuterMul); 2506 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2507 } 2508 2509 // Check this multiply against other multiplies being added together. 2510 for (unsigned OtherMulIdx = Idx+1; 2511 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2512 ++OtherMulIdx) { 2513 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2514 // If MulOp occurs in OtherMul, we can fold the two multiplies 2515 // together. 2516 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2517 OMulOp != e; ++OMulOp) 2518 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2519 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2520 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2521 if (Mul->getNumOperands() != 2) { 2522 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2523 Mul->op_begin()+MulOp); 2524 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2525 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2526 } 2527 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2528 if (OtherMul->getNumOperands() != 2) { 2529 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2530 OtherMul->op_begin()+OMulOp); 2531 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2532 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2533 } 2534 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2535 const SCEV *InnerMulSum = 2536 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2537 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2538 SCEV::FlagAnyWrap, Depth + 1); 2539 if (Ops.size() == 2) return OuterMul; 2540 Ops.erase(Ops.begin()+Idx); 2541 Ops.erase(Ops.begin()+OtherMulIdx-1); 2542 Ops.push_back(OuterMul); 2543 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2544 } 2545 } 2546 } 2547 } 2548 2549 // If there are any add recurrences in the operands list, see if any other 2550 // added values are loop invariant. If so, we can fold them into the 2551 // recurrence. 2552 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2553 ++Idx; 2554 2555 // Scan over all recurrences, trying to fold loop invariants into them. 2556 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2557 // Scan all of the other operands to this add and add them to the vector if 2558 // they are loop invariant w.r.t. the recurrence. 2559 SmallVector<const SCEV *, 8> LIOps; 2560 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2561 const Loop *AddRecLoop = AddRec->getLoop(); 2562 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2563 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2564 LIOps.push_back(Ops[i]); 2565 Ops.erase(Ops.begin()+i); 2566 --i; --e; 2567 } 2568 2569 // If we found some loop invariants, fold them into the recurrence. 2570 if (!LIOps.empty()) { 2571 // Compute nowrap flags for the addition of the loop-invariant ops and 2572 // the addrec. Temporarily push it as an operand for that purpose. 2573 LIOps.push_back(AddRec); 2574 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2575 LIOps.pop_back(); 2576 2577 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2578 LIOps.push_back(AddRec->getStart()); 2579 2580 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2581 AddRec->op_end()); 2582 // This follows from the fact that the no-wrap flags on the outer add 2583 // expression are applicable on the 0th iteration, when the add recurrence 2584 // will be equal to its start value. 2585 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2586 2587 // Build the new addrec. Propagate the NUW and NSW flags if both the 2588 // outer add and the inner addrec are guaranteed to have no overflow. 2589 // Always propagate NW. 2590 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2591 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2592 2593 // If all of the other operands were loop invariant, we are done. 2594 if (Ops.size() == 1) return NewRec; 2595 2596 // Otherwise, add the folded AddRec by the non-invariant parts. 2597 for (unsigned i = 0;; ++i) 2598 if (Ops[i] == AddRec) { 2599 Ops[i] = NewRec; 2600 break; 2601 } 2602 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2603 } 2604 2605 // Okay, if there weren't any loop invariants to be folded, check to see if 2606 // there are multiple AddRec's with the same loop induction variable being 2607 // added together. If so, we can fold them. 2608 for (unsigned OtherIdx = Idx+1; 2609 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2610 ++OtherIdx) { 2611 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2612 // so that the 1st found AddRecExpr is dominated by all others. 2613 assert(DT.dominates( 2614 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2615 AddRec->getLoop()->getHeader()) && 2616 "AddRecExprs are not sorted in reverse dominance order?"); 2617 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2618 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2619 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2620 AddRec->op_end()); 2621 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2622 ++OtherIdx) { 2623 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2624 if (OtherAddRec->getLoop() == AddRecLoop) { 2625 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2626 i != e; ++i) { 2627 if (i >= AddRecOps.size()) { 2628 AddRecOps.append(OtherAddRec->op_begin()+i, 2629 OtherAddRec->op_end()); 2630 break; 2631 } 2632 SmallVector<const SCEV *, 2> TwoOps = { 2633 AddRecOps[i], OtherAddRec->getOperand(i)}; 2634 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2635 } 2636 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2637 } 2638 } 2639 // Step size has changed, so we cannot guarantee no self-wraparound. 2640 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2641 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2642 } 2643 } 2644 2645 // Otherwise couldn't fold anything into this recurrence. Move onto the 2646 // next one. 2647 } 2648 2649 // Okay, it looks like we really DO need an add expr. Check to see if we 2650 // already have one, otherwise create a new one. 2651 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2652 } 2653 2654 const SCEV * 2655 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2656 SCEV::NoWrapFlags Flags) { 2657 FoldingSetNodeID ID; 2658 ID.AddInteger(scAddExpr); 2659 for (const SCEV *Op : Ops) 2660 ID.AddPointer(Op); 2661 void *IP = nullptr; 2662 SCEVAddExpr *S = 2663 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2664 if (!S) { 2665 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2666 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2667 S = new (SCEVAllocator) 2668 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2669 UniqueSCEVs.InsertNode(S, IP); 2670 addToLoopUseLists(S); 2671 } 2672 S->setNoWrapFlags(Flags); 2673 return S; 2674 } 2675 2676 const SCEV * 2677 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2678 const Loop *L, SCEV::NoWrapFlags Flags) { 2679 FoldingSetNodeID ID; 2680 ID.AddInteger(scAddRecExpr); 2681 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2682 ID.AddPointer(Ops[i]); 2683 ID.AddPointer(L); 2684 void *IP = nullptr; 2685 SCEVAddRecExpr *S = 2686 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2687 if (!S) { 2688 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2689 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2690 S = new (SCEVAllocator) 2691 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2692 UniqueSCEVs.InsertNode(S, IP); 2693 addToLoopUseLists(S); 2694 } 2695 setNoWrapFlags(S, Flags); 2696 return S; 2697 } 2698 2699 const SCEV * 2700 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2701 SCEV::NoWrapFlags Flags) { 2702 FoldingSetNodeID ID; 2703 ID.AddInteger(scMulExpr); 2704 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2705 ID.AddPointer(Ops[i]); 2706 void *IP = nullptr; 2707 SCEVMulExpr *S = 2708 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2709 if (!S) { 2710 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2711 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2712 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2713 O, Ops.size()); 2714 UniqueSCEVs.InsertNode(S, IP); 2715 addToLoopUseLists(S); 2716 } 2717 S->setNoWrapFlags(Flags); 2718 return S; 2719 } 2720 2721 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2722 uint64_t k = i*j; 2723 if (j > 1 && k / j != i) Overflow = true; 2724 return k; 2725 } 2726 2727 /// Compute the result of "n choose k", the binomial coefficient. If an 2728 /// intermediate computation overflows, Overflow will be set and the return will 2729 /// be garbage. Overflow is not cleared on absence of overflow. 2730 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2731 // We use the multiplicative formula: 2732 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2733 // At each iteration, we take the n-th term of the numeral and divide by the 2734 // (k-n)th term of the denominator. This division will always produce an 2735 // integral result, and helps reduce the chance of overflow in the 2736 // intermediate computations. However, we can still overflow even when the 2737 // final result would fit. 2738 2739 if (n == 0 || n == k) return 1; 2740 if (k > n) return 0; 2741 2742 if (k > n/2) 2743 k = n-k; 2744 2745 uint64_t r = 1; 2746 for (uint64_t i = 1; i <= k; ++i) { 2747 r = umul_ov(r, n-(i-1), Overflow); 2748 r /= i; 2749 } 2750 return r; 2751 } 2752 2753 /// Determine if any of the operands in this SCEV are a constant or if 2754 /// any of the add or multiply expressions in this SCEV contain a constant. 2755 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2756 struct FindConstantInAddMulChain { 2757 bool FoundConstant = false; 2758 2759 bool follow(const SCEV *S) { 2760 FoundConstant |= isa<SCEVConstant>(S); 2761 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2762 } 2763 2764 bool isDone() const { 2765 return FoundConstant; 2766 } 2767 }; 2768 2769 FindConstantInAddMulChain F; 2770 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2771 ST.visitAll(StartExpr); 2772 return F.FoundConstant; 2773 } 2774 2775 /// Get a canonical multiply expression, or something simpler if possible. 2776 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2777 SCEV::NoWrapFlags OrigFlags, 2778 unsigned Depth) { 2779 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2780 "only nuw or nsw allowed"); 2781 assert(!Ops.empty() && "Cannot get empty mul!"); 2782 if (Ops.size() == 1) return Ops[0]; 2783 #ifndef NDEBUG 2784 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2785 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2786 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2787 "SCEVMulExpr operand types don't match!"); 2788 #endif 2789 2790 // Sort by complexity, this groups all similar expression types together. 2791 GroupByComplexity(Ops, &LI, DT); 2792 2793 // If there are any constants, fold them together. 2794 unsigned Idx = 0; 2795 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2796 ++Idx; 2797 assert(Idx < Ops.size()); 2798 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2799 // We found two constants, fold them together! 2800 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2801 if (Ops.size() == 2) return Ops[0]; 2802 Ops.erase(Ops.begin()+1); // Erase the folded element 2803 LHSC = cast<SCEVConstant>(Ops[0]); 2804 } 2805 2806 // If we have a multiply of zero, it will always be zero. 2807 if (LHSC->getValue()->isZero()) 2808 return LHSC; 2809 2810 // If we are left with a constant one being multiplied, strip it off. 2811 if (LHSC->getValue()->isOne()) { 2812 Ops.erase(Ops.begin()); 2813 --Idx; 2814 } 2815 2816 if (Ops.size() == 1) 2817 return Ops[0]; 2818 } 2819 2820 // Delay expensive flag strengthening until necessary. 2821 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2822 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2823 }; 2824 2825 // Limit recursion calls depth. 2826 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2827 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2828 2829 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2830 // Don't strengthen flags if we have no new information. 2831 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2832 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2833 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2834 return S; 2835 } 2836 2837 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2838 if (Ops.size() == 2) { 2839 // C1*(C2+V) -> C1*C2 + C1*V 2840 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2841 // If any of Add's ops are Adds or Muls with a constant, apply this 2842 // transformation as well. 2843 // 2844 // TODO: There are some cases where this transformation is not 2845 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2846 // this transformation should be narrowed down. 2847 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2848 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2849 SCEV::FlagAnyWrap, Depth + 1), 2850 getMulExpr(LHSC, Add->getOperand(1), 2851 SCEV::FlagAnyWrap, Depth + 1), 2852 SCEV::FlagAnyWrap, Depth + 1); 2853 2854 if (Ops[0]->isAllOnesValue()) { 2855 // If we have a mul by -1 of an add, try distributing the -1 among the 2856 // add operands. 2857 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2858 SmallVector<const SCEV *, 4> NewOps; 2859 bool AnyFolded = false; 2860 for (const SCEV *AddOp : Add->operands()) { 2861 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2862 Depth + 1); 2863 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2864 NewOps.push_back(Mul); 2865 } 2866 if (AnyFolded) 2867 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2868 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2869 // Negation preserves a recurrence's no self-wrap property. 2870 SmallVector<const SCEV *, 4> Operands; 2871 for (const SCEV *AddRecOp : AddRec->operands()) 2872 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2873 Depth + 1)); 2874 2875 return getAddRecExpr(Operands, AddRec->getLoop(), 2876 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2877 } 2878 } 2879 } 2880 } 2881 2882 // Skip over the add expression until we get to a multiply. 2883 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2884 ++Idx; 2885 2886 // If there are mul operands inline them all into this expression. 2887 if (Idx < Ops.size()) { 2888 bool DeletedMul = false; 2889 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2890 if (Ops.size() > MulOpsInlineThreshold) 2891 break; 2892 // If we have an mul, expand the mul operands onto the end of the 2893 // operands list. 2894 Ops.erase(Ops.begin()+Idx); 2895 Ops.append(Mul->op_begin(), Mul->op_end()); 2896 DeletedMul = true; 2897 } 2898 2899 // If we deleted at least one mul, we added operands to the end of the 2900 // list, and they are not necessarily sorted. Recurse to resort and 2901 // resimplify any operands we just acquired. 2902 if (DeletedMul) 2903 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2904 } 2905 2906 // If there are any add recurrences in the operands list, see if any other 2907 // added values are loop invariant. If so, we can fold them into the 2908 // recurrence. 2909 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2910 ++Idx; 2911 2912 // Scan over all recurrences, trying to fold loop invariants into them. 2913 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2914 // Scan all of the other operands to this mul and add them to the vector 2915 // if they are loop invariant w.r.t. the recurrence. 2916 SmallVector<const SCEV *, 8> LIOps; 2917 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2918 const Loop *AddRecLoop = AddRec->getLoop(); 2919 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2920 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2921 LIOps.push_back(Ops[i]); 2922 Ops.erase(Ops.begin()+i); 2923 --i; --e; 2924 } 2925 2926 // If we found some loop invariants, fold them into the recurrence. 2927 if (!LIOps.empty()) { 2928 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2929 SmallVector<const SCEV *, 4> NewOps; 2930 NewOps.reserve(AddRec->getNumOperands()); 2931 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2932 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2933 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2934 SCEV::FlagAnyWrap, Depth + 1)); 2935 2936 // Build the new addrec. Propagate the NUW and NSW flags if both the 2937 // outer mul and the inner addrec are guaranteed to have no overflow. 2938 // 2939 // No self-wrap cannot be guaranteed after changing the step size, but 2940 // will be inferred if either NUW or NSW is true. 2941 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 2942 const SCEV *NewRec = getAddRecExpr( 2943 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 2944 2945 // If all of the other operands were loop invariant, we are done. 2946 if (Ops.size() == 1) return NewRec; 2947 2948 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2949 for (unsigned i = 0;; ++i) 2950 if (Ops[i] == AddRec) { 2951 Ops[i] = NewRec; 2952 break; 2953 } 2954 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2955 } 2956 2957 // Okay, if there weren't any loop invariants to be folded, check to see 2958 // if there are multiple AddRec's with the same loop induction variable 2959 // being multiplied together. If so, we can fold them. 2960 2961 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2962 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2963 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2964 // ]]],+,...up to x=2n}. 2965 // Note that the arguments to choose() are always integers with values 2966 // known at compile time, never SCEV objects. 2967 // 2968 // The implementation avoids pointless extra computations when the two 2969 // addrec's are of different length (mathematically, it's equivalent to 2970 // an infinite stream of zeros on the right). 2971 bool OpsModified = false; 2972 for (unsigned OtherIdx = Idx+1; 2973 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2974 ++OtherIdx) { 2975 const SCEVAddRecExpr *OtherAddRec = 2976 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2977 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2978 continue; 2979 2980 // Limit max number of arguments to avoid creation of unreasonably big 2981 // SCEVAddRecs with very complex operands. 2982 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2983 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 2984 continue; 2985 2986 bool Overflow = false; 2987 Type *Ty = AddRec->getType(); 2988 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2989 SmallVector<const SCEV*, 7> AddRecOps; 2990 for (int x = 0, xe = AddRec->getNumOperands() + 2991 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2992 SmallVector <const SCEV *, 7> SumOps; 2993 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2994 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2995 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2996 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2997 z < ze && !Overflow; ++z) { 2998 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2999 uint64_t Coeff; 3000 if (LargerThan64Bits) 3001 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3002 else 3003 Coeff = Coeff1*Coeff2; 3004 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3005 const SCEV *Term1 = AddRec->getOperand(y-z); 3006 const SCEV *Term2 = OtherAddRec->getOperand(z); 3007 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3008 SCEV::FlagAnyWrap, Depth + 1)); 3009 } 3010 } 3011 if (SumOps.empty()) 3012 SumOps.push_back(getZero(Ty)); 3013 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3014 } 3015 if (!Overflow) { 3016 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3017 SCEV::FlagAnyWrap); 3018 if (Ops.size() == 2) return NewAddRec; 3019 Ops[Idx] = NewAddRec; 3020 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3021 OpsModified = true; 3022 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3023 if (!AddRec) 3024 break; 3025 } 3026 } 3027 if (OpsModified) 3028 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3029 3030 // Otherwise couldn't fold anything into this recurrence. Move onto the 3031 // next one. 3032 } 3033 3034 // Okay, it looks like we really DO need an mul expr. Check to see if we 3035 // already have one, otherwise create a new one. 3036 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3037 } 3038 3039 /// Represents an unsigned remainder expression based on unsigned division. 3040 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3041 const SCEV *RHS) { 3042 assert(getEffectiveSCEVType(LHS->getType()) == 3043 getEffectiveSCEVType(RHS->getType()) && 3044 "SCEVURemExpr operand types don't match!"); 3045 3046 // Short-circuit easy cases 3047 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3048 // If constant is one, the result is trivial 3049 if (RHSC->getValue()->isOne()) 3050 return getZero(LHS->getType()); // X urem 1 --> 0 3051 3052 // If constant is a power of two, fold into a zext(trunc(LHS)). 3053 if (RHSC->getAPInt().isPowerOf2()) { 3054 Type *FullTy = LHS->getType(); 3055 Type *TruncTy = 3056 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3057 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3058 } 3059 } 3060 3061 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3062 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3063 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3064 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3065 } 3066 3067 /// Get a canonical unsigned division expression, or something simpler if 3068 /// possible. 3069 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3070 const SCEV *RHS) { 3071 assert(getEffectiveSCEVType(LHS->getType()) == 3072 getEffectiveSCEVType(RHS->getType()) && 3073 "SCEVUDivExpr operand types don't match!"); 3074 3075 FoldingSetNodeID ID; 3076 ID.AddInteger(scUDivExpr); 3077 ID.AddPointer(LHS); 3078 ID.AddPointer(RHS); 3079 void *IP = nullptr; 3080 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3081 return S; 3082 3083 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3084 if (RHSC->getValue()->isOne()) 3085 return LHS; // X udiv 1 --> x 3086 // If the denominator is zero, the result of the udiv is undefined. Don't 3087 // try to analyze it, because the resolution chosen here may differ from 3088 // the resolution chosen in other parts of the compiler. 3089 if (!RHSC->getValue()->isZero()) { 3090 // Determine if the division can be folded into the operands of 3091 // its operands. 3092 // TODO: Generalize this to non-constants by using known-bits information. 3093 Type *Ty = LHS->getType(); 3094 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3095 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3096 // For non-power-of-two values, effectively round the value up to the 3097 // nearest power of two. 3098 if (!RHSC->getAPInt().isPowerOf2()) 3099 ++MaxShiftAmt; 3100 IntegerType *ExtTy = 3101 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3102 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3103 if (const SCEVConstant *Step = 3104 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3105 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3106 const APInt &StepInt = Step->getAPInt(); 3107 const APInt &DivInt = RHSC->getAPInt(); 3108 if (!StepInt.urem(DivInt) && 3109 getZeroExtendExpr(AR, ExtTy) == 3110 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3111 getZeroExtendExpr(Step, ExtTy), 3112 AR->getLoop(), SCEV::FlagAnyWrap)) { 3113 SmallVector<const SCEV *, 4> Operands; 3114 for (const SCEV *Op : AR->operands()) 3115 Operands.push_back(getUDivExpr(Op, RHS)); 3116 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3117 } 3118 /// Get a canonical UDivExpr for a recurrence. 3119 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3120 // We can currently only fold X%N if X is constant. 3121 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3122 if (StartC && !DivInt.urem(StepInt) && 3123 getZeroExtendExpr(AR, ExtTy) == 3124 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3125 getZeroExtendExpr(Step, ExtTy), 3126 AR->getLoop(), SCEV::FlagAnyWrap)) { 3127 const APInt &StartInt = StartC->getAPInt(); 3128 const APInt &StartRem = StartInt.urem(StepInt); 3129 if (StartRem != 0) { 3130 const SCEV *NewLHS = 3131 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3132 AR->getLoop(), SCEV::FlagNW); 3133 if (LHS != NewLHS) { 3134 LHS = NewLHS; 3135 3136 // Reset the ID to include the new LHS, and check if it is 3137 // already cached. 3138 ID.clear(); 3139 ID.AddInteger(scUDivExpr); 3140 ID.AddPointer(LHS); 3141 ID.AddPointer(RHS); 3142 IP = nullptr; 3143 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3144 return S; 3145 } 3146 } 3147 } 3148 } 3149 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3150 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3151 SmallVector<const SCEV *, 4> Operands; 3152 for (const SCEV *Op : M->operands()) 3153 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3154 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3155 // Find an operand that's safely divisible. 3156 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3157 const SCEV *Op = M->getOperand(i); 3158 const SCEV *Div = getUDivExpr(Op, RHSC); 3159 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3160 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3161 M->op_end()); 3162 Operands[i] = Div; 3163 return getMulExpr(Operands); 3164 } 3165 } 3166 } 3167 3168 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3169 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3170 if (auto *DivisorConstant = 3171 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3172 bool Overflow = false; 3173 APInt NewRHS = 3174 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3175 if (Overflow) { 3176 return getConstant(RHSC->getType(), 0, false); 3177 } 3178 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3179 } 3180 } 3181 3182 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3183 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3184 SmallVector<const SCEV *, 4> Operands; 3185 for (const SCEV *Op : A->operands()) 3186 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3187 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3188 Operands.clear(); 3189 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3190 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3191 if (isa<SCEVUDivExpr>(Op) || 3192 getMulExpr(Op, RHS) != A->getOperand(i)) 3193 break; 3194 Operands.push_back(Op); 3195 } 3196 if (Operands.size() == A->getNumOperands()) 3197 return getAddExpr(Operands); 3198 } 3199 } 3200 3201 // Fold if both operands are constant. 3202 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3203 Constant *LHSCV = LHSC->getValue(); 3204 Constant *RHSCV = RHSC->getValue(); 3205 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3206 RHSCV))); 3207 } 3208 } 3209 } 3210 3211 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3212 // changes). Make sure we get a new one. 3213 IP = nullptr; 3214 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3215 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3216 LHS, RHS); 3217 UniqueSCEVs.InsertNode(S, IP); 3218 addToLoopUseLists(S); 3219 return S; 3220 } 3221 3222 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3223 APInt A = C1->getAPInt().abs(); 3224 APInt B = C2->getAPInt().abs(); 3225 uint32_t ABW = A.getBitWidth(); 3226 uint32_t BBW = B.getBitWidth(); 3227 3228 if (ABW > BBW) 3229 B = B.zext(ABW); 3230 else if (ABW < BBW) 3231 A = A.zext(BBW); 3232 3233 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3234 } 3235 3236 /// Get a canonical unsigned division expression, or something simpler if 3237 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3238 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3239 /// it's not exact because the udiv may be clearing bits. 3240 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3241 const SCEV *RHS) { 3242 // TODO: we could try to find factors in all sorts of things, but for now we 3243 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3244 // end of this file for inspiration. 3245 3246 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3247 if (!Mul || !Mul->hasNoUnsignedWrap()) 3248 return getUDivExpr(LHS, RHS); 3249 3250 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3251 // If the mulexpr multiplies by a constant, then that constant must be the 3252 // first element of the mulexpr. 3253 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3254 if (LHSCst == RHSCst) { 3255 SmallVector<const SCEV *, 2> Operands; 3256 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3257 return getMulExpr(Operands); 3258 } 3259 3260 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3261 // that there's a factor provided by one of the other terms. We need to 3262 // check. 3263 APInt Factor = gcd(LHSCst, RHSCst); 3264 if (!Factor.isIntN(1)) { 3265 LHSCst = 3266 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3267 RHSCst = 3268 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3269 SmallVector<const SCEV *, 2> Operands; 3270 Operands.push_back(LHSCst); 3271 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3272 LHS = getMulExpr(Operands); 3273 RHS = RHSCst; 3274 Mul = dyn_cast<SCEVMulExpr>(LHS); 3275 if (!Mul) 3276 return getUDivExactExpr(LHS, RHS); 3277 } 3278 } 3279 } 3280 3281 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3282 if (Mul->getOperand(i) == RHS) { 3283 SmallVector<const SCEV *, 2> Operands; 3284 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3285 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3286 return getMulExpr(Operands); 3287 } 3288 } 3289 3290 return getUDivExpr(LHS, RHS); 3291 } 3292 3293 /// Get an add recurrence expression for the specified loop. Simplify the 3294 /// expression as much as possible. 3295 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3296 const Loop *L, 3297 SCEV::NoWrapFlags Flags) { 3298 SmallVector<const SCEV *, 4> Operands; 3299 Operands.push_back(Start); 3300 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3301 if (StepChrec->getLoop() == L) { 3302 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3303 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3304 } 3305 3306 Operands.push_back(Step); 3307 return getAddRecExpr(Operands, L, Flags); 3308 } 3309 3310 /// Get an add recurrence expression for the specified loop. Simplify the 3311 /// expression as much as possible. 3312 const SCEV * 3313 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3314 const Loop *L, SCEV::NoWrapFlags Flags) { 3315 if (Operands.size() == 1) return Operands[0]; 3316 #ifndef NDEBUG 3317 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3318 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3319 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3320 "SCEVAddRecExpr operand types don't match!"); 3321 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3322 assert(isLoopInvariant(Operands[i], L) && 3323 "SCEVAddRecExpr operand is not loop-invariant!"); 3324 #endif 3325 3326 if (Operands.back()->isZero()) { 3327 Operands.pop_back(); 3328 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3329 } 3330 3331 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3332 // use that information to infer NUW and NSW flags. However, computing a 3333 // BE count requires calling getAddRecExpr, so we may not yet have a 3334 // meaningful BE count at this point (and if we don't, we'd be stuck 3335 // with a SCEVCouldNotCompute as the cached BE count). 3336 3337 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3338 3339 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3340 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3341 const Loop *NestedLoop = NestedAR->getLoop(); 3342 if (L->contains(NestedLoop) 3343 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3344 : (!NestedLoop->contains(L) && 3345 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3346 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3347 NestedAR->op_end()); 3348 Operands[0] = NestedAR->getStart(); 3349 // AddRecs require their operands be loop-invariant with respect to their 3350 // loops. Don't perform this transformation if it would break this 3351 // requirement. 3352 bool AllInvariant = all_of( 3353 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3354 3355 if (AllInvariant) { 3356 // Create a recurrence for the outer loop with the same step size. 3357 // 3358 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3359 // inner recurrence has the same property. 3360 SCEV::NoWrapFlags OuterFlags = 3361 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3362 3363 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3364 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3365 return isLoopInvariant(Op, NestedLoop); 3366 }); 3367 3368 if (AllInvariant) { 3369 // Ok, both add recurrences are valid after the transformation. 3370 // 3371 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3372 // the outer recurrence has the same property. 3373 SCEV::NoWrapFlags InnerFlags = 3374 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3375 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3376 } 3377 } 3378 // Reset Operands to its original state. 3379 Operands[0] = NestedAR; 3380 } 3381 } 3382 3383 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3384 // already have one, otherwise create a new one. 3385 return getOrCreateAddRecExpr(Operands, L, Flags); 3386 } 3387 3388 const SCEV * 3389 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3390 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3391 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3392 // getSCEV(Base)->getType() has the same address space as Base->getType() 3393 // because SCEV::getType() preserves the address space. 3394 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3395 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3396 // instruction to its SCEV, because the Instruction may be guarded by control 3397 // flow and the no-overflow bits may not be valid for the expression in any 3398 // context. This can be fixed similarly to how these flags are handled for 3399 // adds. 3400 SCEV::NoWrapFlags OffsetWrap = 3401 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3402 3403 Type *CurTy = GEP->getType(); 3404 bool FirstIter = true; 3405 SmallVector<const SCEV *, 4> Offsets; 3406 for (const SCEV *IndexExpr : IndexExprs) { 3407 // Compute the (potentially symbolic) offset in bytes for this index. 3408 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3409 // For a struct, add the member offset. 3410 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3411 unsigned FieldNo = Index->getZExtValue(); 3412 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3413 Offsets.push_back(FieldOffset); 3414 3415 // Update CurTy to the type of the field at Index. 3416 CurTy = STy->getTypeAtIndex(Index); 3417 } else { 3418 // Update CurTy to its element type. 3419 if (FirstIter) { 3420 assert(isa<PointerType>(CurTy) && 3421 "The first index of a GEP indexes a pointer"); 3422 CurTy = GEP->getSourceElementType(); 3423 FirstIter = false; 3424 } else { 3425 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3426 } 3427 // For an array, add the element offset, explicitly scaled. 3428 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3429 // Getelementptr indices are signed. 3430 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3431 3432 // Multiply the index by the element size to compute the element offset. 3433 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3434 Offsets.push_back(LocalOffset); 3435 } 3436 } 3437 3438 // Handle degenerate case of GEP without offsets. 3439 if (Offsets.empty()) 3440 return BaseExpr; 3441 3442 // Add the offsets together, assuming nsw if inbounds. 3443 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3444 // Add the base address and the offset. We cannot use the nsw flag, as the 3445 // base address is unsigned. However, if we know that the offset is 3446 // non-negative, we can use nuw. 3447 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3448 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3449 return getAddExpr(BaseExpr, Offset, BaseWrap); 3450 } 3451 3452 std::tuple<SCEV *, FoldingSetNodeID, void *> 3453 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3454 ArrayRef<const SCEV *> Ops) { 3455 FoldingSetNodeID ID; 3456 void *IP = nullptr; 3457 ID.AddInteger(SCEVType); 3458 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3459 ID.AddPointer(Ops[i]); 3460 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3461 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3462 } 3463 3464 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3465 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3466 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3467 } 3468 3469 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3470 Type *Ty = Op->getType(); 3471 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3472 } 3473 3474 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3475 SmallVectorImpl<const SCEV *> &Ops) { 3476 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3477 if (Ops.size() == 1) return Ops[0]; 3478 #ifndef NDEBUG 3479 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3480 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3481 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3482 "Operand types don't match!"); 3483 #endif 3484 3485 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3486 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3487 3488 // Sort by complexity, this groups all similar expression types together. 3489 GroupByComplexity(Ops, &LI, DT); 3490 3491 // Check if we have created the same expression before. 3492 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3493 return S; 3494 } 3495 3496 // If there are any constants, fold them together. 3497 unsigned Idx = 0; 3498 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3499 ++Idx; 3500 assert(Idx < Ops.size()); 3501 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3502 if (Kind == scSMaxExpr) 3503 return APIntOps::smax(LHS, RHS); 3504 else if (Kind == scSMinExpr) 3505 return APIntOps::smin(LHS, RHS); 3506 else if (Kind == scUMaxExpr) 3507 return APIntOps::umax(LHS, RHS); 3508 else if (Kind == scUMinExpr) 3509 return APIntOps::umin(LHS, RHS); 3510 llvm_unreachable("Unknown SCEV min/max opcode"); 3511 }; 3512 3513 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3514 // We found two constants, fold them together! 3515 ConstantInt *Fold = ConstantInt::get( 3516 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3517 Ops[0] = getConstant(Fold); 3518 Ops.erase(Ops.begin()+1); // Erase the folded element 3519 if (Ops.size() == 1) return Ops[0]; 3520 LHSC = cast<SCEVConstant>(Ops[0]); 3521 } 3522 3523 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3524 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3525 3526 if (IsMax ? IsMinV : IsMaxV) { 3527 // If we are left with a constant minimum(/maximum)-int, strip it off. 3528 Ops.erase(Ops.begin()); 3529 --Idx; 3530 } else if (IsMax ? IsMaxV : IsMinV) { 3531 // If we have a max(/min) with a constant maximum(/minimum)-int, 3532 // it will always be the extremum. 3533 return LHSC; 3534 } 3535 3536 if (Ops.size() == 1) return Ops[0]; 3537 } 3538 3539 // Find the first operation of the same kind 3540 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3541 ++Idx; 3542 3543 // Check to see if one of the operands is of the same kind. If so, expand its 3544 // operands onto our operand list, and recurse to simplify. 3545 if (Idx < Ops.size()) { 3546 bool DeletedAny = false; 3547 while (Ops[Idx]->getSCEVType() == Kind) { 3548 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3549 Ops.erase(Ops.begin()+Idx); 3550 Ops.append(SMME->op_begin(), SMME->op_end()); 3551 DeletedAny = true; 3552 } 3553 3554 if (DeletedAny) 3555 return getMinMaxExpr(Kind, Ops); 3556 } 3557 3558 // Okay, check to see if the same value occurs in the operand list twice. If 3559 // so, delete one. Since we sorted the list, these values are required to 3560 // be adjacent. 3561 llvm::CmpInst::Predicate GEPred = 3562 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3563 llvm::CmpInst::Predicate LEPred = 3564 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3565 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3566 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3567 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3568 if (Ops[i] == Ops[i + 1] || 3569 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3570 // X op Y op Y --> X op Y 3571 // X op Y --> X, if we know X, Y are ordered appropriately 3572 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3573 --i; 3574 --e; 3575 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3576 Ops[i + 1])) { 3577 // X op Y --> Y, if we know X, Y are ordered appropriately 3578 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3579 --i; 3580 --e; 3581 } 3582 } 3583 3584 if (Ops.size() == 1) return Ops[0]; 3585 3586 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3587 3588 // Okay, it looks like we really DO need an expr. Check to see if we 3589 // already have one, otherwise create a new one. 3590 const SCEV *ExistingSCEV; 3591 FoldingSetNodeID ID; 3592 void *IP; 3593 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3594 if (ExistingSCEV) 3595 return ExistingSCEV; 3596 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3597 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3598 SCEV *S = new (SCEVAllocator) 3599 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3600 3601 UniqueSCEVs.InsertNode(S, IP); 3602 addToLoopUseLists(S); 3603 return S; 3604 } 3605 3606 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3607 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3608 return getSMaxExpr(Ops); 3609 } 3610 3611 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3612 return getMinMaxExpr(scSMaxExpr, Ops); 3613 } 3614 3615 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3616 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3617 return getUMaxExpr(Ops); 3618 } 3619 3620 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3621 return getMinMaxExpr(scUMaxExpr, Ops); 3622 } 3623 3624 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3625 const SCEV *RHS) { 3626 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3627 return getSMinExpr(Ops); 3628 } 3629 3630 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3631 return getMinMaxExpr(scSMinExpr, Ops); 3632 } 3633 3634 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3635 const SCEV *RHS) { 3636 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3637 return getUMinExpr(Ops); 3638 } 3639 3640 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3641 return getMinMaxExpr(scUMinExpr, Ops); 3642 } 3643 3644 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3645 if (isa<ScalableVectorType>(AllocTy)) { 3646 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3647 Constant *One = ConstantInt::get(IntTy, 1); 3648 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3649 // Note that the expression we created is the final expression, we don't 3650 // want to simplify it any further Also, if we call a normal getSCEV(), 3651 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3652 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3653 } 3654 // We can bypass creating a target-independent 3655 // constant expression and then folding it back into a ConstantInt. 3656 // This is just a compile-time optimization. 3657 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3658 } 3659 3660 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3661 StructType *STy, 3662 unsigned FieldNo) { 3663 // We can bypass creating a target-independent 3664 // constant expression and then folding it back into a ConstantInt. 3665 // This is just a compile-time optimization. 3666 return getConstant( 3667 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3668 } 3669 3670 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3671 // Don't attempt to do anything other than create a SCEVUnknown object 3672 // here. createSCEV only calls getUnknown after checking for all other 3673 // interesting possibilities, and any other code that calls getUnknown 3674 // is doing so in order to hide a value from SCEV canonicalization. 3675 3676 FoldingSetNodeID ID; 3677 ID.AddInteger(scUnknown); 3678 ID.AddPointer(V); 3679 void *IP = nullptr; 3680 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3681 assert(cast<SCEVUnknown>(S)->getValue() == V && 3682 "Stale SCEVUnknown in uniquing map!"); 3683 return S; 3684 } 3685 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3686 FirstUnknown); 3687 FirstUnknown = cast<SCEVUnknown>(S); 3688 UniqueSCEVs.InsertNode(S, IP); 3689 return S; 3690 } 3691 3692 //===----------------------------------------------------------------------===// 3693 // Basic SCEV Analysis and PHI Idiom Recognition Code 3694 // 3695 3696 /// Test if values of the given type are analyzable within the SCEV 3697 /// framework. This primarily includes integer types, and it can optionally 3698 /// include pointer types if the ScalarEvolution class has access to 3699 /// target-specific information. 3700 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3701 // Integers and pointers are always SCEVable. 3702 return Ty->isIntOrPtrTy(); 3703 } 3704 3705 /// Return the size in bits of the specified type, for which isSCEVable must 3706 /// return true. 3707 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3708 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3709 if (Ty->isPointerTy()) 3710 return getDataLayout().getIndexTypeSizeInBits(Ty); 3711 return getDataLayout().getTypeSizeInBits(Ty); 3712 } 3713 3714 /// Return a type with the same bitwidth as the given type and which represents 3715 /// how SCEV will treat the given type, for which isSCEVable must return 3716 /// true. For pointer types, this is the pointer index sized integer type. 3717 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3718 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3719 3720 if (Ty->isIntegerTy()) 3721 return Ty; 3722 3723 // The only other support type is pointer. 3724 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3725 return getDataLayout().getIndexType(Ty); 3726 } 3727 3728 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3729 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3730 } 3731 3732 const SCEV *ScalarEvolution::getCouldNotCompute() { 3733 return CouldNotCompute.get(); 3734 } 3735 3736 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3737 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3738 auto *SU = dyn_cast<SCEVUnknown>(S); 3739 return SU && SU->getValue() == nullptr; 3740 }); 3741 3742 return !ContainsNulls; 3743 } 3744 3745 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3746 HasRecMapType::iterator I = HasRecMap.find(S); 3747 if (I != HasRecMap.end()) 3748 return I->second; 3749 3750 bool FoundAddRec = 3751 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3752 HasRecMap.insert({S, FoundAddRec}); 3753 return FoundAddRec; 3754 } 3755 3756 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3757 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3758 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3759 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3760 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3761 if (!Add) 3762 return {S, nullptr}; 3763 3764 if (Add->getNumOperands() != 2) 3765 return {S, nullptr}; 3766 3767 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3768 if (!ConstOp) 3769 return {S, nullptr}; 3770 3771 return {Add->getOperand(1), ConstOp->getValue()}; 3772 } 3773 3774 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3775 /// by the value and offset from any ValueOffsetPair in the set. 3776 SetVector<ScalarEvolution::ValueOffsetPair> * 3777 ScalarEvolution::getSCEVValues(const SCEV *S) { 3778 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3779 if (SI == ExprValueMap.end()) 3780 return nullptr; 3781 #ifndef NDEBUG 3782 if (VerifySCEVMap) { 3783 // Check there is no dangling Value in the set returned. 3784 for (const auto &VE : SI->second) 3785 assert(ValueExprMap.count(VE.first)); 3786 } 3787 #endif 3788 return &SI->second; 3789 } 3790 3791 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3792 /// cannot be used separately. eraseValueFromMap should be used to remove 3793 /// V from ValueExprMap and ExprValueMap at the same time. 3794 void ScalarEvolution::eraseValueFromMap(Value *V) { 3795 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3796 if (I != ValueExprMap.end()) { 3797 const SCEV *S = I->second; 3798 // Remove {V, 0} from the set of ExprValueMap[S] 3799 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3800 SV->remove({V, nullptr}); 3801 3802 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3803 const SCEV *Stripped; 3804 ConstantInt *Offset; 3805 std::tie(Stripped, Offset) = splitAddExpr(S); 3806 if (Offset != nullptr) { 3807 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3808 SV->remove({V, Offset}); 3809 } 3810 ValueExprMap.erase(V); 3811 } 3812 } 3813 3814 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3815 /// TODO: In reality it is better to check the poison recursively 3816 /// but this is better than nothing. 3817 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3818 if (auto *I = dyn_cast<Instruction>(V)) { 3819 if (isa<OverflowingBinaryOperator>(I)) { 3820 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3821 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3822 return true; 3823 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3824 return true; 3825 } 3826 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3827 return true; 3828 } 3829 return false; 3830 } 3831 3832 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3833 /// create a new one. 3834 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3835 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3836 3837 const SCEV *S = getExistingSCEV(V); 3838 if (S == nullptr) { 3839 S = createSCEV(V); 3840 // During PHI resolution, it is possible to create two SCEVs for the same 3841 // V, so it is needed to double check whether V->S is inserted into 3842 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3843 std::pair<ValueExprMapType::iterator, bool> Pair = 3844 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3845 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3846 ExprValueMap[S].insert({V, nullptr}); 3847 3848 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3849 // ExprValueMap. 3850 const SCEV *Stripped = S; 3851 ConstantInt *Offset = nullptr; 3852 std::tie(Stripped, Offset) = splitAddExpr(S); 3853 // If stripped is SCEVUnknown, don't bother to save 3854 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3855 // increase the complexity of the expansion code. 3856 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3857 // because it may generate add/sub instead of GEP in SCEV expansion. 3858 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3859 !isa<GetElementPtrInst>(V)) 3860 ExprValueMap[Stripped].insert({V, Offset}); 3861 } 3862 } 3863 return S; 3864 } 3865 3866 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3867 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3868 3869 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3870 if (I != ValueExprMap.end()) { 3871 const SCEV *S = I->second; 3872 if (checkValidity(S)) 3873 return S; 3874 eraseValueFromMap(V); 3875 forgetMemoizedResults(S); 3876 } 3877 return nullptr; 3878 } 3879 3880 /// Return a SCEV corresponding to -V = -1*V 3881 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3882 SCEV::NoWrapFlags Flags) { 3883 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3884 return getConstant( 3885 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3886 3887 Type *Ty = V->getType(); 3888 Ty = getEffectiveSCEVType(Ty); 3889 return getMulExpr(V, getMinusOne(Ty), Flags); 3890 } 3891 3892 /// If Expr computes ~A, return A else return nullptr 3893 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3894 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3895 if (!Add || Add->getNumOperands() != 2 || 3896 !Add->getOperand(0)->isAllOnesValue()) 3897 return nullptr; 3898 3899 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3900 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3901 !AddRHS->getOperand(0)->isAllOnesValue()) 3902 return nullptr; 3903 3904 return AddRHS->getOperand(1); 3905 } 3906 3907 /// Return a SCEV corresponding to ~V = -1-V 3908 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3909 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3910 return getConstant( 3911 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3912 3913 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3914 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3915 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3916 SmallVector<const SCEV *, 2> MatchedOperands; 3917 for (const SCEV *Operand : MME->operands()) { 3918 const SCEV *Matched = MatchNotExpr(Operand); 3919 if (!Matched) 3920 return (const SCEV *)nullptr; 3921 MatchedOperands.push_back(Matched); 3922 } 3923 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3924 MatchedOperands); 3925 }; 3926 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3927 return Replaced; 3928 } 3929 3930 Type *Ty = V->getType(); 3931 Ty = getEffectiveSCEVType(Ty); 3932 return getMinusSCEV(getMinusOne(Ty), V); 3933 } 3934 3935 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3936 SCEV::NoWrapFlags Flags, 3937 unsigned Depth) { 3938 // Fast path: X - X --> 0. 3939 if (LHS == RHS) 3940 return getZero(LHS->getType()); 3941 3942 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3943 // makes it so that we cannot make much use of NUW. 3944 auto AddFlags = SCEV::FlagAnyWrap; 3945 const bool RHSIsNotMinSigned = 3946 !getSignedRangeMin(RHS).isMinSignedValue(); 3947 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3948 // Let M be the minimum representable signed value. Then (-1)*RHS 3949 // signed-wraps if and only if RHS is M. That can happen even for 3950 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3951 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3952 // (-1)*RHS, we need to prove that RHS != M. 3953 // 3954 // If LHS is non-negative and we know that LHS - RHS does not 3955 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3956 // either by proving that RHS > M or that LHS >= 0. 3957 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3958 AddFlags = SCEV::FlagNSW; 3959 } 3960 } 3961 3962 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3963 // RHS is NSW and LHS >= 0. 3964 // 3965 // The difficulty here is that the NSW flag may have been proven 3966 // relative to a loop that is to be found in a recurrence in LHS and 3967 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3968 // larger scope than intended. 3969 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3970 3971 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3972 } 3973 3974 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3975 unsigned Depth) { 3976 Type *SrcTy = V->getType(); 3977 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3978 "Cannot truncate or zero extend with non-integer arguments!"); 3979 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3980 return V; // No conversion 3981 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3982 return getTruncateExpr(V, Ty, Depth); 3983 return getZeroExtendExpr(V, Ty, Depth); 3984 } 3985 3986 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 3987 unsigned Depth) { 3988 Type *SrcTy = V->getType(); 3989 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3990 "Cannot truncate or zero extend with non-integer arguments!"); 3991 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3992 return V; // No conversion 3993 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3994 return getTruncateExpr(V, Ty, Depth); 3995 return getSignExtendExpr(V, Ty, Depth); 3996 } 3997 3998 const SCEV * 3999 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4000 Type *SrcTy = V->getType(); 4001 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4002 "Cannot noop or zero extend with non-integer arguments!"); 4003 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4004 "getNoopOrZeroExtend cannot truncate!"); 4005 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4006 return V; // No conversion 4007 return getZeroExtendExpr(V, Ty); 4008 } 4009 4010 const SCEV * 4011 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4012 Type *SrcTy = V->getType(); 4013 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4014 "Cannot noop or sign extend with non-integer arguments!"); 4015 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4016 "getNoopOrSignExtend cannot truncate!"); 4017 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4018 return V; // No conversion 4019 return getSignExtendExpr(V, Ty); 4020 } 4021 4022 const SCEV * 4023 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4024 Type *SrcTy = V->getType(); 4025 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4026 "Cannot noop or any extend with non-integer arguments!"); 4027 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4028 "getNoopOrAnyExtend cannot truncate!"); 4029 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4030 return V; // No conversion 4031 return getAnyExtendExpr(V, Ty); 4032 } 4033 4034 const SCEV * 4035 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4036 Type *SrcTy = V->getType(); 4037 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4038 "Cannot truncate or noop with non-integer arguments!"); 4039 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4040 "getTruncateOrNoop cannot extend!"); 4041 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4042 return V; // No conversion 4043 return getTruncateExpr(V, Ty); 4044 } 4045 4046 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4047 const SCEV *RHS) { 4048 const SCEV *PromotedLHS = LHS; 4049 const SCEV *PromotedRHS = RHS; 4050 4051 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4052 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4053 else 4054 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4055 4056 return getUMaxExpr(PromotedLHS, PromotedRHS); 4057 } 4058 4059 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4060 const SCEV *RHS) { 4061 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4062 return getUMinFromMismatchedTypes(Ops); 4063 } 4064 4065 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4066 SmallVectorImpl<const SCEV *> &Ops) { 4067 assert(!Ops.empty() && "At least one operand must be!"); 4068 // Trivial case. 4069 if (Ops.size() == 1) 4070 return Ops[0]; 4071 4072 // Find the max type first. 4073 Type *MaxType = nullptr; 4074 for (auto *S : Ops) 4075 if (MaxType) 4076 MaxType = getWiderType(MaxType, S->getType()); 4077 else 4078 MaxType = S->getType(); 4079 assert(MaxType && "Failed to find maximum type!"); 4080 4081 // Extend all ops to max type. 4082 SmallVector<const SCEV *, 2> PromotedOps; 4083 for (auto *S : Ops) 4084 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4085 4086 // Generate umin. 4087 return getUMinExpr(PromotedOps); 4088 } 4089 4090 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4091 // A pointer operand may evaluate to a nonpointer expression, such as null. 4092 if (!V->getType()->isPointerTy()) 4093 return V; 4094 4095 while (true) { 4096 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4097 V = Cast->getOperand(); 4098 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4099 const SCEV *PtrOp = nullptr; 4100 for (const SCEV *NAryOp : NAry->operands()) { 4101 if (NAryOp->getType()->isPointerTy()) { 4102 // Cannot find the base of an expression with multiple pointer ops. 4103 if (PtrOp) 4104 return V; 4105 PtrOp = NAryOp; 4106 } 4107 } 4108 if (!PtrOp) // All operands were non-pointer. 4109 return V; 4110 V = PtrOp; 4111 } else // Not something we can look further into. 4112 return V; 4113 } 4114 } 4115 4116 /// Push users of the given Instruction onto the given Worklist. 4117 static void 4118 PushDefUseChildren(Instruction *I, 4119 SmallVectorImpl<Instruction *> &Worklist) { 4120 // Push the def-use children onto the Worklist stack. 4121 for (User *U : I->users()) 4122 Worklist.push_back(cast<Instruction>(U)); 4123 } 4124 4125 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4126 SmallVector<Instruction *, 16> Worklist; 4127 PushDefUseChildren(PN, Worklist); 4128 4129 SmallPtrSet<Instruction *, 8> Visited; 4130 Visited.insert(PN); 4131 while (!Worklist.empty()) { 4132 Instruction *I = Worklist.pop_back_val(); 4133 if (!Visited.insert(I).second) 4134 continue; 4135 4136 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4137 if (It != ValueExprMap.end()) { 4138 const SCEV *Old = It->second; 4139 4140 // Short-circuit the def-use traversal if the symbolic name 4141 // ceases to appear in expressions. 4142 if (Old != SymName && !hasOperand(Old, SymName)) 4143 continue; 4144 4145 // SCEVUnknown for a PHI either means that it has an unrecognized 4146 // structure, it's a PHI that's in the progress of being computed 4147 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4148 // additional loop trip count information isn't going to change anything. 4149 // In the second case, createNodeForPHI will perform the necessary 4150 // updates on its own when it gets to that point. In the third, we do 4151 // want to forget the SCEVUnknown. 4152 if (!isa<PHINode>(I) || 4153 !isa<SCEVUnknown>(Old) || 4154 (I != PN && Old == SymName)) { 4155 eraseValueFromMap(It->first); 4156 forgetMemoizedResults(Old); 4157 } 4158 } 4159 4160 PushDefUseChildren(I, Worklist); 4161 } 4162 } 4163 4164 namespace { 4165 4166 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4167 /// expression in case its Loop is L. If it is not L then 4168 /// if IgnoreOtherLoops is true then use AddRec itself 4169 /// otherwise rewrite cannot be done. 4170 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4171 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4172 public: 4173 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4174 bool IgnoreOtherLoops = true) { 4175 SCEVInitRewriter Rewriter(L, SE); 4176 const SCEV *Result = Rewriter.visit(S); 4177 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4178 return SE.getCouldNotCompute(); 4179 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4180 ? SE.getCouldNotCompute() 4181 : Result; 4182 } 4183 4184 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4185 if (!SE.isLoopInvariant(Expr, L)) 4186 SeenLoopVariantSCEVUnknown = true; 4187 return Expr; 4188 } 4189 4190 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4191 // Only re-write AddRecExprs for this loop. 4192 if (Expr->getLoop() == L) 4193 return Expr->getStart(); 4194 SeenOtherLoops = true; 4195 return Expr; 4196 } 4197 4198 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4199 4200 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4201 4202 private: 4203 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4204 : SCEVRewriteVisitor(SE), L(L) {} 4205 4206 const Loop *L; 4207 bool SeenLoopVariantSCEVUnknown = false; 4208 bool SeenOtherLoops = false; 4209 }; 4210 4211 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4212 /// increment expression in case its Loop is L. If it is not L then 4213 /// use AddRec itself. 4214 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4215 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4216 public: 4217 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4218 SCEVPostIncRewriter Rewriter(L, SE); 4219 const SCEV *Result = Rewriter.visit(S); 4220 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4221 ? SE.getCouldNotCompute() 4222 : Result; 4223 } 4224 4225 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4226 if (!SE.isLoopInvariant(Expr, L)) 4227 SeenLoopVariantSCEVUnknown = true; 4228 return Expr; 4229 } 4230 4231 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4232 // Only re-write AddRecExprs for this loop. 4233 if (Expr->getLoop() == L) 4234 return Expr->getPostIncExpr(SE); 4235 SeenOtherLoops = true; 4236 return Expr; 4237 } 4238 4239 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4240 4241 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4242 4243 private: 4244 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4245 : SCEVRewriteVisitor(SE), L(L) {} 4246 4247 const Loop *L; 4248 bool SeenLoopVariantSCEVUnknown = false; 4249 bool SeenOtherLoops = false; 4250 }; 4251 4252 /// This class evaluates the compare condition by matching it against the 4253 /// condition of loop latch. If there is a match we assume a true value 4254 /// for the condition while building SCEV nodes. 4255 class SCEVBackedgeConditionFolder 4256 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4257 public: 4258 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4259 ScalarEvolution &SE) { 4260 bool IsPosBECond = false; 4261 Value *BECond = nullptr; 4262 if (BasicBlock *Latch = L->getLoopLatch()) { 4263 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4264 if (BI && BI->isConditional()) { 4265 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4266 "Both outgoing branches should not target same header!"); 4267 BECond = BI->getCondition(); 4268 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4269 } else { 4270 return S; 4271 } 4272 } 4273 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4274 return Rewriter.visit(S); 4275 } 4276 4277 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4278 const SCEV *Result = Expr; 4279 bool InvariantF = SE.isLoopInvariant(Expr, L); 4280 4281 if (!InvariantF) { 4282 Instruction *I = cast<Instruction>(Expr->getValue()); 4283 switch (I->getOpcode()) { 4284 case Instruction::Select: { 4285 SelectInst *SI = cast<SelectInst>(I); 4286 Optional<const SCEV *> Res = 4287 compareWithBackedgeCondition(SI->getCondition()); 4288 if (Res.hasValue()) { 4289 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4290 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4291 } 4292 break; 4293 } 4294 default: { 4295 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4296 if (Res.hasValue()) 4297 Result = Res.getValue(); 4298 break; 4299 } 4300 } 4301 } 4302 return Result; 4303 } 4304 4305 private: 4306 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4307 bool IsPosBECond, ScalarEvolution &SE) 4308 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4309 IsPositiveBECond(IsPosBECond) {} 4310 4311 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4312 4313 const Loop *L; 4314 /// Loop back condition. 4315 Value *BackedgeCond = nullptr; 4316 /// Set to true if loop back is on positive branch condition. 4317 bool IsPositiveBECond; 4318 }; 4319 4320 Optional<const SCEV *> 4321 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4322 4323 // If value matches the backedge condition for loop latch, 4324 // then return a constant evolution node based on loopback 4325 // branch taken. 4326 if (BackedgeCond == IC) 4327 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4328 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4329 return None; 4330 } 4331 4332 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4333 public: 4334 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4335 ScalarEvolution &SE) { 4336 SCEVShiftRewriter Rewriter(L, SE); 4337 const SCEV *Result = Rewriter.visit(S); 4338 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4339 } 4340 4341 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4342 // Only allow AddRecExprs for this loop. 4343 if (!SE.isLoopInvariant(Expr, L)) 4344 Valid = false; 4345 return Expr; 4346 } 4347 4348 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4349 if (Expr->getLoop() == L && Expr->isAffine()) 4350 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4351 Valid = false; 4352 return Expr; 4353 } 4354 4355 bool isValid() { return Valid; } 4356 4357 private: 4358 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4359 : SCEVRewriteVisitor(SE), L(L) {} 4360 4361 const Loop *L; 4362 bool Valid = true; 4363 }; 4364 4365 } // end anonymous namespace 4366 4367 SCEV::NoWrapFlags 4368 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4369 if (!AR->isAffine()) 4370 return SCEV::FlagAnyWrap; 4371 4372 using OBO = OverflowingBinaryOperator; 4373 4374 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4375 4376 if (!AR->hasNoSignedWrap()) { 4377 ConstantRange AddRecRange = getSignedRange(AR); 4378 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4379 4380 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4381 Instruction::Add, IncRange, OBO::NoSignedWrap); 4382 if (NSWRegion.contains(AddRecRange)) 4383 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4384 } 4385 4386 if (!AR->hasNoUnsignedWrap()) { 4387 ConstantRange AddRecRange = getUnsignedRange(AR); 4388 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4389 4390 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4391 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4392 if (NUWRegion.contains(AddRecRange)) 4393 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4394 } 4395 4396 return Result; 4397 } 4398 4399 SCEV::NoWrapFlags 4400 ScalarEvolution::proveNoWrapViaInduction(const SCEVAddRecExpr *AR) { 4401 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4402 if (!AR->isAffine()) 4403 return Result; 4404 4405 const SCEV *Step = AR->getStepRecurrence(*this); 4406 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4407 const Loop *L = AR->getLoop(); 4408 4409 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4410 // Note that this serves two purposes: It filters out loops that are 4411 // simply not analyzable, and it covers the case where this code is 4412 // being called from within backedge-taken count analysis, such that 4413 // attempting to ask for the backedge-taken count would likely result 4414 // in infinite recursion. In the later case, the analysis code will 4415 // cope with a conservative value, and it will take care to purge 4416 // that value once it has finished. 4417 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4418 4419 // Normally, in the cases we can prove no-overflow via a 4420 // backedge guarding condition, we can also compute a backedge 4421 // taken count for the loop. The exceptions are assumptions and 4422 // guards present in the loop -- SCEV is not great at exploiting 4423 // these to compute max backedge taken counts, but can still use 4424 // these to prove lack of overflow. Use this fact to avoid 4425 // doing extra work that may not pay off. 4426 4427 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4428 AC.assumptions().empty()) 4429 return Result; 4430 4431 if (!AR->hasNoSignedWrap()) { 4432 // If the backedge is guarded by a comparison with the pre-inc 4433 // value the addrec is safe. Also, if the entry is guarded by 4434 // a comparison with the start value and the backedge is 4435 // guarded by a comparison with the post-inc value, the addrec 4436 // is safe. 4437 ICmpInst::Predicate Pred; 4438 const SCEV *OverflowLimit = 4439 getSignedOverflowLimitForStep(Step, &Pred, this); 4440 if (OverflowLimit && 4441 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4442 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4443 Result = setFlags(Result, SCEV::FlagNSW); 4444 } 4445 } 4446 4447 if (!AR->hasNoUnsignedWrap()) { 4448 // If the backedge is guarded by a comparison with the pre-inc 4449 // value the addrec is safe. Also, if the entry is guarded by 4450 // a comparison with the start value and the backedge is 4451 // guarded by a comparison with the post-inc value, the addrec 4452 // is safe. 4453 if (isKnownPositive(Step)) { 4454 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4455 getUnsignedRangeMax(Step)); 4456 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4457 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4458 Result = setFlags(Result, SCEV::FlagNUW); 4459 } 4460 } 4461 } 4462 4463 if (!AR->hasNoSelfWrap()) { 4464 if (isKnownNegative(Step)) { 4465 // TODO: We can generalize this condition by proving (ugt AR, AR.start) 4466 // for the two clauses below. 4467 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 4468 getSignedRangeMin(Step)); 4469 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 4470 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 4471 // Negative step causes unsigned wrap, but it still can't self-wrap. 4472 Result = setFlags(Result, SCEV::FlagNW); 4473 } 4474 } 4475 } 4476 4477 return Result; 4478 } 4479 4480 namespace { 4481 4482 /// Represents an abstract binary operation. This may exist as a 4483 /// normal instruction or constant expression, or may have been 4484 /// derived from an expression tree. 4485 struct BinaryOp { 4486 unsigned Opcode; 4487 Value *LHS; 4488 Value *RHS; 4489 bool IsNSW = false; 4490 bool IsNUW = false; 4491 bool IsExact = false; 4492 4493 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4494 /// constant expression. 4495 Operator *Op = nullptr; 4496 4497 explicit BinaryOp(Operator *Op) 4498 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4499 Op(Op) { 4500 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4501 IsNSW = OBO->hasNoSignedWrap(); 4502 IsNUW = OBO->hasNoUnsignedWrap(); 4503 } 4504 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4505 IsExact = PEO->isExact(); 4506 } 4507 4508 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4509 bool IsNUW = false, bool IsExact = false) 4510 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4511 IsExact(IsExact) {} 4512 }; 4513 4514 } // end anonymous namespace 4515 4516 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4517 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4518 auto *Op = dyn_cast<Operator>(V); 4519 if (!Op) 4520 return None; 4521 4522 // Implementation detail: all the cleverness here should happen without 4523 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4524 // SCEV expressions when possible, and we should not break that. 4525 4526 switch (Op->getOpcode()) { 4527 case Instruction::Add: 4528 case Instruction::Sub: 4529 case Instruction::Mul: 4530 case Instruction::UDiv: 4531 case Instruction::URem: 4532 case Instruction::And: 4533 case Instruction::Or: 4534 case Instruction::AShr: 4535 case Instruction::Shl: 4536 return BinaryOp(Op); 4537 4538 case Instruction::Xor: 4539 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4540 // If the RHS of the xor is a signmask, then this is just an add. 4541 // Instcombine turns add of signmask into xor as a strength reduction step. 4542 if (RHSC->getValue().isSignMask()) 4543 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4544 return BinaryOp(Op); 4545 4546 case Instruction::LShr: 4547 // Turn logical shift right of a constant into a unsigned divide. 4548 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4549 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4550 4551 // If the shift count is not less than the bitwidth, the result of 4552 // the shift is undefined. Don't try to analyze it, because the 4553 // resolution chosen here may differ from the resolution chosen in 4554 // other parts of the compiler. 4555 if (SA->getValue().ult(BitWidth)) { 4556 Constant *X = 4557 ConstantInt::get(SA->getContext(), 4558 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4559 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4560 } 4561 } 4562 return BinaryOp(Op); 4563 4564 case Instruction::ExtractValue: { 4565 auto *EVI = cast<ExtractValueInst>(Op); 4566 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4567 break; 4568 4569 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4570 if (!WO) 4571 break; 4572 4573 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4574 bool Signed = WO->isSigned(); 4575 // TODO: Should add nuw/nsw flags for mul as well. 4576 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4577 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4578 4579 // Now that we know that all uses of the arithmetic-result component of 4580 // CI are guarded by the overflow check, we can go ahead and pretend 4581 // that the arithmetic is non-overflowing. 4582 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4583 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4584 } 4585 4586 default: 4587 break; 4588 } 4589 4590 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4591 // semantics as a Sub, return a binary sub expression. 4592 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4593 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4594 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4595 4596 return None; 4597 } 4598 4599 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4600 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4601 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4602 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4603 /// follows one of the following patterns: 4604 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4605 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4606 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4607 /// we return the type of the truncation operation, and indicate whether the 4608 /// truncated type should be treated as signed/unsigned by setting 4609 /// \p Signed to true/false, respectively. 4610 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4611 bool &Signed, ScalarEvolution &SE) { 4612 // The case where Op == SymbolicPHI (that is, with no type conversions on 4613 // the way) is handled by the regular add recurrence creating logic and 4614 // would have already been triggered in createAddRecForPHI. Reaching it here 4615 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4616 // because one of the other operands of the SCEVAddExpr updating this PHI is 4617 // not invariant). 4618 // 4619 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4620 // this case predicates that allow us to prove that Op == SymbolicPHI will 4621 // be added. 4622 if (Op == SymbolicPHI) 4623 return nullptr; 4624 4625 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4626 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4627 if (SourceBits != NewBits) 4628 return nullptr; 4629 4630 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4631 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4632 if (!SExt && !ZExt) 4633 return nullptr; 4634 const SCEVTruncateExpr *Trunc = 4635 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4636 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4637 if (!Trunc) 4638 return nullptr; 4639 const SCEV *X = Trunc->getOperand(); 4640 if (X != SymbolicPHI) 4641 return nullptr; 4642 Signed = SExt != nullptr; 4643 return Trunc->getType(); 4644 } 4645 4646 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4647 if (!PN->getType()->isIntegerTy()) 4648 return nullptr; 4649 const Loop *L = LI.getLoopFor(PN->getParent()); 4650 if (!L || L->getHeader() != PN->getParent()) 4651 return nullptr; 4652 return L; 4653 } 4654 4655 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4656 // computation that updates the phi follows the following pattern: 4657 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4658 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4659 // If so, try to see if it can be rewritten as an AddRecExpr under some 4660 // Predicates. If successful, return them as a pair. Also cache the results 4661 // of the analysis. 4662 // 4663 // Example usage scenario: 4664 // Say the Rewriter is called for the following SCEV: 4665 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4666 // where: 4667 // %X = phi i64 (%Start, %BEValue) 4668 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4669 // and call this function with %SymbolicPHI = %X. 4670 // 4671 // The analysis will find that the value coming around the backedge has 4672 // the following SCEV: 4673 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4674 // Upon concluding that this matches the desired pattern, the function 4675 // will return the pair {NewAddRec, SmallPredsVec} where: 4676 // NewAddRec = {%Start,+,%Step} 4677 // SmallPredsVec = {P1, P2, P3} as follows: 4678 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4679 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4680 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4681 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4682 // under the predicates {P1,P2,P3}. 4683 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4684 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4685 // 4686 // TODO's: 4687 // 4688 // 1) Extend the Induction descriptor to also support inductions that involve 4689 // casts: When needed (namely, when we are called in the context of the 4690 // vectorizer induction analysis), a Set of cast instructions will be 4691 // populated by this method, and provided back to isInductionPHI. This is 4692 // needed to allow the vectorizer to properly record them to be ignored by 4693 // the cost model and to avoid vectorizing them (otherwise these casts, 4694 // which are redundant under the runtime overflow checks, will be 4695 // vectorized, which can be costly). 4696 // 4697 // 2) Support additional induction/PHISCEV patterns: We also want to support 4698 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4699 // after the induction update operation (the induction increment): 4700 // 4701 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4702 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4703 // 4704 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4705 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4706 // 4707 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4708 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4709 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4710 SmallVector<const SCEVPredicate *, 3> Predicates; 4711 4712 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4713 // return an AddRec expression under some predicate. 4714 4715 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4716 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4717 assert(L && "Expecting an integer loop header phi"); 4718 4719 // The loop may have multiple entrances or multiple exits; we can analyze 4720 // this phi as an addrec if it has a unique entry value and a unique 4721 // backedge value. 4722 Value *BEValueV = nullptr, *StartValueV = nullptr; 4723 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4724 Value *V = PN->getIncomingValue(i); 4725 if (L->contains(PN->getIncomingBlock(i))) { 4726 if (!BEValueV) { 4727 BEValueV = V; 4728 } else if (BEValueV != V) { 4729 BEValueV = nullptr; 4730 break; 4731 } 4732 } else if (!StartValueV) { 4733 StartValueV = V; 4734 } else if (StartValueV != V) { 4735 StartValueV = nullptr; 4736 break; 4737 } 4738 } 4739 if (!BEValueV || !StartValueV) 4740 return None; 4741 4742 const SCEV *BEValue = getSCEV(BEValueV); 4743 4744 // If the value coming around the backedge is an add with the symbolic 4745 // value we just inserted, possibly with casts that we can ignore under 4746 // an appropriate runtime guard, then we found a simple induction variable! 4747 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4748 if (!Add) 4749 return None; 4750 4751 // If there is a single occurrence of the symbolic value, possibly 4752 // casted, replace it with a recurrence. 4753 unsigned FoundIndex = Add->getNumOperands(); 4754 Type *TruncTy = nullptr; 4755 bool Signed; 4756 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4757 if ((TruncTy = 4758 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4759 if (FoundIndex == e) { 4760 FoundIndex = i; 4761 break; 4762 } 4763 4764 if (FoundIndex == Add->getNumOperands()) 4765 return None; 4766 4767 // Create an add with everything but the specified operand. 4768 SmallVector<const SCEV *, 8> Ops; 4769 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4770 if (i != FoundIndex) 4771 Ops.push_back(Add->getOperand(i)); 4772 const SCEV *Accum = getAddExpr(Ops); 4773 4774 // The runtime checks will not be valid if the step amount is 4775 // varying inside the loop. 4776 if (!isLoopInvariant(Accum, L)) 4777 return None; 4778 4779 // *** Part2: Create the predicates 4780 4781 // Analysis was successful: we have a phi-with-cast pattern for which we 4782 // can return an AddRec expression under the following predicates: 4783 // 4784 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4785 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4786 // P2: An Equal predicate that guarantees that 4787 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4788 // P3: An Equal predicate that guarantees that 4789 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4790 // 4791 // As we next prove, the above predicates guarantee that: 4792 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4793 // 4794 // 4795 // More formally, we want to prove that: 4796 // Expr(i+1) = Start + (i+1) * Accum 4797 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4798 // 4799 // Given that: 4800 // 1) Expr(0) = Start 4801 // 2) Expr(1) = Start + Accum 4802 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4803 // 3) Induction hypothesis (step i): 4804 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4805 // 4806 // Proof: 4807 // Expr(i+1) = 4808 // = Start + (i+1)*Accum 4809 // = (Start + i*Accum) + Accum 4810 // = Expr(i) + Accum 4811 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4812 // :: from step i 4813 // 4814 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4815 // 4816 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4817 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4818 // + Accum :: from P3 4819 // 4820 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4821 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4822 // 4823 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4824 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4825 // 4826 // By induction, the same applies to all iterations 1<=i<n: 4827 // 4828 4829 // Create a truncated addrec for which we will add a no overflow check (P1). 4830 const SCEV *StartVal = getSCEV(StartValueV); 4831 const SCEV *PHISCEV = 4832 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4833 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4834 4835 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4836 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4837 // will be constant. 4838 // 4839 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4840 // add P1. 4841 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4842 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4843 Signed ? SCEVWrapPredicate::IncrementNSSW 4844 : SCEVWrapPredicate::IncrementNUSW; 4845 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4846 Predicates.push_back(AddRecPred); 4847 } 4848 4849 // Create the Equal Predicates P2,P3: 4850 4851 // It is possible that the predicates P2 and/or P3 are computable at 4852 // compile time due to StartVal and/or Accum being constants. 4853 // If either one is, then we can check that now and escape if either P2 4854 // or P3 is false. 4855 4856 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4857 // for each of StartVal and Accum 4858 auto getExtendedExpr = [&](const SCEV *Expr, 4859 bool CreateSignExtend) -> const SCEV * { 4860 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4861 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4862 const SCEV *ExtendedExpr = 4863 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4864 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4865 return ExtendedExpr; 4866 }; 4867 4868 // Given: 4869 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4870 // = getExtendedExpr(Expr) 4871 // Determine whether the predicate P: Expr == ExtendedExpr 4872 // is known to be false at compile time 4873 auto PredIsKnownFalse = [&](const SCEV *Expr, 4874 const SCEV *ExtendedExpr) -> bool { 4875 return Expr != ExtendedExpr && 4876 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4877 }; 4878 4879 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4880 if (PredIsKnownFalse(StartVal, StartExtended)) { 4881 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4882 return None; 4883 } 4884 4885 // The Step is always Signed (because the overflow checks are either 4886 // NSSW or NUSW) 4887 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4888 if (PredIsKnownFalse(Accum, AccumExtended)) { 4889 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4890 return None; 4891 } 4892 4893 auto AppendPredicate = [&](const SCEV *Expr, 4894 const SCEV *ExtendedExpr) -> void { 4895 if (Expr != ExtendedExpr && 4896 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4897 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4898 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4899 Predicates.push_back(Pred); 4900 } 4901 }; 4902 4903 AppendPredicate(StartVal, StartExtended); 4904 AppendPredicate(Accum, AccumExtended); 4905 4906 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4907 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4908 // into NewAR if it will also add the runtime overflow checks specified in 4909 // Predicates. 4910 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4911 4912 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4913 std::make_pair(NewAR, Predicates); 4914 // Remember the result of the analysis for this SCEV at this locayyytion. 4915 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4916 return PredRewrite; 4917 } 4918 4919 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4920 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4921 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4922 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4923 if (!L) 4924 return None; 4925 4926 // Check to see if we already analyzed this PHI. 4927 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4928 if (I != PredicatedSCEVRewrites.end()) { 4929 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4930 I->second; 4931 // Analysis was done before and failed to create an AddRec: 4932 if (Rewrite.first == SymbolicPHI) 4933 return None; 4934 // Analysis was done before and succeeded to create an AddRec under 4935 // a predicate: 4936 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4937 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4938 return Rewrite; 4939 } 4940 4941 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4942 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4943 4944 // Record in the cache that the analysis failed 4945 if (!Rewrite) { 4946 SmallVector<const SCEVPredicate *, 3> Predicates; 4947 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4948 return None; 4949 } 4950 4951 return Rewrite; 4952 } 4953 4954 // FIXME: This utility is currently required because the Rewriter currently 4955 // does not rewrite this expression: 4956 // {0, +, (sext ix (trunc iy to ix) to iy)} 4957 // into {0, +, %step}, 4958 // even when the following Equal predicate exists: 4959 // "%step == (sext ix (trunc iy to ix) to iy)". 4960 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4961 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4962 if (AR1 == AR2) 4963 return true; 4964 4965 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4966 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4967 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4968 return false; 4969 return true; 4970 }; 4971 4972 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4973 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4974 return false; 4975 return true; 4976 } 4977 4978 /// A helper function for createAddRecFromPHI to handle simple cases. 4979 /// 4980 /// This function tries to find an AddRec expression for the simplest (yet most 4981 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4982 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4983 /// technique for finding the AddRec expression. 4984 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4985 Value *BEValueV, 4986 Value *StartValueV) { 4987 const Loop *L = LI.getLoopFor(PN->getParent()); 4988 assert(L && L->getHeader() == PN->getParent()); 4989 assert(BEValueV && StartValueV); 4990 4991 auto BO = MatchBinaryOp(BEValueV, DT); 4992 if (!BO) 4993 return nullptr; 4994 4995 if (BO->Opcode != Instruction::Add) 4996 return nullptr; 4997 4998 const SCEV *Accum = nullptr; 4999 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5000 Accum = getSCEV(BO->RHS); 5001 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5002 Accum = getSCEV(BO->LHS); 5003 5004 if (!Accum) 5005 return nullptr; 5006 5007 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5008 if (BO->IsNUW) 5009 Flags = setFlags(Flags, SCEV::FlagNUW); 5010 if (BO->IsNSW) 5011 Flags = setFlags(Flags, SCEV::FlagNSW); 5012 5013 const SCEV *StartVal = getSCEV(StartValueV); 5014 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5015 5016 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5017 5018 // We can add Flags to the post-inc expression only if we 5019 // know that it is *undefined behavior* for BEValueV to 5020 // overflow. 5021 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5022 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5023 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5024 5025 return PHISCEV; 5026 } 5027 5028 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5029 const Loop *L = LI.getLoopFor(PN->getParent()); 5030 if (!L || L->getHeader() != PN->getParent()) 5031 return nullptr; 5032 5033 // The loop may have multiple entrances or multiple exits; we can analyze 5034 // this phi as an addrec if it has a unique entry value and a unique 5035 // backedge value. 5036 Value *BEValueV = nullptr, *StartValueV = nullptr; 5037 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5038 Value *V = PN->getIncomingValue(i); 5039 if (L->contains(PN->getIncomingBlock(i))) { 5040 if (!BEValueV) { 5041 BEValueV = V; 5042 } else if (BEValueV != V) { 5043 BEValueV = nullptr; 5044 break; 5045 } 5046 } else if (!StartValueV) { 5047 StartValueV = V; 5048 } else if (StartValueV != V) { 5049 StartValueV = nullptr; 5050 break; 5051 } 5052 } 5053 if (!BEValueV || !StartValueV) 5054 return nullptr; 5055 5056 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5057 "PHI node already processed?"); 5058 5059 // First, try to find AddRec expression without creating a fictituos symbolic 5060 // value for PN. 5061 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5062 return S; 5063 5064 // Handle PHI node value symbolically. 5065 const SCEV *SymbolicName = getUnknown(PN); 5066 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5067 5068 // Using this symbolic name for the PHI, analyze the value coming around 5069 // the back-edge. 5070 const SCEV *BEValue = getSCEV(BEValueV); 5071 5072 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5073 // has a special value for the first iteration of the loop. 5074 5075 // If the value coming around the backedge is an add with the symbolic 5076 // value we just inserted, then we found a simple induction variable! 5077 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5078 // If there is a single occurrence of the symbolic value, replace it 5079 // with a recurrence. 5080 unsigned FoundIndex = Add->getNumOperands(); 5081 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5082 if (Add->getOperand(i) == SymbolicName) 5083 if (FoundIndex == e) { 5084 FoundIndex = i; 5085 break; 5086 } 5087 5088 if (FoundIndex != Add->getNumOperands()) { 5089 // Create an add with everything but the specified operand. 5090 SmallVector<const SCEV *, 8> Ops; 5091 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5092 if (i != FoundIndex) 5093 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5094 L, *this)); 5095 const SCEV *Accum = getAddExpr(Ops); 5096 5097 // This is not a valid addrec if the step amount is varying each 5098 // loop iteration, but is not itself an addrec in this loop. 5099 if (isLoopInvariant(Accum, L) || 5100 (isa<SCEVAddRecExpr>(Accum) && 5101 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5102 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5103 5104 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5105 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5106 if (BO->IsNUW) 5107 Flags = setFlags(Flags, SCEV::FlagNUW); 5108 if (BO->IsNSW) 5109 Flags = setFlags(Flags, SCEV::FlagNSW); 5110 } 5111 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5112 // If the increment is an inbounds GEP, then we know the address 5113 // space cannot be wrapped around. We cannot make any guarantee 5114 // about signed or unsigned overflow because pointers are 5115 // unsigned but we may have a negative index from the base 5116 // pointer. We can guarantee that no unsigned wrap occurs if the 5117 // indices form a positive value. 5118 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5119 Flags = setFlags(Flags, SCEV::FlagNW); 5120 5121 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5122 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5123 Flags = setFlags(Flags, SCEV::FlagNUW); 5124 } 5125 5126 // We cannot transfer nuw and nsw flags from subtraction 5127 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5128 // for instance. 5129 } 5130 5131 const SCEV *StartVal = getSCEV(StartValueV); 5132 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5133 5134 // Okay, for the entire analysis of this edge we assumed the PHI 5135 // to be symbolic. We now need to go back and purge all of the 5136 // entries for the scalars that use the symbolic expression. 5137 forgetSymbolicName(PN, SymbolicName); 5138 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5139 5140 // We can add Flags to the post-inc expression only if we 5141 // know that it is *undefined behavior* for BEValueV to 5142 // overflow. 5143 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5144 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5145 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5146 5147 return PHISCEV; 5148 } 5149 } 5150 } else { 5151 // Otherwise, this could be a loop like this: 5152 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5153 // In this case, j = {1,+,1} and BEValue is j. 5154 // Because the other in-value of i (0) fits the evolution of BEValue 5155 // i really is an addrec evolution. 5156 // 5157 // We can generalize this saying that i is the shifted value of BEValue 5158 // by one iteration: 5159 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5160 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5161 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5162 if (Shifted != getCouldNotCompute() && 5163 Start != getCouldNotCompute()) { 5164 const SCEV *StartVal = getSCEV(StartValueV); 5165 if (Start == StartVal) { 5166 // Okay, for the entire analysis of this edge we assumed the PHI 5167 // to be symbolic. We now need to go back and purge all of the 5168 // entries for the scalars that use the symbolic expression. 5169 forgetSymbolicName(PN, SymbolicName); 5170 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5171 return Shifted; 5172 } 5173 } 5174 } 5175 5176 // Remove the temporary PHI node SCEV that has been inserted while intending 5177 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5178 // as it will prevent later (possibly simpler) SCEV expressions to be added 5179 // to the ValueExprMap. 5180 eraseValueFromMap(PN); 5181 5182 return nullptr; 5183 } 5184 5185 // Checks if the SCEV S is available at BB. S is considered available at BB 5186 // if S can be materialized at BB without introducing a fault. 5187 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5188 BasicBlock *BB) { 5189 struct CheckAvailable { 5190 bool TraversalDone = false; 5191 bool Available = true; 5192 5193 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5194 BasicBlock *BB = nullptr; 5195 DominatorTree &DT; 5196 5197 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5198 : L(L), BB(BB), DT(DT) {} 5199 5200 bool setUnavailable() { 5201 TraversalDone = true; 5202 Available = false; 5203 return false; 5204 } 5205 5206 bool follow(const SCEV *S) { 5207 switch (S->getSCEVType()) { 5208 case scConstant: 5209 case scPtrToInt: 5210 case scTruncate: 5211 case scZeroExtend: 5212 case scSignExtend: 5213 case scAddExpr: 5214 case scMulExpr: 5215 case scUMaxExpr: 5216 case scSMaxExpr: 5217 case scUMinExpr: 5218 case scSMinExpr: 5219 // These expressions are available if their operand(s) is/are. 5220 return true; 5221 5222 case scAddRecExpr: { 5223 // We allow add recurrences that are on the loop BB is in, or some 5224 // outer loop. This guarantees availability because the value of the 5225 // add recurrence at BB is simply the "current" value of the induction 5226 // variable. We can relax this in the future; for instance an add 5227 // recurrence on a sibling dominating loop is also available at BB. 5228 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5229 if (L && (ARLoop == L || ARLoop->contains(L))) 5230 return true; 5231 5232 return setUnavailable(); 5233 } 5234 5235 case scUnknown: { 5236 // For SCEVUnknown, we check for simple dominance. 5237 const auto *SU = cast<SCEVUnknown>(S); 5238 Value *V = SU->getValue(); 5239 5240 if (isa<Argument>(V)) 5241 return false; 5242 5243 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5244 return false; 5245 5246 return setUnavailable(); 5247 } 5248 5249 case scUDivExpr: 5250 case scCouldNotCompute: 5251 // We do not try to smart about these at all. 5252 return setUnavailable(); 5253 } 5254 llvm_unreachable("Unknown SCEV kind!"); 5255 } 5256 5257 bool isDone() { return TraversalDone; } 5258 }; 5259 5260 CheckAvailable CA(L, BB, DT); 5261 SCEVTraversal<CheckAvailable> ST(CA); 5262 5263 ST.visitAll(S); 5264 return CA.Available; 5265 } 5266 5267 // Try to match a control flow sequence that branches out at BI and merges back 5268 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5269 // match. 5270 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5271 Value *&C, Value *&LHS, Value *&RHS) { 5272 C = BI->getCondition(); 5273 5274 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5275 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5276 5277 if (!LeftEdge.isSingleEdge()) 5278 return false; 5279 5280 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5281 5282 Use &LeftUse = Merge->getOperandUse(0); 5283 Use &RightUse = Merge->getOperandUse(1); 5284 5285 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5286 LHS = LeftUse; 5287 RHS = RightUse; 5288 return true; 5289 } 5290 5291 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5292 LHS = RightUse; 5293 RHS = LeftUse; 5294 return true; 5295 } 5296 5297 return false; 5298 } 5299 5300 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5301 auto IsReachable = 5302 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5303 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5304 const Loop *L = LI.getLoopFor(PN->getParent()); 5305 5306 // We don't want to break LCSSA, even in a SCEV expression tree. 5307 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5308 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5309 return nullptr; 5310 5311 // Try to match 5312 // 5313 // br %cond, label %left, label %right 5314 // left: 5315 // br label %merge 5316 // right: 5317 // br label %merge 5318 // merge: 5319 // V = phi [ %x, %left ], [ %y, %right ] 5320 // 5321 // as "select %cond, %x, %y" 5322 5323 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5324 assert(IDom && "At least the entry block should dominate PN"); 5325 5326 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5327 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5328 5329 if (BI && BI->isConditional() && 5330 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5331 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5332 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5333 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5334 } 5335 5336 return nullptr; 5337 } 5338 5339 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5340 if (const SCEV *S = createAddRecFromPHI(PN)) 5341 return S; 5342 5343 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5344 return S; 5345 5346 // If the PHI has a single incoming value, follow that value, unless the 5347 // PHI's incoming blocks are in a different loop, in which case doing so 5348 // risks breaking LCSSA form. Instcombine would normally zap these, but 5349 // it doesn't have DominatorTree information, so it may miss cases. 5350 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5351 if (LI.replacementPreservesLCSSAForm(PN, V)) 5352 return getSCEV(V); 5353 5354 // If it's not a loop phi, we can't handle it yet. 5355 return getUnknown(PN); 5356 } 5357 5358 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5359 Value *Cond, 5360 Value *TrueVal, 5361 Value *FalseVal) { 5362 // Handle "constant" branch or select. This can occur for instance when a 5363 // loop pass transforms an inner loop and moves on to process the outer loop. 5364 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5365 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5366 5367 // Try to match some simple smax or umax patterns. 5368 auto *ICI = dyn_cast<ICmpInst>(Cond); 5369 if (!ICI) 5370 return getUnknown(I); 5371 5372 Value *LHS = ICI->getOperand(0); 5373 Value *RHS = ICI->getOperand(1); 5374 5375 switch (ICI->getPredicate()) { 5376 case ICmpInst::ICMP_SLT: 5377 case ICmpInst::ICMP_SLE: 5378 std::swap(LHS, RHS); 5379 LLVM_FALLTHROUGH; 5380 case ICmpInst::ICMP_SGT: 5381 case ICmpInst::ICMP_SGE: 5382 // a >s b ? a+x : b+x -> smax(a, b)+x 5383 // a >s b ? b+x : a+x -> smin(a, b)+x 5384 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5385 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5386 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), 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, RS); 5391 if (LDiff == RDiff) 5392 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5393 LDiff = getMinusSCEV(LA, RS); 5394 RDiff = getMinusSCEV(RA, LS); 5395 if (LDiff == RDiff) 5396 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5397 } 5398 break; 5399 case ICmpInst::ICMP_ULT: 5400 case ICmpInst::ICMP_ULE: 5401 std::swap(LHS, RHS); 5402 LLVM_FALLTHROUGH; 5403 case ICmpInst::ICMP_UGT: 5404 case ICmpInst::ICMP_UGE: 5405 // a >u b ? a+x : b+x -> umax(a, b)+x 5406 // a >u b ? b+x : a+x -> umin(a, b)+x 5407 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5408 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5409 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5410 const SCEV *LA = getSCEV(TrueVal); 5411 const SCEV *RA = getSCEV(FalseVal); 5412 const SCEV *LDiff = getMinusSCEV(LA, LS); 5413 const SCEV *RDiff = getMinusSCEV(RA, RS); 5414 if (LDiff == RDiff) 5415 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5416 LDiff = getMinusSCEV(LA, RS); 5417 RDiff = getMinusSCEV(RA, LS); 5418 if (LDiff == RDiff) 5419 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5420 } 5421 break; 5422 case ICmpInst::ICMP_NE: 5423 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5424 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5425 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5426 const SCEV *One = getOne(I->getType()); 5427 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5428 const SCEV *LA = getSCEV(TrueVal); 5429 const SCEV *RA = getSCEV(FalseVal); 5430 const SCEV *LDiff = getMinusSCEV(LA, LS); 5431 const SCEV *RDiff = getMinusSCEV(RA, One); 5432 if (LDiff == RDiff) 5433 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5434 } 5435 break; 5436 case ICmpInst::ICMP_EQ: 5437 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5438 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5439 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5440 const SCEV *One = getOne(I->getType()); 5441 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5442 const SCEV *LA = getSCEV(TrueVal); 5443 const SCEV *RA = getSCEV(FalseVal); 5444 const SCEV *LDiff = getMinusSCEV(LA, One); 5445 const SCEV *RDiff = getMinusSCEV(RA, LS); 5446 if (LDiff == RDiff) 5447 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5448 } 5449 break; 5450 default: 5451 break; 5452 } 5453 5454 return getUnknown(I); 5455 } 5456 5457 /// Expand GEP instructions into add and multiply operations. This allows them 5458 /// to be analyzed by regular SCEV code. 5459 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5460 // Don't attempt to analyze GEPs over unsized objects. 5461 if (!GEP->getSourceElementType()->isSized()) 5462 return getUnknown(GEP); 5463 5464 SmallVector<const SCEV *, 4> IndexExprs; 5465 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5466 IndexExprs.push_back(getSCEV(*Index)); 5467 return getGEPExpr(GEP, IndexExprs); 5468 } 5469 5470 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5471 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5472 return C->getAPInt().countTrailingZeros(); 5473 5474 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5475 return GetMinTrailingZeros(I->getOperand()); 5476 5477 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5478 return std::min(GetMinTrailingZeros(T->getOperand()), 5479 (uint32_t)getTypeSizeInBits(T->getType())); 5480 5481 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5482 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5483 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5484 ? getTypeSizeInBits(E->getType()) 5485 : OpRes; 5486 } 5487 5488 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5489 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5490 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5491 ? getTypeSizeInBits(E->getType()) 5492 : OpRes; 5493 } 5494 5495 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5496 // The result is the min of all operands results. 5497 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5498 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5500 return MinOpRes; 5501 } 5502 5503 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5504 // The result is the sum of all operands results. 5505 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5506 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5507 for (unsigned i = 1, e = M->getNumOperands(); 5508 SumOpRes != BitWidth && i != e; ++i) 5509 SumOpRes = 5510 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5511 return SumOpRes; 5512 } 5513 5514 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5515 // The result is the min of all operands results. 5516 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5517 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5518 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5519 return MinOpRes; 5520 } 5521 5522 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5523 // The result is the min of all operands results. 5524 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5525 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5526 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5527 return MinOpRes; 5528 } 5529 5530 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5531 // The result is the min of all operands results. 5532 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5533 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5534 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5535 return MinOpRes; 5536 } 5537 5538 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5539 // For a SCEVUnknown, ask ValueTracking. 5540 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5541 return Known.countMinTrailingZeros(); 5542 } 5543 5544 // SCEVUDivExpr 5545 return 0; 5546 } 5547 5548 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5549 auto I = MinTrailingZerosCache.find(S); 5550 if (I != MinTrailingZerosCache.end()) 5551 return I->second; 5552 5553 uint32_t Result = GetMinTrailingZerosImpl(S); 5554 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5555 assert(InsertPair.second && "Should insert a new key"); 5556 return InsertPair.first->second; 5557 } 5558 5559 /// Helper method to assign a range to V from metadata present in the IR. 5560 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5561 if (Instruction *I = dyn_cast<Instruction>(V)) 5562 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5563 return getConstantRangeFromMetadata(*MD); 5564 5565 return None; 5566 } 5567 5568 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5569 SCEV::NoWrapFlags Flags) { 5570 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5571 AddRec->setNoWrapFlags(Flags); 5572 UnsignedRanges.erase(AddRec); 5573 SignedRanges.erase(AddRec); 5574 } 5575 } 5576 5577 /// Determine the range for a particular SCEV. If SignHint is 5578 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5579 /// with a "cleaner" unsigned (resp. signed) representation. 5580 const ConstantRange & 5581 ScalarEvolution::getRangeRef(const SCEV *S, 5582 ScalarEvolution::RangeSignHint SignHint) { 5583 DenseMap<const SCEV *, ConstantRange> &Cache = 5584 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5585 : SignedRanges; 5586 ConstantRange::PreferredRangeType RangeType = 5587 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5588 ? ConstantRange::Unsigned : ConstantRange::Signed; 5589 5590 // See if we've computed this range already. 5591 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5592 if (I != Cache.end()) 5593 return I->second; 5594 5595 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5596 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5597 5598 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5599 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5600 using OBO = OverflowingBinaryOperator; 5601 5602 // If the value has known zeros, the maximum value will have those known zeros 5603 // as well. 5604 uint32_t TZ = GetMinTrailingZeros(S); 5605 if (TZ != 0) { 5606 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5607 ConservativeResult = 5608 ConstantRange(APInt::getMinValue(BitWidth), 5609 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5610 else 5611 ConservativeResult = ConstantRange( 5612 APInt::getSignedMinValue(BitWidth), 5613 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5614 } 5615 5616 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5617 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5618 unsigned WrapType = OBO::AnyWrap; 5619 if (Add->hasNoSignedWrap()) 5620 WrapType |= OBO::NoSignedWrap; 5621 if (Add->hasNoUnsignedWrap()) 5622 WrapType |= OBO::NoUnsignedWrap; 5623 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5624 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5625 WrapType, RangeType); 5626 return setRange(Add, SignHint, 5627 ConservativeResult.intersectWith(X, RangeType)); 5628 } 5629 5630 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5631 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5632 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5633 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5634 return setRange(Mul, SignHint, 5635 ConservativeResult.intersectWith(X, RangeType)); 5636 } 5637 5638 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5639 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5640 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5641 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5642 return setRange(SMax, SignHint, 5643 ConservativeResult.intersectWith(X, RangeType)); 5644 } 5645 5646 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5647 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5648 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5649 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5650 return setRange(UMax, SignHint, 5651 ConservativeResult.intersectWith(X, RangeType)); 5652 } 5653 5654 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5655 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5656 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5657 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5658 return setRange(SMin, SignHint, 5659 ConservativeResult.intersectWith(X, RangeType)); 5660 } 5661 5662 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5663 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5664 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5665 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5666 return setRange(UMin, SignHint, 5667 ConservativeResult.intersectWith(X, RangeType)); 5668 } 5669 5670 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5671 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5672 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5673 return setRange(UDiv, SignHint, 5674 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5675 } 5676 5677 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5678 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5679 return setRange(ZExt, SignHint, 5680 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5681 RangeType)); 5682 } 5683 5684 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5685 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5686 return setRange(SExt, SignHint, 5687 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5688 RangeType)); 5689 } 5690 5691 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5692 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5693 return setRange(PtrToInt, SignHint, X); 5694 } 5695 5696 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5697 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5698 return setRange(Trunc, SignHint, 5699 ConservativeResult.intersectWith(X.truncate(BitWidth), 5700 RangeType)); 5701 } 5702 5703 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5704 // If there's no unsigned wrap, the value will never be less than its 5705 // initial value. 5706 if (AddRec->hasNoUnsignedWrap()) { 5707 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5708 if (!UnsignedMinValue.isNullValue()) 5709 ConservativeResult = ConservativeResult.intersectWith( 5710 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5711 } 5712 5713 // If there's no signed wrap, and all the operands except initial value have 5714 // the same sign or zero, the value won't ever be: 5715 // 1: smaller than initial value if operands are non negative, 5716 // 2: bigger than initial value if operands are non positive. 5717 // For both cases, value can not cross signed min/max boundary. 5718 if (AddRec->hasNoSignedWrap()) { 5719 bool AllNonNeg = true; 5720 bool AllNonPos = true; 5721 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5722 if (!isKnownNonNegative(AddRec->getOperand(i))) 5723 AllNonNeg = false; 5724 if (!isKnownNonPositive(AddRec->getOperand(i))) 5725 AllNonPos = false; 5726 } 5727 if (AllNonNeg) 5728 ConservativeResult = ConservativeResult.intersectWith( 5729 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5730 APInt::getSignedMinValue(BitWidth)), 5731 RangeType); 5732 else if (AllNonPos) 5733 ConservativeResult = ConservativeResult.intersectWith( 5734 ConstantRange::getNonEmpty( 5735 APInt::getSignedMinValue(BitWidth), 5736 getSignedRangeMax(AddRec->getStart()) + 1), 5737 RangeType); 5738 } 5739 5740 // TODO: non-affine addrec 5741 if (AddRec->isAffine()) { 5742 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5743 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5744 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5745 auto RangeFromAffine = getRangeForAffineAR( 5746 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5747 BitWidth); 5748 ConservativeResult = 5749 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5750 5751 auto RangeFromFactoring = getRangeViaFactoring( 5752 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5753 BitWidth); 5754 ConservativeResult = 5755 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5756 } 5757 5758 // Now try symbolic BE count and more powerful methods. 5759 if (UseExpensiveRangeSharpening) { 5760 const SCEV *SymbolicMaxBECount = 5761 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 5762 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 5763 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5764 AddRec->hasNoSelfWrap()) { 5765 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5766 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 5767 ConservativeResult = 5768 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5769 } 5770 } 5771 } 5772 5773 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5774 } 5775 5776 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5777 // Check if the IR explicitly contains !range metadata. 5778 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5779 if (MDRange.hasValue()) 5780 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5781 RangeType); 5782 5783 // Split here to avoid paying the compile-time cost of calling both 5784 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5785 // if needed. 5786 const DataLayout &DL = getDataLayout(); 5787 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5788 // For a SCEVUnknown, ask ValueTracking. 5789 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5790 if (Known.getBitWidth() != BitWidth) 5791 Known = Known.zextOrTrunc(BitWidth); 5792 // If Known does not result in full-set, intersect with it. 5793 if (Known.getMinValue() != Known.getMaxValue() + 1) 5794 ConservativeResult = ConservativeResult.intersectWith( 5795 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5796 RangeType); 5797 } else { 5798 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5799 "generalize as needed!"); 5800 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5801 // If the pointer size is larger than the index size type, this can cause 5802 // NS to be larger than BitWidth. So compensate for this. 5803 if (U->getType()->isPointerTy()) { 5804 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5805 int ptrIdxDiff = ptrSize - BitWidth; 5806 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5807 NS -= ptrIdxDiff; 5808 } 5809 5810 if (NS > 1) 5811 ConservativeResult = ConservativeResult.intersectWith( 5812 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5813 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5814 RangeType); 5815 } 5816 5817 // A range of Phi is a subset of union of all ranges of its input. 5818 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5819 // Make sure that we do not run over cycled Phis. 5820 if (PendingPhiRanges.insert(Phi).second) { 5821 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5822 for (auto &Op : Phi->operands()) { 5823 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5824 RangeFromOps = RangeFromOps.unionWith(OpRange); 5825 // No point to continue if we already have a full set. 5826 if (RangeFromOps.isFullSet()) 5827 break; 5828 } 5829 ConservativeResult = 5830 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5831 bool Erased = PendingPhiRanges.erase(Phi); 5832 assert(Erased && "Failed to erase Phi properly?"); 5833 (void) Erased; 5834 } 5835 } 5836 5837 return setRange(U, SignHint, std::move(ConservativeResult)); 5838 } 5839 5840 return setRange(S, SignHint, std::move(ConservativeResult)); 5841 } 5842 5843 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5844 // values that the expression can take. Initially, the expression has a value 5845 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5846 // argument defines if we treat Step as signed or unsigned. 5847 static ConstantRange getRangeForAffineARHelper(APInt Step, 5848 const ConstantRange &StartRange, 5849 const APInt &MaxBECount, 5850 unsigned BitWidth, bool Signed) { 5851 // If either Step or MaxBECount is 0, then the expression won't change, and we 5852 // just need to return the initial range. 5853 if (Step == 0 || MaxBECount == 0) 5854 return StartRange; 5855 5856 // If we don't know anything about the initial value (i.e. StartRange is 5857 // FullRange), then we don't know anything about the final range either. 5858 // Return FullRange. 5859 if (StartRange.isFullSet()) 5860 return ConstantRange::getFull(BitWidth); 5861 5862 // If Step is signed and negative, then we use its absolute value, but we also 5863 // note that we're moving in the opposite direction. 5864 bool Descending = Signed && Step.isNegative(); 5865 5866 if (Signed) 5867 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5868 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5869 // This equations hold true due to the well-defined wrap-around behavior of 5870 // APInt. 5871 Step = Step.abs(); 5872 5873 // Check if Offset is more than full span of BitWidth. If it is, the 5874 // expression is guaranteed to overflow. 5875 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5876 return ConstantRange::getFull(BitWidth); 5877 5878 // Offset is by how much the expression can change. Checks above guarantee no 5879 // overflow here. 5880 APInt Offset = Step * MaxBECount; 5881 5882 // Minimum value of the final range will match the minimal value of StartRange 5883 // if the expression is increasing and will be decreased by Offset otherwise. 5884 // Maximum value of the final range will match the maximal value of StartRange 5885 // if the expression is decreasing and will be increased by Offset otherwise. 5886 APInt StartLower = StartRange.getLower(); 5887 APInt StartUpper = StartRange.getUpper() - 1; 5888 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5889 : (StartUpper + std::move(Offset)); 5890 5891 // It's possible that the new minimum/maximum value will fall into the initial 5892 // range (due to wrap around). This means that the expression can take any 5893 // value in this bitwidth, and we have to return full range. 5894 if (StartRange.contains(MovedBoundary)) 5895 return ConstantRange::getFull(BitWidth); 5896 5897 APInt NewLower = 5898 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5899 APInt NewUpper = 5900 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5901 NewUpper += 1; 5902 5903 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5904 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5905 } 5906 5907 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5908 const SCEV *Step, 5909 const SCEV *MaxBECount, 5910 unsigned BitWidth) { 5911 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5912 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5913 "Precondition!"); 5914 5915 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5916 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5917 5918 // First, consider step signed. 5919 ConstantRange StartSRange = getSignedRange(Start); 5920 ConstantRange StepSRange = getSignedRange(Step); 5921 5922 // If Step can be both positive and negative, we need to find ranges for the 5923 // maximum absolute step values in both directions and union them. 5924 ConstantRange SR = 5925 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5926 MaxBECountValue, BitWidth, /* Signed = */ true); 5927 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5928 StartSRange, MaxBECountValue, 5929 BitWidth, /* Signed = */ true)); 5930 5931 // Next, consider step unsigned. 5932 ConstantRange UR = getRangeForAffineARHelper( 5933 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5934 MaxBECountValue, BitWidth, /* Signed = */ false); 5935 5936 // Finally, intersect signed and unsigned ranges. 5937 return SR.intersectWith(UR, ConstantRange::Smallest); 5938 } 5939 5940 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 5941 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 5942 ScalarEvolution::RangeSignHint SignHint) { 5943 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 5944 assert(AddRec->hasNoSelfWrap() && 5945 "This only works for non-self-wrapping AddRecs!"); 5946 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 5947 const SCEV *Step = AddRec->getStepRecurrence(*this); 5948 // Only deal with constant step to save compile time. 5949 if (!isa<SCEVConstant>(Step)) 5950 return ConstantRange::getFull(BitWidth); 5951 // Let's make sure that we can prove that we do not self-wrap during 5952 // MaxBECount iterations. We need this because MaxBECount is a maximum 5953 // iteration count estimate, and we might infer nw from some exit for which we 5954 // do not know max exit count (or any other side reasoning). 5955 // TODO: Turn into assert at some point. 5956 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 5957 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 5958 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 5959 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 5960 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 5961 MaxItersWithoutWrap)) 5962 return ConstantRange::getFull(BitWidth); 5963 5964 ICmpInst::Predicate LEPred = 5965 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 5966 ICmpInst::Predicate GEPred = 5967 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 5968 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 5969 5970 // We know that there is no self-wrap. Let's take Start and End values and 5971 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 5972 // the iteration. They either lie inside the range [Min(Start, End), 5973 // Max(Start, End)] or outside it: 5974 // 5975 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 5976 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 5977 // 5978 // No self wrap flag guarantees that the intermediate values cannot be BOTH 5979 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 5980 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 5981 // Start <= End and step is positive, or Start >= End and step is negative. 5982 const SCEV *Start = AddRec->getStart(); 5983 ConstantRange StartRange = getRangeRef(Start, SignHint); 5984 ConstantRange EndRange = getRangeRef(End, SignHint); 5985 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 5986 // If they already cover full iteration space, we will know nothing useful 5987 // even if we prove what we want to prove. 5988 if (RangeBetween.isFullSet()) 5989 return RangeBetween; 5990 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 5991 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 5992 : RangeBetween.isWrappedSet(); 5993 if (IsWrappedSet) 5994 return ConstantRange::getFull(BitWidth); 5995 5996 if (isKnownPositive(Step) && 5997 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 5998 return RangeBetween; 5999 else if (isKnownNegative(Step) && 6000 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6001 return RangeBetween; 6002 return ConstantRange::getFull(BitWidth); 6003 } 6004 6005 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6006 const SCEV *Step, 6007 const SCEV *MaxBECount, 6008 unsigned BitWidth) { 6009 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6010 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6011 6012 struct SelectPattern { 6013 Value *Condition = nullptr; 6014 APInt TrueValue; 6015 APInt FalseValue; 6016 6017 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6018 const SCEV *S) { 6019 Optional<unsigned> CastOp; 6020 APInt Offset(BitWidth, 0); 6021 6022 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6023 "Should be!"); 6024 6025 // Peel off a constant offset: 6026 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6027 // In the future we could consider being smarter here and handle 6028 // {Start+Step,+,Step} too. 6029 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6030 return; 6031 6032 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6033 S = SA->getOperand(1); 6034 } 6035 6036 // Peel off a cast operation 6037 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6038 CastOp = SCast->getSCEVType(); 6039 S = SCast->getOperand(); 6040 } 6041 6042 using namespace llvm::PatternMatch; 6043 6044 auto *SU = dyn_cast<SCEVUnknown>(S); 6045 const APInt *TrueVal, *FalseVal; 6046 if (!SU || 6047 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6048 m_APInt(FalseVal)))) { 6049 Condition = nullptr; 6050 return; 6051 } 6052 6053 TrueValue = *TrueVal; 6054 FalseValue = *FalseVal; 6055 6056 // Re-apply the cast we peeled off earlier 6057 if (CastOp.hasValue()) 6058 switch (*CastOp) { 6059 default: 6060 llvm_unreachable("Unknown SCEV cast type!"); 6061 6062 case scTruncate: 6063 TrueValue = TrueValue.trunc(BitWidth); 6064 FalseValue = FalseValue.trunc(BitWidth); 6065 break; 6066 case scZeroExtend: 6067 TrueValue = TrueValue.zext(BitWidth); 6068 FalseValue = FalseValue.zext(BitWidth); 6069 break; 6070 case scSignExtend: 6071 TrueValue = TrueValue.sext(BitWidth); 6072 FalseValue = FalseValue.sext(BitWidth); 6073 break; 6074 } 6075 6076 // Re-apply the constant offset we peeled off earlier 6077 TrueValue += Offset; 6078 FalseValue += Offset; 6079 } 6080 6081 bool isRecognized() { return Condition != nullptr; } 6082 }; 6083 6084 SelectPattern StartPattern(*this, BitWidth, Start); 6085 if (!StartPattern.isRecognized()) 6086 return ConstantRange::getFull(BitWidth); 6087 6088 SelectPattern StepPattern(*this, BitWidth, Step); 6089 if (!StepPattern.isRecognized()) 6090 return ConstantRange::getFull(BitWidth); 6091 6092 if (StartPattern.Condition != StepPattern.Condition) { 6093 // We don't handle this case today; but we could, by considering four 6094 // possibilities below instead of two. I'm not sure if there are cases where 6095 // that will help over what getRange already does, though. 6096 return ConstantRange::getFull(BitWidth); 6097 } 6098 6099 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6100 // construct arbitrary general SCEV expressions here. This function is called 6101 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6102 // say) can end up caching a suboptimal value. 6103 6104 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6105 // C2352 and C2512 (otherwise it isn't needed). 6106 6107 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6108 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6109 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6110 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6111 6112 ConstantRange TrueRange = 6113 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6114 ConstantRange FalseRange = 6115 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6116 6117 return TrueRange.unionWith(FalseRange); 6118 } 6119 6120 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6121 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6122 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6123 6124 // Return early if there are no flags to propagate to the SCEV. 6125 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6126 if (BinOp->hasNoUnsignedWrap()) 6127 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6128 if (BinOp->hasNoSignedWrap()) 6129 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6130 if (Flags == SCEV::FlagAnyWrap) 6131 return SCEV::FlagAnyWrap; 6132 6133 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6134 } 6135 6136 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6137 // Here we check that I is in the header of the innermost loop containing I, 6138 // since we only deal with instructions in the loop header. The actual loop we 6139 // need to check later will come from an add recurrence, but getting that 6140 // requires computing the SCEV of the operands, which can be expensive. This 6141 // check we can do cheaply to rule out some cases early. 6142 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6143 if (InnermostContainingLoop == nullptr || 6144 InnermostContainingLoop->getHeader() != I->getParent()) 6145 return false; 6146 6147 // Only proceed if we can prove that I does not yield poison. 6148 if (!programUndefinedIfPoison(I)) 6149 return false; 6150 6151 // At this point we know that if I is executed, then it does not wrap 6152 // according to at least one of NSW or NUW. If I is not executed, then we do 6153 // not know if the calculation that I represents would wrap. Multiple 6154 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6155 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6156 // derived from other instructions that map to the same SCEV. We cannot make 6157 // that guarantee for cases where I is not executed. So we need to find the 6158 // loop that I is considered in relation to and prove that I is executed for 6159 // every iteration of that loop. That implies that the value that I 6160 // calculates does not wrap anywhere in the loop, so then we can apply the 6161 // flags to the SCEV. 6162 // 6163 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6164 // from different loops, so that we know which loop to prove that I is 6165 // executed in. 6166 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6167 // I could be an extractvalue from a call to an overflow intrinsic. 6168 // TODO: We can do better here in some cases. 6169 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6170 return false; 6171 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6172 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6173 bool AllOtherOpsLoopInvariant = true; 6174 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6175 ++OtherOpIndex) { 6176 if (OtherOpIndex != OpIndex) { 6177 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6178 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6179 AllOtherOpsLoopInvariant = false; 6180 break; 6181 } 6182 } 6183 } 6184 if (AllOtherOpsLoopInvariant && 6185 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6186 return true; 6187 } 6188 } 6189 return false; 6190 } 6191 6192 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6193 // If we know that \c I can never be poison period, then that's enough. 6194 if (isSCEVExprNeverPoison(I)) 6195 return true; 6196 6197 // For an add recurrence specifically, we assume that infinite loops without 6198 // side effects are undefined behavior, and then reason as follows: 6199 // 6200 // If the add recurrence is poison in any iteration, it is poison on all 6201 // future iterations (since incrementing poison yields poison). If the result 6202 // of the add recurrence is fed into the loop latch condition and the loop 6203 // does not contain any throws or exiting blocks other than the latch, we now 6204 // have the ability to "choose" whether the backedge is taken or not (by 6205 // choosing a sufficiently evil value for the poison feeding into the branch) 6206 // for every iteration including and after the one in which \p I first became 6207 // poison. There are two possibilities (let's call the iteration in which \p 6208 // I first became poison as K): 6209 // 6210 // 1. In the set of iterations including and after K, the loop body executes 6211 // no side effects. In this case executing the backege an infinte number 6212 // of times will yield undefined behavior. 6213 // 6214 // 2. In the set of iterations including and after K, the loop body executes 6215 // at least one side effect. In this case, that specific instance of side 6216 // effect is control dependent on poison, which also yields undefined 6217 // behavior. 6218 6219 auto *ExitingBB = L->getExitingBlock(); 6220 auto *LatchBB = L->getLoopLatch(); 6221 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6222 return false; 6223 6224 SmallPtrSet<const Instruction *, 16> Pushed; 6225 SmallVector<const Instruction *, 8> PoisonStack; 6226 6227 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6228 // things that are known to be poison under that assumption go on the 6229 // PoisonStack. 6230 Pushed.insert(I); 6231 PoisonStack.push_back(I); 6232 6233 bool LatchControlDependentOnPoison = false; 6234 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6235 const Instruction *Poison = PoisonStack.pop_back_val(); 6236 6237 for (auto *PoisonUser : Poison->users()) { 6238 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6239 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6240 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6241 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6242 assert(BI->isConditional() && "Only possibility!"); 6243 if (BI->getParent() == LatchBB) { 6244 LatchControlDependentOnPoison = true; 6245 break; 6246 } 6247 } 6248 } 6249 } 6250 6251 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6252 } 6253 6254 ScalarEvolution::LoopProperties 6255 ScalarEvolution::getLoopProperties(const Loop *L) { 6256 using LoopProperties = ScalarEvolution::LoopProperties; 6257 6258 auto Itr = LoopPropertiesCache.find(L); 6259 if (Itr == LoopPropertiesCache.end()) { 6260 auto HasSideEffects = [](Instruction *I) { 6261 if (auto *SI = dyn_cast<StoreInst>(I)) 6262 return !SI->isSimple(); 6263 6264 return I->mayHaveSideEffects(); 6265 }; 6266 6267 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6268 /*HasNoSideEffects*/ true}; 6269 6270 for (auto *BB : L->getBlocks()) 6271 for (auto &I : *BB) { 6272 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6273 LP.HasNoAbnormalExits = false; 6274 if (HasSideEffects(&I)) 6275 LP.HasNoSideEffects = false; 6276 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6277 break; // We're already as pessimistic as we can get. 6278 } 6279 6280 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6281 assert(InsertPair.second && "We just checked!"); 6282 Itr = InsertPair.first; 6283 } 6284 6285 return Itr->second; 6286 } 6287 6288 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6289 if (!isSCEVable(V->getType())) 6290 return getUnknown(V); 6291 6292 if (Instruction *I = dyn_cast<Instruction>(V)) { 6293 // Don't attempt to analyze instructions in blocks that aren't 6294 // reachable. Such instructions don't matter, and they aren't required 6295 // to obey basic rules for definitions dominating uses which this 6296 // analysis depends on. 6297 if (!DT.isReachableFromEntry(I->getParent())) 6298 return getUnknown(UndefValue::get(V->getType())); 6299 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6300 return getConstant(CI); 6301 else if (isa<ConstantPointerNull>(V)) 6302 // FIXME: we shouldn't special-case null pointer constant. 6303 return getZero(V->getType()); 6304 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6305 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6306 else if (!isa<ConstantExpr>(V)) 6307 return getUnknown(V); 6308 6309 Operator *U = cast<Operator>(V); 6310 if (auto BO = MatchBinaryOp(U, DT)) { 6311 switch (BO->Opcode) { 6312 case Instruction::Add: { 6313 // The simple thing to do would be to just call getSCEV on both operands 6314 // and call getAddExpr with the result. However if we're looking at a 6315 // bunch of things all added together, this can be quite inefficient, 6316 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6317 // Instead, gather up all the operands and make a single getAddExpr call. 6318 // LLVM IR canonical form means we need only traverse the left operands. 6319 SmallVector<const SCEV *, 4> AddOps; 6320 do { 6321 if (BO->Op) { 6322 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6323 AddOps.push_back(OpSCEV); 6324 break; 6325 } 6326 6327 // If a NUW or NSW flag can be applied to the SCEV for this 6328 // addition, then compute the SCEV for this addition by itself 6329 // with a separate call to getAddExpr. We need to do that 6330 // instead of pushing the operands of the addition onto AddOps, 6331 // since the flags are only known to apply to this particular 6332 // addition - they may not apply to other additions that can be 6333 // formed with operands from AddOps. 6334 const SCEV *RHS = getSCEV(BO->RHS); 6335 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6336 if (Flags != SCEV::FlagAnyWrap) { 6337 const SCEV *LHS = getSCEV(BO->LHS); 6338 if (BO->Opcode == Instruction::Sub) 6339 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6340 else 6341 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6342 break; 6343 } 6344 } 6345 6346 if (BO->Opcode == Instruction::Sub) 6347 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6348 else 6349 AddOps.push_back(getSCEV(BO->RHS)); 6350 6351 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6352 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6353 NewBO->Opcode != Instruction::Sub)) { 6354 AddOps.push_back(getSCEV(BO->LHS)); 6355 break; 6356 } 6357 BO = NewBO; 6358 } while (true); 6359 6360 return getAddExpr(AddOps); 6361 } 6362 6363 case Instruction::Mul: { 6364 SmallVector<const SCEV *, 4> MulOps; 6365 do { 6366 if (BO->Op) { 6367 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6368 MulOps.push_back(OpSCEV); 6369 break; 6370 } 6371 6372 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6373 if (Flags != SCEV::FlagAnyWrap) { 6374 MulOps.push_back( 6375 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6376 break; 6377 } 6378 } 6379 6380 MulOps.push_back(getSCEV(BO->RHS)); 6381 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6382 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6383 MulOps.push_back(getSCEV(BO->LHS)); 6384 break; 6385 } 6386 BO = NewBO; 6387 } while (true); 6388 6389 return getMulExpr(MulOps); 6390 } 6391 case Instruction::UDiv: 6392 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6393 case Instruction::URem: 6394 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6395 case Instruction::Sub: { 6396 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6397 if (BO->Op) 6398 Flags = getNoWrapFlagsFromUB(BO->Op); 6399 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6400 } 6401 case Instruction::And: 6402 // For an expression like x&255 that merely masks off the high bits, 6403 // use zext(trunc(x)) as the SCEV expression. 6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6405 if (CI->isZero()) 6406 return getSCEV(BO->RHS); 6407 if (CI->isMinusOne()) 6408 return getSCEV(BO->LHS); 6409 const APInt &A = CI->getValue(); 6410 6411 // Instcombine's ShrinkDemandedConstant may strip bits out of 6412 // constants, obscuring what would otherwise be a low-bits mask. 6413 // Use computeKnownBits to compute what ShrinkDemandedConstant 6414 // knew about to reconstruct a low-bits mask value. 6415 unsigned LZ = A.countLeadingZeros(); 6416 unsigned TZ = A.countTrailingZeros(); 6417 unsigned BitWidth = A.getBitWidth(); 6418 KnownBits Known(BitWidth); 6419 computeKnownBits(BO->LHS, Known, getDataLayout(), 6420 0, &AC, nullptr, &DT); 6421 6422 APInt EffectiveMask = 6423 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6424 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6425 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6426 const SCEV *LHS = getSCEV(BO->LHS); 6427 const SCEV *ShiftedLHS = nullptr; 6428 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6429 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6430 // For an expression like (x * 8) & 8, simplify the multiply. 6431 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6432 unsigned GCD = std::min(MulZeros, TZ); 6433 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6434 SmallVector<const SCEV*, 4> MulOps; 6435 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6436 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6437 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6438 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6439 } 6440 } 6441 if (!ShiftedLHS) 6442 ShiftedLHS = getUDivExpr(LHS, MulCount); 6443 return getMulExpr( 6444 getZeroExtendExpr( 6445 getTruncateExpr(ShiftedLHS, 6446 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6447 BO->LHS->getType()), 6448 MulCount); 6449 } 6450 } 6451 break; 6452 6453 case Instruction::Or: 6454 // If the RHS of the Or is a constant, we may have something like: 6455 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6456 // optimizations will transparently handle this case. 6457 // 6458 // In order for this transformation to be safe, the LHS must be of the 6459 // form X*(2^n) and the Or constant must be less than 2^n. 6460 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6461 const SCEV *LHS = getSCEV(BO->LHS); 6462 const APInt &CIVal = CI->getValue(); 6463 if (GetMinTrailingZeros(LHS) >= 6464 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6465 // Build a plain add SCEV. 6466 return getAddExpr(LHS, getSCEV(CI), 6467 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6468 } 6469 } 6470 break; 6471 6472 case Instruction::Xor: 6473 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6474 // If the RHS of xor is -1, then this is a not operation. 6475 if (CI->isMinusOne()) 6476 return getNotSCEV(getSCEV(BO->LHS)); 6477 6478 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6479 // This is a variant of the check for xor with -1, and it handles 6480 // the case where instcombine has trimmed non-demanded bits out 6481 // of an xor with -1. 6482 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6483 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6484 if (LBO->getOpcode() == Instruction::And && 6485 LCI->getValue() == CI->getValue()) 6486 if (const SCEVZeroExtendExpr *Z = 6487 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6488 Type *UTy = BO->LHS->getType(); 6489 const SCEV *Z0 = Z->getOperand(); 6490 Type *Z0Ty = Z0->getType(); 6491 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6492 6493 // If C is a low-bits mask, the zero extend is serving to 6494 // mask off the high bits. Complement the operand and 6495 // re-apply the zext. 6496 if (CI->getValue().isMask(Z0TySize)) 6497 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6498 6499 // If C is a single bit, it may be in the sign-bit position 6500 // before the zero-extend. In this case, represent the xor 6501 // using an add, which is equivalent, and re-apply the zext. 6502 APInt Trunc = CI->getValue().trunc(Z0TySize); 6503 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6504 Trunc.isSignMask()) 6505 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6506 UTy); 6507 } 6508 } 6509 break; 6510 6511 case Instruction::Shl: 6512 // Turn shift left of a constant amount into a multiply. 6513 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6514 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6515 6516 // If the shift count is not less than the bitwidth, the result of 6517 // the shift is undefined. Don't try to analyze it, because the 6518 // resolution chosen here may differ from the resolution chosen in 6519 // other parts of the compiler. 6520 if (SA->getValue().uge(BitWidth)) 6521 break; 6522 6523 // We can safely preserve the nuw flag in all cases. It's also safe to 6524 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6525 // requires special handling. It can be preserved as long as we're not 6526 // left shifting by bitwidth - 1. 6527 auto Flags = SCEV::FlagAnyWrap; 6528 if (BO->Op) { 6529 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6530 if ((MulFlags & SCEV::FlagNSW) && 6531 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6532 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6533 if (MulFlags & SCEV::FlagNUW) 6534 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6535 } 6536 6537 Constant *X = ConstantInt::get( 6538 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6539 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6540 } 6541 break; 6542 6543 case Instruction::AShr: { 6544 // AShr X, C, where C is a constant. 6545 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6546 if (!CI) 6547 break; 6548 6549 Type *OuterTy = BO->LHS->getType(); 6550 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6551 // If the shift count is not less than the bitwidth, the result of 6552 // the shift is undefined. Don't try to analyze it, because the 6553 // resolution chosen here may differ from the resolution chosen in 6554 // other parts of the compiler. 6555 if (CI->getValue().uge(BitWidth)) 6556 break; 6557 6558 if (CI->isZero()) 6559 return getSCEV(BO->LHS); // shift by zero --> noop 6560 6561 uint64_t AShrAmt = CI->getZExtValue(); 6562 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6563 6564 Operator *L = dyn_cast<Operator>(BO->LHS); 6565 if (L && L->getOpcode() == Instruction::Shl) { 6566 // X = Shl A, n 6567 // Y = AShr X, m 6568 // Both n and m are constant. 6569 6570 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6571 if (L->getOperand(1) == BO->RHS) 6572 // For a two-shift sext-inreg, i.e. n = m, 6573 // use sext(trunc(x)) as the SCEV expression. 6574 return getSignExtendExpr( 6575 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6576 6577 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6578 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6579 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6580 if (ShlAmt > AShrAmt) { 6581 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6582 // expression. We already checked that ShlAmt < BitWidth, so 6583 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6584 // ShlAmt - AShrAmt < Amt. 6585 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6586 ShlAmt - AShrAmt); 6587 return getSignExtendExpr( 6588 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6589 getConstant(Mul)), OuterTy); 6590 } 6591 } 6592 } 6593 if (BO->IsExact) { 6594 // Given exact arithmetic in-bounds right-shift by a constant, 6595 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6596 const SCEV *X = getSCEV(BO->LHS); 6597 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6598 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6599 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6600 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6601 } 6602 break; 6603 } 6604 } 6605 } 6606 6607 switch (U->getOpcode()) { 6608 case Instruction::Trunc: 6609 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6610 6611 case Instruction::ZExt: 6612 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6613 6614 case Instruction::SExt: 6615 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6616 // The NSW flag of a subtract does not always survive the conversion to 6617 // A + (-1)*B. By pushing sign extension onto its operands we are much 6618 // more likely to preserve NSW and allow later AddRec optimisations. 6619 // 6620 // NOTE: This is effectively duplicating this logic from getSignExtend: 6621 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6622 // but by that point the NSW information has potentially been lost. 6623 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6624 Type *Ty = U->getType(); 6625 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6626 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6627 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6628 } 6629 } 6630 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6631 6632 case Instruction::BitCast: 6633 // BitCasts are no-op casts so we just eliminate the cast. 6634 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6635 return getSCEV(U->getOperand(0)); 6636 break; 6637 6638 case Instruction::PtrToInt: { 6639 // Pointer to integer cast is straight-forward, so do model it. 6640 Value *Ptr = U->getOperand(0); 6641 const SCEV *Op = getSCEV(Ptr); 6642 Type *DstIntTy = U->getType(); 6643 // SCEV doesn't have constant pointer expression type, but it supports 6644 // nullptr constant (and only that one), which is modelled in SCEV as a 6645 // zero integer constant. So just skip the ptrtoint cast for constants. 6646 if (isa<SCEVConstant>(Op)) 6647 return getTruncateOrZeroExtend(Op, DstIntTy); 6648 Type *PtrTy = Ptr->getType(); 6649 Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy); 6650 // But only if effective SCEV (integer) type is wide enough to represent 6651 // all possible pointer values. 6652 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) != 6653 getDataLayout().getTypeSizeInBits(IntPtrTy)) 6654 return getUnknown(V); 6655 return getPtrToIntExpr(Op, DstIntTy); 6656 } 6657 case Instruction::IntToPtr: 6658 // Just don't deal with inttoptr casts. 6659 return getUnknown(V); 6660 6661 case Instruction::SDiv: 6662 // If both operands are non-negative, this is just an udiv. 6663 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6664 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6665 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6666 break; 6667 6668 case Instruction::SRem: 6669 // If both operands are non-negative, this is just an urem. 6670 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6671 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6672 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6673 break; 6674 6675 case Instruction::GetElementPtr: 6676 return createNodeForGEP(cast<GEPOperator>(U)); 6677 6678 case Instruction::PHI: 6679 return createNodeForPHI(cast<PHINode>(U)); 6680 6681 case Instruction::Select: 6682 // U can also be a select constant expr, which let fall through. Since 6683 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6684 // constant expressions cannot have instructions as operands, we'd have 6685 // returned getUnknown for a select constant expressions anyway. 6686 if (isa<Instruction>(U)) 6687 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6688 U->getOperand(1), U->getOperand(2)); 6689 break; 6690 6691 case Instruction::Call: 6692 case Instruction::Invoke: 6693 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6694 return getSCEV(RV); 6695 6696 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6697 switch (II->getIntrinsicID()) { 6698 case Intrinsic::abs: 6699 return getAbsExpr( 6700 getSCEV(II->getArgOperand(0)), 6701 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6702 case Intrinsic::umax: 6703 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6704 getSCEV(II->getArgOperand(1))); 6705 case Intrinsic::umin: 6706 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6707 getSCEV(II->getArgOperand(1))); 6708 case Intrinsic::smax: 6709 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6710 getSCEV(II->getArgOperand(1))); 6711 case Intrinsic::smin: 6712 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6713 getSCEV(II->getArgOperand(1))); 6714 case Intrinsic::usub_sat: { 6715 const SCEV *X = getSCEV(II->getArgOperand(0)); 6716 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6717 const SCEV *ClampedY = getUMinExpr(X, Y); 6718 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6719 } 6720 case Intrinsic::uadd_sat: { 6721 const SCEV *X = getSCEV(II->getArgOperand(0)); 6722 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6723 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6724 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6725 } 6726 case Intrinsic::start_loop_iterations: 6727 // A start_loop_iterations is just equivalent to the first operand for 6728 // SCEV purposes. 6729 return getSCEV(II->getArgOperand(0)); 6730 default: 6731 break; 6732 } 6733 } 6734 break; 6735 } 6736 6737 return getUnknown(V); 6738 } 6739 6740 //===----------------------------------------------------------------------===// 6741 // Iteration Count Computation Code 6742 // 6743 6744 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6745 if (!ExitCount) 6746 return 0; 6747 6748 ConstantInt *ExitConst = ExitCount->getValue(); 6749 6750 // Guard against huge trip counts. 6751 if (ExitConst->getValue().getActiveBits() > 32) 6752 return 0; 6753 6754 // In case of integer overflow, this returns 0, which is correct. 6755 return ((unsigned)ExitConst->getZExtValue()) + 1; 6756 } 6757 6758 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6759 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6760 return getSmallConstantTripCount(L, ExitingBB); 6761 6762 // No trip count information for multiple exits. 6763 return 0; 6764 } 6765 6766 unsigned 6767 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6768 const BasicBlock *ExitingBlock) { 6769 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6770 assert(L->isLoopExiting(ExitingBlock) && 6771 "Exiting block must actually branch out of the loop!"); 6772 const SCEVConstant *ExitCount = 6773 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6774 return getConstantTripCount(ExitCount); 6775 } 6776 6777 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6778 const auto *MaxExitCount = 6779 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6780 return getConstantTripCount(MaxExitCount); 6781 } 6782 6783 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6784 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6785 return getSmallConstantTripMultiple(L, ExitingBB); 6786 6787 // No trip multiple information for multiple exits. 6788 return 0; 6789 } 6790 6791 /// Returns the largest constant divisor of the trip count of this loop as a 6792 /// normal unsigned value, if possible. This means that the actual trip count is 6793 /// always a multiple of the returned value (don't forget the trip count could 6794 /// very well be zero as well!). 6795 /// 6796 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6797 /// multiple of a constant (which is also the case if the trip count is simply 6798 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6799 /// if the trip count is very large (>= 2^32). 6800 /// 6801 /// As explained in the comments for getSmallConstantTripCount, this assumes 6802 /// that control exits the loop via ExitingBlock. 6803 unsigned 6804 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6805 const BasicBlock *ExitingBlock) { 6806 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6807 assert(L->isLoopExiting(ExitingBlock) && 6808 "Exiting block must actually branch out of the loop!"); 6809 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6810 if (ExitCount == getCouldNotCompute()) 6811 return 1; 6812 6813 // Get the trip count from the BE count by adding 1. 6814 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6815 6816 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6817 if (!TC) 6818 // Attempt to factor more general cases. Returns the greatest power of 6819 // two divisor. If overflow happens, the trip count expression is still 6820 // divisible by the greatest power of 2 divisor returned. 6821 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6822 6823 ConstantInt *Result = TC->getValue(); 6824 6825 // Guard against huge trip counts (this requires checking 6826 // for zero to handle the case where the trip count == -1 and the 6827 // addition wraps). 6828 if (!Result || Result->getValue().getActiveBits() > 32 || 6829 Result->getValue().getActiveBits() == 0) 6830 return 1; 6831 6832 return (unsigned)Result->getZExtValue(); 6833 } 6834 6835 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6836 const BasicBlock *ExitingBlock, 6837 ExitCountKind Kind) { 6838 switch (Kind) { 6839 case Exact: 6840 case SymbolicMaximum: 6841 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6842 case ConstantMaximum: 6843 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 6844 }; 6845 llvm_unreachable("Invalid ExitCountKind!"); 6846 } 6847 6848 const SCEV * 6849 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6850 SCEVUnionPredicate &Preds) { 6851 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6852 } 6853 6854 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6855 ExitCountKind Kind) { 6856 switch (Kind) { 6857 case Exact: 6858 return getBackedgeTakenInfo(L).getExact(L, this); 6859 case ConstantMaximum: 6860 return getBackedgeTakenInfo(L).getConstantMax(this); 6861 case SymbolicMaximum: 6862 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 6863 }; 6864 llvm_unreachable("Invalid ExitCountKind!"); 6865 } 6866 6867 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6868 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 6869 } 6870 6871 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6872 static void 6873 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6874 BasicBlock *Header = L->getHeader(); 6875 6876 // Push all Loop-header PHIs onto the Worklist stack. 6877 for (PHINode &PN : Header->phis()) 6878 Worklist.push_back(&PN); 6879 } 6880 6881 const ScalarEvolution::BackedgeTakenInfo & 6882 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6883 auto &BTI = getBackedgeTakenInfo(L); 6884 if (BTI.hasFullInfo()) 6885 return BTI; 6886 6887 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6888 6889 if (!Pair.second) 6890 return Pair.first->second; 6891 6892 BackedgeTakenInfo Result = 6893 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6894 6895 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6896 } 6897 6898 ScalarEvolution::BackedgeTakenInfo & 6899 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6900 // Initially insert an invalid entry for this loop. If the insertion 6901 // succeeds, proceed to actually compute a backedge-taken count and 6902 // update the value. The temporary CouldNotCompute value tells SCEV 6903 // code elsewhere that it shouldn't attempt to request a new 6904 // backedge-taken count, which could result in infinite recursion. 6905 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6906 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6907 if (!Pair.second) 6908 return Pair.first->second; 6909 6910 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6911 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6912 // must be cleared in this scope. 6913 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6914 6915 // In product build, there are no usage of statistic. 6916 (void)NumTripCountsComputed; 6917 (void)NumTripCountsNotComputed; 6918 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6919 const SCEV *BEExact = Result.getExact(L, this); 6920 if (BEExact != getCouldNotCompute()) { 6921 assert(isLoopInvariant(BEExact, L) && 6922 isLoopInvariant(Result.getConstantMax(this), L) && 6923 "Computed backedge-taken count isn't loop invariant for loop!"); 6924 ++NumTripCountsComputed; 6925 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 6926 isa<PHINode>(L->getHeader()->begin())) { 6927 // Only count loops that have phi nodes as not being computable. 6928 ++NumTripCountsNotComputed; 6929 } 6930 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6931 6932 // Now that we know more about the trip count for this loop, forget any 6933 // existing SCEV values for PHI nodes in this loop since they are only 6934 // conservative estimates made without the benefit of trip count 6935 // information. This is similar to the code in forgetLoop, except that 6936 // it handles SCEVUnknown PHI nodes specially. 6937 if (Result.hasAnyInfo()) { 6938 SmallVector<Instruction *, 16> Worklist; 6939 PushLoopPHIs(L, Worklist); 6940 6941 SmallPtrSet<Instruction *, 8> Discovered; 6942 while (!Worklist.empty()) { 6943 Instruction *I = Worklist.pop_back_val(); 6944 6945 ValueExprMapType::iterator It = 6946 ValueExprMap.find_as(static_cast<Value *>(I)); 6947 if (It != ValueExprMap.end()) { 6948 const SCEV *Old = It->second; 6949 6950 // SCEVUnknown for a PHI either means that it has an unrecognized 6951 // structure, or it's a PHI that's in the progress of being computed 6952 // by createNodeForPHI. In the former case, additional loop trip 6953 // count information isn't going to change anything. In the later 6954 // case, createNodeForPHI will perform the necessary updates on its 6955 // own when it gets to that point. 6956 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6957 eraseValueFromMap(It->first); 6958 forgetMemoizedResults(Old); 6959 } 6960 if (PHINode *PN = dyn_cast<PHINode>(I)) 6961 ConstantEvolutionLoopExitValue.erase(PN); 6962 } 6963 6964 // Since we don't need to invalidate anything for correctness and we're 6965 // only invalidating to make SCEV's results more precise, we get to stop 6966 // early to avoid invalidating too much. This is especially important in 6967 // cases like: 6968 // 6969 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6970 // loop0: 6971 // %pn0 = phi 6972 // ... 6973 // loop1: 6974 // %pn1 = phi 6975 // ... 6976 // 6977 // where both loop0 and loop1's backedge taken count uses the SCEV 6978 // expression for %v. If we don't have the early stop below then in cases 6979 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6980 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6981 // count for loop1, effectively nullifying SCEV's trip count cache. 6982 for (auto *U : I->users()) 6983 if (auto *I = dyn_cast<Instruction>(U)) { 6984 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6985 if (LoopForUser && L->contains(LoopForUser) && 6986 Discovered.insert(I).second) 6987 Worklist.push_back(I); 6988 } 6989 } 6990 } 6991 6992 // Re-lookup the insert position, since the call to 6993 // computeBackedgeTakenCount above could result in a 6994 // recusive call to getBackedgeTakenInfo (on a different 6995 // loop), which would invalidate the iterator computed 6996 // earlier. 6997 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6998 } 6999 7000 void ScalarEvolution::forgetAllLoops() { 7001 // This method is intended to forget all info about loops. It should 7002 // invalidate caches as if the following happened: 7003 // - The trip counts of all loops have changed arbitrarily 7004 // - Every llvm::Value has been updated in place to produce a different 7005 // result. 7006 BackedgeTakenCounts.clear(); 7007 PredicatedBackedgeTakenCounts.clear(); 7008 LoopPropertiesCache.clear(); 7009 ConstantEvolutionLoopExitValue.clear(); 7010 ValueExprMap.clear(); 7011 ValuesAtScopes.clear(); 7012 LoopDispositions.clear(); 7013 BlockDispositions.clear(); 7014 UnsignedRanges.clear(); 7015 SignedRanges.clear(); 7016 ExprValueMap.clear(); 7017 HasRecMap.clear(); 7018 MinTrailingZerosCache.clear(); 7019 PredicatedSCEVRewrites.clear(); 7020 } 7021 7022 void ScalarEvolution::forgetLoop(const Loop *L) { 7023 // Drop any stored trip count value. 7024 auto RemoveLoopFromBackedgeMap = 7025 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 7026 auto BTCPos = Map.find(L); 7027 if (BTCPos != Map.end()) { 7028 BTCPos->second.clear(); 7029 Map.erase(BTCPos); 7030 } 7031 }; 7032 7033 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7034 SmallVector<Instruction *, 32> Worklist; 7035 SmallPtrSet<Instruction *, 16> Visited; 7036 7037 // Iterate over all the loops and sub-loops to drop SCEV information. 7038 while (!LoopWorklist.empty()) { 7039 auto *CurrL = LoopWorklist.pop_back_val(); 7040 7041 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 7042 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 7043 7044 // Drop information about predicated SCEV rewrites for this loop. 7045 for (auto I = PredicatedSCEVRewrites.begin(); 7046 I != PredicatedSCEVRewrites.end();) { 7047 std::pair<const SCEV *, const Loop *> Entry = I->first; 7048 if (Entry.second == CurrL) 7049 PredicatedSCEVRewrites.erase(I++); 7050 else 7051 ++I; 7052 } 7053 7054 auto LoopUsersItr = LoopUsers.find(CurrL); 7055 if (LoopUsersItr != LoopUsers.end()) { 7056 for (auto *S : LoopUsersItr->second) 7057 forgetMemoizedResults(S); 7058 LoopUsers.erase(LoopUsersItr); 7059 } 7060 7061 // Drop information about expressions based on loop-header PHIs. 7062 PushLoopPHIs(CurrL, Worklist); 7063 7064 while (!Worklist.empty()) { 7065 Instruction *I = Worklist.pop_back_val(); 7066 if (!Visited.insert(I).second) 7067 continue; 7068 7069 ValueExprMapType::iterator It = 7070 ValueExprMap.find_as(static_cast<Value *>(I)); 7071 if (It != ValueExprMap.end()) { 7072 eraseValueFromMap(It->first); 7073 forgetMemoizedResults(It->second); 7074 if (PHINode *PN = dyn_cast<PHINode>(I)) 7075 ConstantEvolutionLoopExitValue.erase(PN); 7076 } 7077 7078 PushDefUseChildren(I, Worklist); 7079 } 7080 7081 LoopPropertiesCache.erase(CurrL); 7082 // Forget all contained loops too, to avoid dangling entries in the 7083 // ValuesAtScopes map. 7084 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7085 } 7086 } 7087 7088 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7089 while (Loop *Parent = L->getParentLoop()) 7090 L = Parent; 7091 forgetLoop(L); 7092 } 7093 7094 void ScalarEvolution::forgetValue(Value *V) { 7095 Instruction *I = dyn_cast<Instruction>(V); 7096 if (!I) return; 7097 7098 // Drop information about expressions based on loop-header PHIs. 7099 SmallVector<Instruction *, 16> Worklist; 7100 Worklist.push_back(I); 7101 7102 SmallPtrSet<Instruction *, 8> Visited; 7103 while (!Worklist.empty()) { 7104 I = Worklist.pop_back_val(); 7105 if (!Visited.insert(I).second) 7106 continue; 7107 7108 ValueExprMapType::iterator It = 7109 ValueExprMap.find_as(static_cast<Value *>(I)); 7110 if (It != ValueExprMap.end()) { 7111 eraseValueFromMap(It->first); 7112 forgetMemoizedResults(It->second); 7113 if (PHINode *PN = dyn_cast<PHINode>(I)) 7114 ConstantEvolutionLoopExitValue.erase(PN); 7115 } 7116 7117 PushDefUseChildren(I, Worklist); 7118 } 7119 } 7120 7121 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7122 LoopDispositions.clear(); 7123 } 7124 7125 /// Get the exact loop backedge taken count considering all loop exits. A 7126 /// computable result can only be returned for loops with all exiting blocks 7127 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7128 /// is never skipped. This is a valid assumption as long as the loop exits via 7129 /// that test. For precise results, it is the caller's responsibility to specify 7130 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7131 const SCEV * 7132 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7133 SCEVUnionPredicate *Preds) const { 7134 // If any exits were not computable, the loop is not computable. 7135 if (!isComplete() || ExitNotTaken.empty()) 7136 return SE->getCouldNotCompute(); 7137 7138 const BasicBlock *Latch = L->getLoopLatch(); 7139 // All exiting blocks we have collected must dominate the only backedge. 7140 if (!Latch) 7141 return SE->getCouldNotCompute(); 7142 7143 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7144 // count is simply a minimum out of all these calculated exit counts. 7145 SmallVector<const SCEV *, 2> Ops; 7146 for (auto &ENT : ExitNotTaken) { 7147 const SCEV *BECount = ENT.ExactNotTaken; 7148 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7149 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7150 "We should only have known counts for exiting blocks that dominate " 7151 "latch!"); 7152 7153 Ops.push_back(BECount); 7154 7155 if (Preds && !ENT.hasAlwaysTruePredicate()) 7156 Preds->add(ENT.Predicate.get()); 7157 7158 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7159 "Predicate should be always true!"); 7160 } 7161 7162 return SE->getUMinFromMismatchedTypes(Ops); 7163 } 7164 7165 /// Get the exact not taken count for this loop exit. 7166 const SCEV * 7167 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7168 ScalarEvolution *SE) const { 7169 for (auto &ENT : ExitNotTaken) 7170 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7171 return ENT.ExactNotTaken; 7172 7173 return SE->getCouldNotCompute(); 7174 } 7175 7176 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7177 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7178 for (auto &ENT : ExitNotTaken) 7179 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7180 return ENT.MaxNotTaken; 7181 7182 return SE->getCouldNotCompute(); 7183 } 7184 7185 /// getConstantMax - Get the constant max backedge taken count for the loop. 7186 const SCEV * 7187 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7188 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7189 return !ENT.hasAlwaysTruePredicate(); 7190 }; 7191 7192 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7193 return SE->getCouldNotCompute(); 7194 7195 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7196 isa<SCEVConstant>(getConstantMax())) && 7197 "No point in having a non-constant max backedge taken count!"); 7198 return getConstantMax(); 7199 } 7200 7201 const SCEV * 7202 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7203 ScalarEvolution *SE) { 7204 if (!SymbolicMax) 7205 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7206 return SymbolicMax; 7207 } 7208 7209 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7210 ScalarEvolution *SE) const { 7211 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7212 return !ENT.hasAlwaysTruePredicate(); 7213 }; 7214 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7215 } 7216 7217 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7218 ScalarEvolution *SE) const { 7219 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() && 7220 SE->hasOperand(getConstantMax(), S)) 7221 return true; 7222 7223 for (auto &ENT : ExitNotTaken) 7224 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7225 SE->hasOperand(ENT.ExactNotTaken, S)) 7226 return true; 7227 7228 return false; 7229 } 7230 7231 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7232 : ExactNotTaken(E), MaxNotTaken(E) { 7233 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7234 isa<SCEVConstant>(MaxNotTaken)) && 7235 "No point in having a non-constant max backedge taken count!"); 7236 } 7237 7238 ScalarEvolution::ExitLimit::ExitLimit( 7239 const SCEV *E, const SCEV *M, bool MaxOrZero, 7240 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7241 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7242 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7243 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7244 "Exact is not allowed to be less precise than Max"); 7245 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7246 isa<SCEVConstant>(MaxNotTaken)) && 7247 "No point in having a non-constant max backedge taken count!"); 7248 for (auto *PredSet : PredSetList) 7249 for (auto *P : *PredSet) 7250 addPredicate(P); 7251 } 7252 7253 ScalarEvolution::ExitLimit::ExitLimit( 7254 const SCEV *E, const SCEV *M, bool MaxOrZero, 7255 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7256 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7257 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7258 isa<SCEVConstant>(MaxNotTaken)) && 7259 "No point in having a non-constant max backedge taken count!"); 7260 } 7261 7262 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7263 bool MaxOrZero) 7264 : ExitLimit(E, M, MaxOrZero, None) { 7265 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7266 isa<SCEVConstant>(MaxNotTaken)) && 7267 "No point in having a non-constant max backedge taken count!"); 7268 } 7269 7270 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7271 /// computable exit into a persistent ExitNotTakenInfo array. 7272 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7273 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7274 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7275 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7276 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7277 7278 ExitNotTaken.reserve(ExitCounts.size()); 7279 std::transform( 7280 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7281 [&](const EdgeExitInfo &EEI) { 7282 BasicBlock *ExitBB = EEI.first; 7283 const ExitLimit &EL = EEI.second; 7284 if (EL.Predicates.empty()) 7285 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7286 nullptr); 7287 7288 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7289 for (auto *Pred : EL.Predicates) 7290 Predicate->add(Pred); 7291 7292 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7293 std::move(Predicate)); 7294 }); 7295 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7296 isa<SCEVConstant>(ConstantMax)) && 7297 "No point in having a non-constant max backedge taken count!"); 7298 } 7299 7300 /// Invalidate this result and free the ExitNotTakenInfo array. 7301 void ScalarEvolution::BackedgeTakenInfo::clear() { 7302 ExitNotTaken.clear(); 7303 } 7304 7305 /// Compute the number of times the backedge of the specified loop will execute. 7306 ScalarEvolution::BackedgeTakenInfo 7307 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7308 bool AllowPredicates) { 7309 SmallVector<BasicBlock *, 8> ExitingBlocks; 7310 L->getExitingBlocks(ExitingBlocks); 7311 7312 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7313 7314 SmallVector<EdgeExitInfo, 4> ExitCounts; 7315 bool CouldComputeBECount = true; 7316 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7317 const SCEV *MustExitMaxBECount = nullptr; 7318 const SCEV *MayExitMaxBECount = nullptr; 7319 bool MustExitMaxOrZero = false; 7320 7321 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7322 // and compute maxBECount. 7323 // Do a union of all the predicates here. 7324 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7325 BasicBlock *ExitBB = ExitingBlocks[i]; 7326 7327 // We canonicalize untaken exits to br (constant), ignore them so that 7328 // proving an exit untaken doesn't negatively impact our ability to reason 7329 // about the loop as whole. 7330 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7331 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7332 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7333 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7334 continue; 7335 } 7336 7337 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7338 7339 assert((AllowPredicates || EL.Predicates.empty()) && 7340 "Predicated exit limit when predicates are not allowed!"); 7341 7342 // 1. For each exit that can be computed, add an entry to ExitCounts. 7343 // CouldComputeBECount is true only if all exits can be computed. 7344 if (EL.ExactNotTaken == getCouldNotCompute()) 7345 // We couldn't compute an exact value for this exit, so 7346 // we won't be able to compute an exact value for the loop. 7347 CouldComputeBECount = false; 7348 else 7349 ExitCounts.emplace_back(ExitBB, EL); 7350 7351 // 2. Derive the loop's MaxBECount from each exit's max number of 7352 // non-exiting iterations. Partition the loop exits into two kinds: 7353 // LoopMustExits and LoopMayExits. 7354 // 7355 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7356 // is a LoopMayExit. If any computable LoopMustExit is found, then 7357 // MaxBECount is the minimum EL.MaxNotTaken of computable 7358 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7359 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7360 // computable EL.MaxNotTaken. 7361 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7362 DT.dominates(ExitBB, Latch)) { 7363 if (!MustExitMaxBECount) { 7364 MustExitMaxBECount = EL.MaxNotTaken; 7365 MustExitMaxOrZero = EL.MaxOrZero; 7366 } else { 7367 MustExitMaxBECount = 7368 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7369 } 7370 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7371 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7372 MayExitMaxBECount = EL.MaxNotTaken; 7373 else { 7374 MayExitMaxBECount = 7375 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7376 } 7377 } 7378 } 7379 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7380 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7381 // The loop backedge will be taken the maximum or zero times if there's 7382 // a single exit that must be taken the maximum or zero times. 7383 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7384 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7385 MaxBECount, MaxOrZero); 7386 } 7387 7388 ScalarEvolution::ExitLimit 7389 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7390 bool AllowPredicates) { 7391 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7392 // If our exiting block does not dominate the latch, then its connection with 7393 // loop's exit limit may be far from trivial. 7394 const BasicBlock *Latch = L->getLoopLatch(); 7395 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7396 return getCouldNotCompute(); 7397 7398 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7399 Instruction *Term = ExitingBlock->getTerminator(); 7400 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7401 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7402 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7403 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7404 "It should have one successor in loop and one exit block!"); 7405 // Proceed to the next level to examine the exit condition expression. 7406 return computeExitLimitFromCond( 7407 L, BI->getCondition(), ExitIfTrue, 7408 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7409 } 7410 7411 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7412 // For switch, make sure that there is a single exit from the loop. 7413 BasicBlock *Exit = nullptr; 7414 for (auto *SBB : successors(ExitingBlock)) 7415 if (!L->contains(SBB)) { 7416 if (Exit) // Multiple exit successors. 7417 return getCouldNotCompute(); 7418 Exit = SBB; 7419 } 7420 assert(Exit && "Exiting block must have at least one exit"); 7421 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7422 /*ControlsExit=*/IsOnlyExit); 7423 } 7424 7425 return getCouldNotCompute(); 7426 } 7427 7428 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7429 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7430 bool ControlsExit, bool AllowPredicates) { 7431 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7432 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7433 ControlsExit, AllowPredicates); 7434 } 7435 7436 Optional<ScalarEvolution::ExitLimit> 7437 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7438 bool ExitIfTrue, bool ControlsExit, 7439 bool AllowPredicates) { 7440 (void)this->L; 7441 (void)this->ExitIfTrue; 7442 (void)this->AllowPredicates; 7443 7444 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7445 this->AllowPredicates == AllowPredicates && 7446 "Variance in assumed invariant key components!"); 7447 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7448 if (Itr == TripCountMap.end()) 7449 return None; 7450 return Itr->second; 7451 } 7452 7453 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7454 bool ExitIfTrue, 7455 bool ControlsExit, 7456 bool AllowPredicates, 7457 const ExitLimit &EL) { 7458 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7459 this->AllowPredicates == AllowPredicates && 7460 "Variance in assumed invariant key components!"); 7461 7462 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7463 assert(InsertResult.second && "Expected successful insertion!"); 7464 (void)InsertResult; 7465 (void)ExitIfTrue; 7466 } 7467 7468 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7469 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7470 bool ControlsExit, bool AllowPredicates) { 7471 7472 if (auto MaybeEL = 7473 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7474 return *MaybeEL; 7475 7476 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7477 ControlsExit, AllowPredicates); 7478 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7479 return EL; 7480 } 7481 7482 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7483 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7484 bool ControlsExit, bool AllowPredicates) { 7485 // Check if the controlling expression for this loop is an And or Or. 7486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7487 if (BO->getOpcode() == Instruction::And) { 7488 // Recurse on the operands of the and. 7489 bool EitherMayExit = !ExitIfTrue; 7490 ExitLimit EL0 = computeExitLimitFromCondCached( 7491 Cache, L, BO->getOperand(0), ExitIfTrue, 7492 ControlsExit && !EitherMayExit, AllowPredicates); 7493 ExitLimit EL1 = computeExitLimitFromCondCached( 7494 Cache, L, BO->getOperand(1), ExitIfTrue, 7495 ControlsExit && !EitherMayExit, AllowPredicates); 7496 // Be robust against unsimplified IR for the form "and i1 X, true" 7497 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7498 return CI->isOne() ? EL0 : EL1; 7499 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7500 return CI->isOne() ? EL1 : EL0; 7501 const SCEV *BECount = getCouldNotCompute(); 7502 const SCEV *MaxBECount = getCouldNotCompute(); 7503 if (EitherMayExit) { 7504 // Both conditions must be true for the loop to continue executing. 7505 // Choose the less conservative count. 7506 if (EL0.ExactNotTaken == getCouldNotCompute() || 7507 EL1.ExactNotTaken == getCouldNotCompute()) 7508 BECount = getCouldNotCompute(); 7509 else 7510 BECount = 7511 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7512 if (EL0.MaxNotTaken == getCouldNotCompute()) 7513 MaxBECount = EL1.MaxNotTaken; 7514 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7515 MaxBECount = EL0.MaxNotTaken; 7516 else 7517 MaxBECount = 7518 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7519 } else { 7520 // Both conditions must be true at the same time for the loop to exit. 7521 // For now, be conservative. 7522 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7523 MaxBECount = EL0.MaxNotTaken; 7524 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7525 BECount = EL0.ExactNotTaken; 7526 } 7527 7528 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7529 // to be more aggressive when computing BECount than when computing 7530 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7531 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7532 // to not. 7533 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7534 !isa<SCEVCouldNotCompute>(BECount)) 7535 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7536 7537 return ExitLimit(BECount, MaxBECount, false, 7538 {&EL0.Predicates, &EL1.Predicates}); 7539 } 7540 if (BO->getOpcode() == Instruction::Or) { 7541 // Recurse on the operands of the or. 7542 bool EitherMayExit = ExitIfTrue; 7543 ExitLimit EL0 = computeExitLimitFromCondCached( 7544 Cache, L, BO->getOperand(0), ExitIfTrue, 7545 ControlsExit && !EitherMayExit, AllowPredicates); 7546 ExitLimit EL1 = computeExitLimitFromCondCached( 7547 Cache, L, BO->getOperand(1), ExitIfTrue, 7548 ControlsExit && !EitherMayExit, AllowPredicates); 7549 // Be robust against unsimplified IR for the form "or i1 X, true" 7550 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7551 return CI->isZero() ? EL0 : EL1; 7552 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7553 return CI->isZero() ? EL1 : EL0; 7554 const SCEV *BECount = getCouldNotCompute(); 7555 const SCEV *MaxBECount = getCouldNotCompute(); 7556 if (EitherMayExit) { 7557 // Both conditions must be false for the loop to continue executing. 7558 // Choose the less conservative count. 7559 if (EL0.ExactNotTaken == getCouldNotCompute() || 7560 EL1.ExactNotTaken == getCouldNotCompute()) 7561 BECount = getCouldNotCompute(); 7562 else 7563 BECount = 7564 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7565 if (EL0.MaxNotTaken == getCouldNotCompute()) 7566 MaxBECount = EL1.MaxNotTaken; 7567 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7568 MaxBECount = EL0.MaxNotTaken; 7569 else 7570 MaxBECount = 7571 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7572 } else { 7573 // Both conditions must be false at the same time for the loop to exit. 7574 // For now, be conservative. 7575 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7576 MaxBECount = EL0.MaxNotTaken; 7577 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7578 BECount = EL0.ExactNotTaken; 7579 } 7580 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7581 // to be more aggressive when computing BECount than when computing 7582 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7583 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7584 // to not. 7585 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7586 !isa<SCEVCouldNotCompute>(BECount)) 7587 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7588 7589 return ExitLimit(BECount, MaxBECount, false, 7590 {&EL0.Predicates, &EL1.Predicates}); 7591 } 7592 } 7593 7594 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7595 // Proceed to the next level to examine the icmp. 7596 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7597 ExitLimit EL = 7598 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7599 if (EL.hasFullInfo() || !AllowPredicates) 7600 return EL; 7601 7602 // Try again, but use SCEV predicates this time. 7603 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7604 /*AllowPredicates=*/true); 7605 } 7606 7607 // Check for a constant condition. These are normally stripped out by 7608 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7609 // preserve the CFG and is temporarily leaving constant conditions 7610 // in place. 7611 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7612 if (ExitIfTrue == !CI->getZExtValue()) 7613 // The backedge is always taken. 7614 return getCouldNotCompute(); 7615 else 7616 // The backedge is never taken. 7617 return getZero(CI->getType()); 7618 } 7619 7620 // If it's not an integer or pointer comparison then compute it the hard way. 7621 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7622 } 7623 7624 ScalarEvolution::ExitLimit 7625 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7626 ICmpInst *ExitCond, 7627 bool ExitIfTrue, 7628 bool ControlsExit, 7629 bool AllowPredicates) { 7630 // If the condition was exit on true, convert the condition to exit on false 7631 ICmpInst::Predicate Pred; 7632 if (!ExitIfTrue) 7633 Pred = ExitCond->getPredicate(); 7634 else 7635 Pred = ExitCond->getInversePredicate(); 7636 const ICmpInst::Predicate OriginalPred = Pred; 7637 7638 // Handle common loops like: for (X = "string"; *X; ++X) 7639 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7640 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7641 ExitLimit ItCnt = 7642 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7643 if (ItCnt.hasAnyInfo()) 7644 return ItCnt; 7645 } 7646 7647 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7648 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7649 7650 // Try to evaluate any dependencies out of the loop. 7651 LHS = getSCEVAtScope(LHS, L); 7652 RHS = getSCEVAtScope(RHS, L); 7653 7654 // At this point, we would like to compute how many iterations of the 7655 // loop the predicate will return true for these inputs. 7656 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7657 // If there is a loop-invariant, force it into the RHS. 7658 std::swap(LHS, RHS); 7659 Pred = ICmpInst::getSwappedPredicate(Pred); 7660 } 7661 7662 // Simplify the operands before analyzing them. 7663 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7664 7665 // If we have a comparison of a chrec against a constant, try to use value 7666 // ranges to answer this query. 7667 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7668 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7669 if (AddRec->getLoop() == L) { 7670 // Form the constant range. 7671 ConstantRange CompRange = 7672 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7673 7674 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7675 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7676 } 7677 7678 switch (Pred) { 7679 case ICmpInst::ICMP_NE: { // while (X != Y) 7680 // Convert to: while (X-Y != 0) 7681 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7682 AllowPredicates); 7683 if (EL.hasAnyInfo()) return EL; 7684 break; 7685 } 7686 case ICmpInst::ICMP_EQ: { // while (X == Y) 7687 // Convert to: while (X-Y == 0) 7688 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7689 if (EL.hasAnyInfo()) return EL; 7690 break; 7691 } 7692 case ICmpInst::ICMP_SLT: 7693 case ICmpInst::ICMP_ULT: { // while (X < Y) 7694 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7695 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7696 AllowPredicates); 7697 if (EL.hasAnyInfo()) return EL; 7698 break; 7699 } 7700 case ICmpInst::ICMP_SGT: 7701 case ICmpInst::ICMP_UGT: { // while (X > Y) 7702 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7703 ExitLimit EL = 7704 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7705 AllowPredicates); 7706 if (EL.hasAnyInfo()) return EL; 7707 break; 7708 } 7709 default: 7710 break; 7711 } 7712 7713 auto *ExhaustiveCount = 7714 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7715 7716 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7717 return ExhaustiveCount; 7718 7719 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7720 ExitCond->getOperand(1), L, OriginalPred); 7721 } 7722 7723 ScalarEvolution::ExitLimit 7724 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7725 SwitchInst *Switch, 7726 BasicBlock *ExitingBlock, 7727 bool ControlsExit) { 7728 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7729 7730 // Give up if the exit is the default dest of a switch. 7731 if (Switch->getDefaultDest() == ExitingBlock) 7732 return getCouldNotCompute(); 7733 7734 assert(L->contains(Switch->getDefaultDest()) && 7735 "Default case must not exit the loop!"); 7736 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7737 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7738 7739 // while (X != Y) --> while (X-Y != 0) 7740 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7741 if (EL.hasAnyInfo()) 7742 return EL; 7743 7744 return getCouldNotCompute(); 7745 } 7746 7747 static ConstantInt * 7748 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7749 ScalarEvolution &SE) { 7750 const SCEV *InVal = SE.getConstant(C); 7751 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7752 assert(isa<SCEVConstant>(Val) && 7753 "Evaluation of SCEV at constant didn't fold correctly?"); 7754 return cast<SCEVConstant>(Val)->getValue(); 7755 } 7756 7757 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7758 /// compute the backedge execution count. 7759 ScalarEvolution::ExitLimit 7760 ScalarEvolution::computeLoadConstantCompareExitLimit( 7761 LoadInst *LI, 7762 Constant *RHS, 7763 const Loop *L, 7764 ICmpInst::Predicate predicate) { 7765 if (LI->isVolatile()) return getCouldNotCompute(); 7766 7767 // Check to see if the loaded pointer is a getelementptr of a global. 7768 // TODO: Use SCEV instead of manually grubbing with GEPs. 7769 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7770 if (!GEP) return getCouldNotCompute(); 7771 7772 // Make sure that it is really a constant global we are gepping, with an 7773 // initializer, and make sure the first IDX is really 0. 7774 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7775 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7776 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7777 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7778 return getCouldNotCompute(); 7779 7780 // Okay, we allow one non-constant index into the GEP instruction. 7781 Value *VarIdx = nullptr; 7782 std::vector<Constant*> Indexes; 7783 unsigned VarIdxNum = 0; 7784 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7785 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7786 Indexes.push_back(CI); 7787 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7788 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7789 VarIdx = GEP->getOperand(i); 7790 VarIdxNum = i-2; 7791 Indexes.push_back(nullptr); 7792 } 7793 7794 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7795 if (!VarIdx) 7796 return getCouldNotCompute(); 7797 7798 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7799 // Check to see if X is a loop variant variable value now. 7800 const SCEV *Idx = getSCEV(VarIdx); 7801 Idx = getSCEVAtScope(Idx, L); 7802 7803 // We can only recognize very limited forms of loop index expressions, in 7804 // particular, only affine AddRec's like {C1,+,C2}. 7805 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7806 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7807 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7808 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7809 return getCouldNotCompute(); 7810 7811 unsigned MaxSteps = MaxBruteForceIterations; 7812 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7813 ConstantInt *ItCst = ConstantInt::get( 7814 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7815 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7816 7817 // Form the GEP offset. 7818 Indexes[VarIdxNum] = Val; 7819 7820 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7821 Indexes); 7822 if (!Result) break; // Cannot compute! 7823 7824 // Evaluate the condition for this iteration. 7825 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7826 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7827 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7828 ++NumArrayLenItCounts; 7829 return getConstant(ItCst); // Found terminating iteration! 7830 } 7831 } 7832 return getCouldNotCompute(); 7833 } 7834 7835 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7836 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7837 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7838 if (!RHS) 7839 return getCouldNotCompute(); 7840 7841 const BasicBlock *Latch = L->getLoopLatch(); 7842 if (!Latch) 7843 return getCouldNotCompute(); 7844 7845 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7846 if (!Predecessor) 7847 return getCouldNotCompute(); 7848 7849 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7850 // Return LHS in OutLHS and shift_opt in OutOpCode. 7851 auto MatchPositiveShift = 7852 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7853 7854 using namespace PatternMatch; 7855 7856 ConstantInt *ShiftAmt; 7857 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7858 OutOpCode = Instruction::LShr; 7859 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7860 OutOpCode = Instruction::AShr; 7861 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7862 OutOpCode = Instruction::Shl; 7863 else 7864 return false; 7865 7866 return ShiftAmt->getValue().isStrictlyPositive(); 7867 }; 7868 7869 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7870 // 7871 // loop: 7872 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7873 // %iv.shifted = lshr i32 %iv, <positive constant> 7874 // 7875 // Return true on a successful match. Return the corresponding PHI node (%iv 7876 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7877 auto MatchShiftRecurrence = 7878 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7879 Optional<Instruction::BinaryOps> PostShiftOpCode; 7880 7881 { 7882 Instruction::BinaryOps OpC; 7883 Value *V; 7884 7885 // If we encounter a shift instruction, "peel off" the shift operation, 7886 // and remember that we did so. Later when we inspect %iv's backedge 7887 // value, we will make sure that the backedge value uses the same 7888 // operation. 7889 // 7890 // Note: the peeled shift operation does not have to be the same 7891 // instruction as the one feeding into the PHI's backedge value. We only 7892 // really care about it being the same *kind* of shift instruction -- 7893 // that's all that is required for our later inferences to hold. 7894 if (MatchPositiveShift(LHS, V, OpC)) { 7895 PostShiftOpCode = OpC; 7896 LHS = V; 7897 } 7898 } 7899 7900 PNOut = dyn_cast<PHINode>(LHS); 7901 if (!PNOut || PNOut->getParent() != L->getHeader()) 7902 return false; 7903 7904 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7905 Value *OpLHS; 7906 7907 return 7908 // The backedge value for the PHI node must be a shift by a positive 7909 // amount 7910 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7911 7912 // of the PHI node itself 7913 OpLHS == PNOut && 7914 7915 // and the kind of shift should be match the kind of shift we peeled 7916 // off, if any. 7917 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7918 }; 7919 7920 PHINode *PN; 7921 Instruction::BinaryOps OpCode; 7922 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7923 return getCouldNotCompute(); 7924 7925 const DataLayout &DL = getDataLayout(); 7926 7927 // The key rationale for this optimization is that for some kinds of shift 7928 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7929 // within a finite number of iterations. If the condition guarding the 7930 // backedge (in the sense that the backedge is taken if the condition is true) 7931 // is false for the value the shift recurrence stabilizes to, then we know 7932 // that the backedge is taken only a finite number of times. 7933 7934 ConstantInt *StableValue = nullptr; 7935 switch (OpCode) { 7936 default: 7937 llvm_unreachable("Impossible case!"); 7938 7939 case Instruction::AShr: { 7940 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7941 // bitwidth(K) iterations. 7942 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7943 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7944 Predecessor->getTerminator(), &DT); 7945 auto *Ty = cast<IntegerType>(RHS->getType()); 7946 if (Known.isNonNegative()) 7947 StableValue = ConstantInt::get(Ty, 0); 7948 else if (Known.isNegative()) 7949 StableValue = ConstantInt::get(Ty, -1, true); 7950 else 7951 return getCouldNotCompute(); 7952 7953 break; 7954 } 7955 case Instruction::LShr: 7956 case Instruction::Shl: 7957 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7958 // stabilize to 0 in at most bitwidth(K) iterations. 7959 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7960 break; 7961 } 7962 7963 auto *Result = 7964 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7965 assert(Result->getType()->isIntegerTy(1) && 7966 "Otherwise cannot be an operand to a branch instruction"); 7967 7968 if (Result->isZeroValue()) { 7969 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7970 const SCEV *UpperBound = 7971 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7972 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7973 } 7974 7975 return getCouldNotCompute(); 7976 } 7977 7978 /// Return true if we can constant fold an instruction of the specified type, 7979 /// assuming that all operands were constants. 7980 static bool CanConstantFold(const Instruction *I) { 7981 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7982 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7983 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7984 return true; 7985 7986 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7987 if (const Function *F = CI->getCalledFunction()) 7988 return canConstantFoldCallTo(CI, F); 7989 return false; 7990 } 7991 7992 /// Determine whether this instruction can constant evolve within this loop 7993 /// assuming its operands can all constant evolve. 7994 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7995 // An instruction outside of the loop can't be derived from a loop PHI. 7996 if (!L->contains(I)) return false; 7997 7998 if (isa<PHINode>(I)) { 7999 // We don't currently keep track of the control flow needed to evaluate 8000 // PHIs, so we cannot handle PHIs inside of loops. 8001 return L->getHeader() == I->getParent(); 8002 } 8003 8004 // If we won't be able to constant fold this expression even if the operands 8005 // are constants, bail early. 8006 return CanConstantFold(I); 8007 } 8008 8009 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8010 /// recursing through each instruction operand until reaching a loop header phi. 8011 static PHINode * 8012 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8013 DenseMap<Instruction *, PHINode *> &PHIMap, 8014 unsigned Depth) { 8015 if (Depth > MaxConstantEvolvingDepth) 8016 return nullptr; 8017 8018 // Otherwise, we can evaluate this instruction if all of its operands are 8019 // constant or derived from a PHI node themselves. 8020 PHINode *PHI = nullptr; 8021 for (Value *Op : UseInst->operands()) { 8022 if (isa<Constant>(Op)) continue; 8023 8024 Instruction *OpInst = dyn_cast<Instruction>(Op); 8025 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8026 8027 PHINode *P = dyn_cast<PHINode>(OpInst); 8028 if (!P) 8029 // If this operand is already visited, reuse the prior result. 8030 // We may have P != PHI if this is the deepest point at which the 8031 // inconsistent paths meet. 8032 P = PHIMap.lookup(OpInst); 8033 if (!P) { 8034 // Recurse and memoize the results, whether a phi is found or not. 8035 // This recursive call invalidates pointers into PHIMap. 8036 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8037 PHIMap[OpInst] = P; 8038 } 8039 if (!P) 8040 return nullptr; // Not evolving from PHI 8041 if (PHI && PHI != P) 8042 return nullptr; // Evolving from multiple different PHIs. 8043 PHI = P; 8044 } 8045 // This is a expression evolving from a constant PHI! 8046 return PHI; 8047 } 8048 8049 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8050 /// in the loop that V is derived from. We allow arbitrary operations along the 8051 /// way, but the operands of an operation must either be constants or a value 8052 /// derived from a constant PHI. If this expression does not fit with these 8053 /// constraints, return null. 8054 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8055 Instruction *I = dyn_cast<Instruction>(V); 8056 if (!I || !canConstantEvolve(I, L)) return nullptr; 8057 8058 if (PHINode *PN = dyn_cast<PHINode>(I)) 8059 return PN; 8060 8061 // Record non-constant instructions contained by the loop. 8062 DenseMap<Instruction *, PHINode *> PHIMap; 8063 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8064 } 8065 8066 /// EvaluateExpression - Given an expression that passes the 8067 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8068 /// in the loop has the value PHIVal. If we can't fold this expression for some 8069 /// reason, return null. 8070 static Constant *EvaluateExpression(Value *V, const Loop *L, 8071 DenseMap<Instruction *, Constant *> &Vals, 8072 const DataLayout &DL, 8073 const TargetLibraryInfo *TLI) { 8074 // Convenient constant check, but redundant for recursive calls. 8075 if (Constant *C = dyn_cast<Constant>(V)) return C; 8076 Instruction *I = dyn_cast<Instruction>(V); 8077 if (!I) return nullptr; 8078 8079 if (Constant *C = Vals.lookup(I)) return C; 8080 8081 // An instruction inside the loop depends on a value outside the loop that we 8082 // weren't given a mapping for, or a value such as a call inside the loop. 8083 if (!canConstantEvolve(I, L)) return nullptr; 8084 8085 // An unmapped PHI can be due to a branch or another loop inside this loop, 8086 // or due to this not being the initial iteration through a loop where we 8087 // couldn't compute the evolution of this particular PHI last time. 8088 if (isa<PHINode>(I)) return nullptr; 8089 8090 std::vector<Constant*> Operands(I->getNumOperands()); 8091 8092 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8093 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8094 if (!Operand) { 8095 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8096 if (!Operands[i]) return nullptr; 8097 continue; 8098 } 8099 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8100 Vals[Operand] = C; 8101 if (!C) return nullptr; 8102 Operands[i] = C; 8103 } 8104 8105 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8106 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8107 Operands[1], DL, TLI); 8108 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8109 if (!LI->isVolatile()) 8110 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8111 } 8112 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8113 } 8114 8115 8116 // If every incoming value to PN except the one for BB is a specific Constant, 8117 // return that, else return nullptr. 8118 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8119 Constant *IncomingVal = nullptr; 8120 8121 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8122 if (PN->getIncomingBlock(i) == BB) 8123 continue; 8124 8125 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8126 if (!CurrentVal) 8127 return nullptr; 8128 8129 if (IncomingVal != CurrentVal) { 8130 if (IncomingVal) 8131 return nullptr; 8132 IncomingVal = CurrentVal; 8133 } 8134 } 8135 8136 return IncomingVal; 8137 } 8138 8139 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8140 /// in the header of its containing loop, we know the loop executes a 8141 /// constant number of times, and the PHI node is just a recurrence 8142 /// involving constants, fold it. 8143 Constant * 8144 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8145 const APInt &BEs, 8146 const Loop *L) { 8147 auto I = ConstantEvolutionLoopExitValue.find(PN); 8148 if (I != ConstantEvolutionLoopExitValue.end()) 8149 return I->second; 8150 8151 if (BEs.ugt(MaxBruteForceIterations)) 8152 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8153 8154 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8155 8156 DenseMap<Instruction *, Constant *> CurrentIterVals; 8157 BasicBlock *Header = L->getHeader(); 8158 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8159 8160 BasicBlock *Latch = L->getLoopLatch(); 8161 if (!Latch) 8162 return nullptr; 8163 8164 for (PHINode &PHI : Header->phis()) { 8165 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8166 CurrentIterVals[&PHI] = StartCST; 8167 } 8168 if (!CurrentIterVals.count(PN)) 8169 return RetVal = nullptr; 8170 8171 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8172 8173 // Execute the loop symbolically to determine the exit value. 8174 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8175 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8176 8177 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8178 unsigned IterationNum = 0; 8179 const DataLayout &DL = getDataLayout(); 8180 for (; ; ++IterationNum) { 8181 if (IterationNum == NumIterations) 8182 return RetVal = CurrentIterVals[PN]; // Got exit value! 8183 8184 // Compute the value of the PHIs for the next iteration. 8185 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8186 DenseMap<Instruction *, Constant *> NextIterVals; 8187 Constant *NextPHI = 8188 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8189 if (!NextPHI) 8190 return nullptr; // Couldn't evaluate! 8191 NextIterVals[PN] = NextPHI; 8192 8193 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8194 8195 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8196 // cease to be able to evaluate one of them or if they stop evolving, 8197 // because that doesn't necessarily prevent us from computing PN. 8198 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8199 for (const auto &I : CurrentIterVals) { 8200 PHINode *PHI = dyn_cast<PHINode>(I.first); 8201 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8202 PHIsToCompute.emplace_back(PHI, I.second); 8203 } 8204 // We use two distinct loops because EvaluateExpression may invalidate any 8205 // iterators into CurrentIterVals. 8206 for (const auto &I : PHIsToCompute) { 8207 PHINode *PHI = I.first; 8208 Constant *&NextPHI = NextIterVals[PHI]; 8209 if (!NextPHI) { // Not already computed. 8210 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8211 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8212 } 8213 if (NextPHI != I.second) 8214 StoppedEvolving = false; 8215 } 8216 8217 // If all entries in CurrentIterVals == NextIterVals then we can stop 8218 // iterating, the loop can't continue to change. 8219 if (StoppedEvolving) 8220 return RetVal = CurrentIterVals[PN]; 8221 8222 CurrentIterVals.swap(NextIterVals); 8223 } 8224 } 8225 8226 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8227 Value *Cond, 8228 bool ExitWhen) { 8229 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8230 if (!PN) return getCouldNotCompute(); 8231 8232 // If the loop is canonicalized, the PHI will have exactly two entries. 8233 // That's the only form we support here. 8234 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8235 8236 DenseMap<Instruction *, Constant *> CurrentIterVals; 8237 BasicBlock *Header = L->getHeader(); 8238 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8239 8240 BasicBlock *Latch = L->getLoopLatch(); 8241 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8242 8243 for (PHINode &PHI : Header->phis()) { 8244 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8245 CurrentIterVals[&PHI] = StartCST; 8246 } 8247 if (!CurrentIterVals.count(PN)) 8248 return getCouldNotCompute(); 8249 8250 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8251 // the loop symbolically to determine when the condition gets a value of 8252 // "ExitWhen". 8253 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8254 const DataLayout &DL = getDataLayout(); 8255 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8256 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8257 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8258 8259 // Couldn't symbolically evaluate. 8260 if (!CondVal) return getCouldNotCompute(); 8261 8262 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8263 ++NumBruteForceTripCountsComputed; 8264 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8265 } 8266 8267 // Update all the PHI nodes for the next iteration. 8268 DenseMap<Instruction *, Constant *> NextIterVals; 8269 8270 // Create a list of which PHIs we need to compute. We want to do this before 8271 // calling EvaluateExpression on them because that may invalidate iterators 8272 // into CurrentIterVals. 8273 SmallVector<PHINode *, 8> PHIsToCompute; 8274 for (const auto &I : CurrentIterVals) { 8275 PHINode *PHI = dyn_cast<PHINode>(I.first); 8276 if (!PHI || PHI->getParent() != Header) continue; 8277 PHIsToCompute.push_back(PHI); 8278 } 8279 for (PHINode *PHI : PHIsToCompute) { 8280 Constant *&NextPHI = NextIterVals[PHI]; 8281 if (NextPHI) continue; // Already computed! 8282 8283 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8284 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8285 } 8286 CurrentIterVals.swap(NextIterVals); 8287 } 8288 8289 // Too many iterations were needed to evaluate. 8290 return getCouldNotCompute(); 8291 } 8292 8293 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8294 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8295 ValuesAtScopes[V]; 8296 // Check to see if we've folded this expression at this loop before. 8297 for (auto &LS : Values) 8298 if (LS.first == L) 8299 return LS.second ? LS.second : V; 8300 8301 Values.emplace_back(L, nullptr); 8302 8303 // Otherwise compute it. 8304 const SCEV *C = computeSCEVAtScope(V, L); 8305 for (auto &LS : reverse(ValuesAtScopes[V])) 8306 if (LS.first == L) { 8307 LS.second = C; 8308 break; 8309 } 8310 return C; 8311 } 8312 8313 /// This builds up a Constant using the ConstantExpr interface. That way, we 8314 /// will return Constants for objects which aren't represented by a 8315 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8316 /// Returns NULL if the SCEV isn't representable as a Constant. 8317 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8318 switch (V->getSCEVType()) { 8319 case scCouldNotCompute: 8320 case scAddRecExpr: 8321 return nullptr; 8322 case scConstant: 8323 return cast<SCEVConstant>(V)->getValue(); 8324 case scUnknown: 8325 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8326 case scSignExtend: { 8327 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8328 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8329 return ConstantExpr::getSExt(CastOp, SS->getType()); 8330 return nullptr; 8331 } 8332 case scZeroExtend: { 8333 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8334 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8335 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8336 return nullptr; 8337 } 8338 case scPtrToInt: { 8339 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8340 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8341 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8342 8343 return nullptr; 8344 } 8345 case scTruncate: { 8346 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8347 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8348 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8349 return nullptr; 8350 } 8351 case scAddExpr: { 8352 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8353 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8354 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8355 unsigned AS = PTy->getAddressSpace(); 8356 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8357 C = ConstantExpr::getBitCast(C, DestPtrTy); 8358 } 8359 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8360 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8361 if (!C2) 8362 return nullptr; 8363 8364 // First pointer! 8365 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8366 unsigned AS = C2->getType()->getPointerAddressSpace(); 8367 std::swap(C, C2); 8368 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8369 // The offsets have been converted to bytes. We can add bytes to an 8370 // i8* by GEP with the byte count in the first index. 8371 C = ConstantExpr::getBitCast(C, DestPtrTy); 8372 } 8373 8374 // Don't bother trying to sum two pointers. We probably can't 8375 // statically compute a load that results from it anyway. 8376 if (C2->getType()->isPointerTy()) 8377 return nullptr; 8378 8379 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8380 if (PTy->getElementType()->isStructTy()) 8381 C2 = ConstantExpr::getIntegerCast( 8382 C2, Type::getInt32Ty(C->getContext()), true); 8383 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8384 } else 8385 C = ConstantExpr::getAdd(C, C2); 8386 } 8387 return C; 8388 } 8389 return nullptr; 8390 } 8391 case scMulExpr: { 8392 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8393 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8394 // Don't bother with pointers at all. 8395 if (C->getType()->isPointerTy()) 8396 return nullptr; 8397 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8398 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8399 if (!C2 || C2->getType()->isPointerTy()) 8400 return nullptr; 8401 C = ConstantExpr::getMul(C, C2); 8402 } 8403 return C; 8404 } 8405 return nullptr; 8406 } 8407 case scUDivExpr: { 8408 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8409 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8410 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8411 if (LHS->getType() == RHS->getType()) 8412 return ConstantExpr::getUDiv(LHS, RHS); 8413 return nullptr; 8414 } 8415 case scSMaxExpr: 8416 case scUMaxExpr: 8417 case scSMinExpr: 8418 case scUMinExpr: 8419 return nullptr; // TODO: smax, umax, smin, umax. 8420 } 8421 llvm_unreachable("Unknown SCEV kind!"); 8422 } 8423 8424 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8425 if (isa<SCEVConstant>(V)) return V; 8426 8427 // If this instruction is evolved from a constant-evolving PHI, compute the 8428 // exit value from the loop without using SCEVs. 8429 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8430 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8431 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8432 const Loop *CurrLoop = this->LI[I->getParent()]; 8433 // Looking for loop exit value. 8434 if (CurrLoop && CurrLoop->getParentLoop() == L && 8435 PN->getParent() == CurrLoop->getHeader()) { 8436 // Okay, there is no closed form solution for the PHI node. Check 8437 // to see if the loop that contains it has a known backedge-taken 8438 // count. If so, we may be able to force computation of the exit 8439 // value. 8440 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8441 // This trivial case can show up in some degenerate cases where 8442 // the incoming IR has not yet been fully simplified. 8443 if (BackedgeTakenCount->isZero()) { 8444 Value *InitValue = nullptr; 8445 bool MultipleInitValues = false; 8446 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8447 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8448 if (!InitValue) 8449 InitValue = PN->getIncomingValue(i); 8450 else if (InitValue != PN->getIncomingValue(i)) { 8451 MultipleInitValues = true; 8452 break; 8453 } 8454 } 8455 } 8456 if (!MultipleInitValues && InitValue) 8457 return getSCEV(InitValue); 8458 } 8459 // Do we have a loop invariant value flowing around the backedge 8460 // for a loop which must execute the backedge? 8461 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8462 isKnownPositive(BackedgeTakenCount) && 8463 PN->getNumIncomingValues() == 2) { 8464 8465 unsigned InLoopPred = 8466 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8467 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8468 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8469 return getSCEV(BackedgeVal); 8470 } 8471 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8472 // Okay, we know how many times the containing loop executes. If 8473 // this is a constant evolving PHI node, get the final value at 8474 // the specified iteration number. 8475 Constant *RV = getConstantEvolutionLoopExitValue( 8476 PN, BTCC->getAPInt(), CurrLoop); 8477 if (RV) return getSCEV(RV); 8478 } 8479 } 8480 8481 // If there is a single-input Phi, evaluate it at our scope. If we can 8482 // prove that this replacement does not break LCSSA form, use new value. 8483 if (PN->getNumOperands() == 1) { 8484 const SCEV *Input = getSCEV(PN->getOperand(0)); 8485 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8486 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8487 // for the simplest case just support constants. 8488 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8489 } 8490 } 8491 8492 // Okay, this is an expression that we cannot symbolically evaluate 8493 // into a SCEV. Check to see if it's possible to symbolically evaluate 8494 // the arguments into constants, and if so, try to constant propagate the 8495 // result. This is particularly useful for computing loop exit values. 8496 if (CanConstantFold(I)) { 8497 SmallVector<Constant *, 4> Operands; 8498 bool MadeImprovement = false; 8499 for (Value *Op : I->operands()) { 8500 if (Constant *C = dyn_cast<Constant>(Op)) { 8501 Operands.push_back(C); 8502 continue; 8503 } 8504 8505 // If any of the operands is non-constant and if they are 8506 // non-integer and non-pointer, don't even try to analyze them 8507 // with scev techniques. 8508 if (!isSCEVable(Op->getType())) 8509 return V; 8510 8511 const SCEV *OrigV = getSCEV(Op); 8512 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8513 MadeImprovement |= OrigV != OpV; 8514 8515 Constant *C = BuildConstantFromSCEV(OpV); 8516 if (!C) return V; 8517 if (C->getType() != Op->getType()) 8518 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8519 Op->getType(), 8520 false), 8521 C, Op->getType()); 8522 Operands.push_back(C); 8523 } 8524 8525 // Check to see if getSCEVAtScope actually made an improvement. 8526 if (MadeImprovement) { 8527 Constant *C = nullptr; 8528 const DataLayout &DL = getDataLayout(); 8529 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8530 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8531 Operands[1], DL, &TLI); 8532 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8533 if (!Load->isVolatile()) 8534 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8535 DL); 8536 } else 8537 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8538 if (!C) return V; 8539 return getSCEV(C); 8540 } 8541 } 8542 } 8543 8544 // This is some other type of SCEVUnknown, just return it. 8545 return V; 8546 } 8547 8548 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8549 // Avoid performing the look-up in the common case where the specified 8550 // expression has no loop-variant portions. 8551 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8552 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8553 if (OpAtScope != Comm->getOperand(i)) { 8554 // Okay, at least one of these operands is loop variant but might be 8555 // foldable. Build a new instance of the folded commutative expression. 8556 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8557 Comm->op_begin()+i); 8558 NewOps.push_back(OpAtScope); 8559 8560 for (++i; i != e; ++i) { 8561 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8562 NewOps.push_back(OpAtScope); 8563 } 8564 if (isa<SCEVAddExpr>(Comm)) 8565 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8566 if (isa<SCEVMulExpr>(Comm)) 8567 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8568 if (isa<SCEVMinMaxExpr>(Comm)) 8569 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8570 llvm_unreachable("Unknown commutative SCEV type!"); 8571 } 8572 } 8573 // If we got here, all operands are loop invariant. 8574 return Comm; 8575 } 8576 8577 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8578 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8579 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8580 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8581 return Div; // must be loop invariant 8582 return getUDivExpr(LHS, RHS); 8583 } 8584 8585 // If this is a loop recurrence for a loop that does not contain L, then we 8586 // are dealing with the final value computed by the loop. 8587 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8588 // First, attempt to evaluate each operand. 8589 // Avoid performing the look-up in the common case where the specified 8590 // expression has no loop-variant portions. 8591 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8592 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8593 if (OpAtScope == AddRec->getOperand(i)) 8594 continue; 8595 8596 // Okay, at least one of these operands is loop variant but might be 8597 // foldable. Build a new instance of the folded commutative expression. 8598 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8599 AddRec->op_begin()+i); 8600 NewOps.push_back(OpAtScope); 8601 for (++i; i != e; ++i) 8602 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8603 8604 const SCEV *FoldedRec = 8605 getAddRecExpr(NewOps, AddRec->getLoop(), 8606 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8607 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8608 // The addrec may be folded to a nonrecurrence, for example, if the 8609 // induction variable is multiplied by zero after constant folding. Go 8610 // ahead and return the folded value. 8611 if (!AddRec) 8612 return FoldedRec; 8613 break; 8614 } 8615 8616 // If the scope is outside the addrec's loop, evaluate it by using the 8617 // loop exit value of the addrec. 8618 if (!AddRec->getLoop()->contains(L)) { 8619 // To evaluate this recurrence, we need to know how many times the AddRec 8620 // loop iterates. Compute this now. 8621 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8622 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8623 8624 // Then, evaluate the AddRec. 8625 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8626 } 8627 8628 return AddRec; 8629 } 8630 8631 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8632 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8633 if (Op == Cast->getOperand()) 8634 return Cast; // must be loop invariant 8635 return getZeroExtendExpr(Op, Cast->getType()); 8636 } 8637 8638 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8639 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8640 if (Op == Cast->getOperand()) 8641 return Cast; // must be loop invariant 8642 return getSignExtendExpr(Op, Cast->getType()); 8643 } 8644 8645 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8646 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8647 if (Op == Cast->getOperand()) 8648 return Cast; // must be loop invariant 8649 return getTruncateExpr(Op, Cast->getType()); 8650 } 8651 8652 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8653 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8654 if (Op == Cast->getOperand()) 8655 return Cast; // must be loop invariant 8656 return getPtrToIntExpr(Op, Cast->getType()); 8657 } 8658 8659 llvm_unreachable("Unknown SCEV type!"); 8660 } 8661 8662 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8663 return getSCEVAtScope(getSCEV(V), L); 8664 } 8665 8666 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8667 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8668 return stripInjectiveFunctions(ZExt->getOperand()); 8669 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8670 return stripInjectiveFunctions(SExt->getOperand()); 8671 return S; 8672 } 8673 8674 /// Finds the minimum unsigned root of the following equation: 8675 /// 8676 /// A * X = B (mod N) 8677 /// 8678 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8679 /// A and B isn't important. 8680 /// 8681 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8682 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8683 ScalarEvolution &SE) { 8684 uint32_t BW = A.getBitWidth(); 8685 assert(BW == SE.getTypeSizeInBits(B->getType())); 8686 assert(A != 0 && "A must be non-zero."); 8687 8688 // 1. D = gcd(A, N) 8689 // 8690 // The gcd of A and N may have only one prime factor: 2. The number of 8691 // trailing zeros in A is its multiplicity 8692 uint32_t Mult2 = A.countTrailingZeros(); 8693 // D = 2^Mult2 8694 8695 // 2. Check if B is divisible by D. 8696 // 8697 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8698 // is not less than multiplicity of this prime factor for D. 8699 if (SE.GetMinTrailingZeros(B) < Mult2) 8700 return SE.getCouldNotCompute(); 8701 8702 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8703 // modulo (N / D). 8704 // 8705 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8706 // (N / D) in general. The inverse itself always fits into BW bits, though, 8707 // so we immediately truncate it. 8708 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8709 APInt Mod(BW + 1, 0); 8710 Mod.setBit(BW - Mult2); // Mod = N / D 8711 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8712 8713 // 4. Compute the minimum unsigned root of the equation: 8714 // I * (B / D) mod (N / D) 8715 // To simplify the computation, we factor out the divide by D: 8716 // (I * B mod N) / D 8717 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8718 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8719 } 8720 8721 /// For a given quadratic addrec, generate coefficients of the corresponding 8722 /// quadratic equation, multiplied by a common value to ensure that they are 8723 /// integers. 8724 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8725 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8726 /// were multiplied by, and BitWidth is the bit width of the original addrec 8727 /// coefficients. 8728 /// This function returns None if the addrec coefficients are not compile- 8729 /// time constants. 8730 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8731 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8732 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8733 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8734 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8735 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8736 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8737 << *AddRec << '\n'); 8738 8739 // We currently can only solve this if the coefficients are constants. 8740 if (!LC || !MC || !NC) { 8741 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8742 return None; 8743 } 8744 8745 APInt L = LC->getAPInt(); 8746 APInt M = MC->getAPInt(); 8747 APInt N = NC->getAPInt(); 8748 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8749 8750 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8751 unsigned NewWidth = BitWidth + 1; 8752 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8753 << BitWidth << '\n'); 8754 // The sign-extension (as opposed to a zero-extension) here matches the 8755 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8756 N = N.sext(NewWidth); 8757 M = M.sext(NewWidth); 8758 L = L.sext(NewWidth); 8759 8760 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8761 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8762 // L+M, L+2M+N, L+3M+3N, ... 8763 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8764 // 8765 // The equation Acc = 0 is then 8766 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8767 // In a quadratic form it becomes: 8768 // N n^2 + (2M-N) n + 2L = 0. 8769 8770 APInt A = N; 8771 APInt B = 2 * M - A; 8772 APInt C = 2 * L; 8773 APInt T = APInt(NewWidth, 2); 8774 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8775 << "x + " << C << ", coeff bw: " << NewWidth 8776 << ", multiplied by " << T << '\n'); 8777 return std::make_tuple(A, B, C, T, BitWidth); 8778 } 8779 8780 /// Helper function to compare optional APInts: 8781 /// (a) if X and Y both exist, return min(X, Y), 8782 /// (b) if neither X nor Y exist, return None, 8783 /// (c) if exactly one of X and Y exists, return that value. 8784 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8785 if (X.hasValue() && Y.hasValue()) { 8786 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8787 APInt XW = X->sextOrSelf(W); 8788 APInt YW = Y->sextOrSelf(W); 8789 return XW.slt(YW) ? *X : *Y; 8790 } 8791 if (!X.hasValue() && !Y.hasValue()) 8792 return None; 8793 return X.hasValue() ? *X : *Y; 8794 } 8795 8796 /// Helper function to truncate an optional APInt to a given BitWidth. 8797 /// When solving addrec-related equations, it is preferable to return a value 8798 /// that has the same bit width as the original addrec's coefficients. If the 8799 /// solution fits in the original bit width, truncate it (except for i1). 8800 /// Returning a value of a different bit width may inhibit some optimizations. 8801 /// 8802 /// In general, a solution to a quadratic equation generated from an addrec 8803 /// may require BW+1 bits, where BW is the bit width of the addrec's 8804 /// coefficients. The reason is that the coefficients of the quadratic 8805 /// equation are BW+1 bits wide (to avoid truncation when converting from 8806 /// the addrec to the equation). 8807 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8808 if (!X.hasValue()) 8809 return None; 8810 unsigned W = X->getBitWidth(); 8811 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8812 return X->trunc(BitWidth); 8813 return X; 8814 } 8815 8816 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8817 /// iterations. The values L, M, N are assumed to be signed, and they 8818 /// should all have the same bit widths. 8819 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8820 /// where BW is the bit width of the addrec's coefficients. 8821 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8822 /// returned as such, otherwise the bit width of the returned value may 8823 /// be greater than BW. 8824 /// 8825 /// This function returns None if 8826 /// (a) the addrec coefficients are not constant, or 8827 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8828 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8829 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8830 static Optional<APInt> 8831 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8832 APInt A, B, C, M; 8833 unsigned BitWidth; 8834 auto T = GetQuadraticEquation(AddRec); 8835 if (!T.hasValue()) 8836 return None; 8837 8838 std::tie(A, B, C, M, BitWidth) = *T; 8839 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8840 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8841 if (!X.hasValue()) 8842 return None; 8843 8844 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8845 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8846 if (!V->isZero()) 8847 return None; 8848 8849 return TruncIfPossible(X, BitWidth); 8850 } 8851 8852 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8853 /// iterations. The values M, N are assumed to be signed, and they 8854 /// should all have the same bit widths. 8855 /// Find the least n such that c(n) does not belong to the given range, 8856 /// while c(n-1) does. 8857 /// 8858 /// This function returns None if 8859 /// (a) the addrec coefficients are not constant, or 8860 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8861 /// bounds of the range. 8862 static Optional<APInt> 8863 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8864 const ConstantRange &Range, ScalarEvolution &SE) { 8865 assert(AddRec->getOperand(0)->isZero() && 8866 "Starting value of addrec should be 0"); 8867 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8868 << Range << ", addrec " << *AddRec << '\n'); 8869 // This case is handled in getNumIterationsInRange. Here we can assume that 8870 // we start in the range. 8871 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8872 "Addrec's initial value should be in range"); 8873 8874 APInt A, B, C, M; 8875 unsigned BitWidth; 8876 auto T = GetQuadraticEquation(AddRec); 8877 if (!T.hasValue()) 8878 return None; 8879 8880 // Be careful about the return value: there can be two reasons for not 8881 // returning an actual number. First, if no solutions to the equations 8882 // were found, and second, if the solutions don't leave the given range. 8883 // The first case means that the actual solution is "unknown", the second 8884 // means that it's known, but not valid. If the solution is unknown, we 8885 // cannot make any conclusions. 8886 // Return a pair: the optional solution and a flag indicating if the 8887 // solution was found. 8888 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8889 // Solve for signed overflow and unsigned overflow, pick the lower 8890 // solution. 8891 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8892 << Bound << " (before multiplying by " << M << ")\n"); 8893 Bound *= M; // The quadratic equation multiplier. 8894 8895 Optional<APInt> SO = None; 8896 if (BitWidth > 1) { 8897 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8898 "signed overflow\n"); 8899 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8900 } 8901 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8902 "unsigned overflow\n"); 8903 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8904 BitWidth+1); 8905 8906 auto LeavesRange = [&] (const APInt &X) { 8907 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8908 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8909 if (Range.contains(V0->getValue())) 8910 return false; 8911 // X should be at least 1, so X-1 is non-negative. 8912 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8913 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8914 if (Range.contains(V1->getValue())) 8915 return true; 8916 return false; 8917 }; 8918 8919 // If SolveQuadraticEquationWrap returns None, it means that there can 8920 // be a solution, but the function failed to find it. We cannot treat it 8921 // as "no solution". 8922 if (!SO.hasValue() || !UO.hasValue()) 8923 return { None, false }; 8924 8925 // Check the smaller value first to see if it leaves the range. 8926 // At this point, both SO and UO must have values. 8927 Optional<APInt> Min = MinOptional(SO, UO); 8928 if (LeavesRange(*Min)) 8929 return { Min, true }; 8930 Optional<APInt> Max = Min == SO ? UO : SO; 8931 if (LeavesRange(*Max)) 8932 return { Max, true }; 8933 8934 // Solutions were found, but were eliminated, hence the "true". 8935 return { None, true }; 8936 }; 8937 8938 std::tie(A, B, C, M, BitWidth) = *T; 8939 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8940 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8941 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8942 auto SL = SolveForBoundary(Lower); 8943 auto SU = SolveForBoundary(Upper); 8944 // If any of the solutions was unknown, no meaninigful conclusions can 8945 // be made. 8946 if (!SL.second || !SU.second) 8947 return None; 8948 8949 // Claim: The correct solution is not some value between Min and Max. 8950 // 8951 // Justification: Assuming that Min and Max are different values, one of 8952 // them is when the first signed overflow happens, the other is when the 8953 // first unsigned overflow happens. Crossing the range boundary is only 8954 // possible via an overflow (treating 0 as a special case of it, modeling 8955 // an overflow as crossing k*2^W for some k). 8956 // 8957 // The interesting case here is when Min was eliminated as an invalid 8958 // solution, but Max was not. The argument is that if there was another 8959 // overflow between Min and Max, it would also have been eliminated if 8960 // it was considered. 8961 // 8962 // For a given boundary, it is possible to have two overflows of the same 8963 // type (signed/unsigned) without having the other type in between: this 8964 // can happen when the vertex of the parabola is between the iterations 8965 // corresponding to the overflows. This is only possible when the two 8966 // overflows cross k*2^W for the same k. In such case, if the second one 8967 // left the range (and was the first one to do so), the first overflow 8968 // would have to enter the range, which would mean that either we had left 8969 // the range before or that we started outside of it. Both of these cases 8970 // are contradictions. 8971 // 8972 // Claim: In the case where SolveForBoundary returns None, the correct 8973 // solution is not some value between the Max for this boundary and the 8974 // Min of the other boundary. 8975 // 8976 // Justification: Assume that we had such Max_A and Min_B corresponding 8977 // to range boundaries A and B and such that Max_A < Min_B. If there was 8978 // a solution between Max_A and Min_B, it would have to be caused by an 8979 // overflow corresponding to either A or B. It cannot correspond to B, 8980 // since Min_B is the first occurrence of such an overflow. If it 8981 // corresponded to A, it would have to be either a signed or an unsigned 8982 // overflow that is larger than both eliminated overflows for A. But 8983 // between the eliminated overflows and this overflow, the values would 8984 // cover the entire value space, thus crossing the other boundary, which 8985 // is a contradiction. 8986 8987 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8988 } 8989 8990 ScalarEvolution::ExitLimit 8991 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8992 bool AllowPredicates) { 8993 8994 // This is only used for loops with a "x != y" exit test. The exit condition 8995 // is now expressed as a single expression, V = x-y. So the exit test is 8996 // effectively V != 0. We know and take advantage of the fact that this 8997 // expression only being used in a comparison by zero context. 8998 8999 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9000 // If the value is a constant 9001 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9002 // If the value is already zero, the branch will execute zero times. 9003 if (C->getValue()->isZero()) return C; 9004 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9005 } 9006 9007 const SCEVAddRecExpr *AddRec = 9008 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9009 9010 if (!AddRec && AllowPredicates) 9011 // Try to make this an AddRec using runtime tests, in the first X 9012 // iterations of this loop, where X is the SCEV expression found by the 9013 // algorithm below. 9014 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9015 9016 if (!AddRec || AddRec->getLoop() != L) 9017 return getCouldNotCompute(); 9018 9019 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9020 // the quadratic equation to solve it. 9021 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9022 // We can only use this value if the chrec ends up with an exact zero 9023 // value at this index. When solving for "X*X != 5", for example, we 9024 // should not accept a root of 2. 9025 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9026 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9027 return ExitLimit(R, R, false, Predicates); 9028 } 9029 return getCouldNotCompute(); 9030 } 9031 9032 // Otherwise we can only handle this if it is affine. 9033 if (!AddRec->isAffine()) 9034 return getCouldNotCompute(); 9035 9036 // If this is an affine expression, the execution count of this branch is 9037 // the minimum unsigned root of the following equation: 9038 // 9039 // Start + Step*N = 0 (mod 2^BW) 9040 // 9041 // equivalent to: 9042 // 9043 // Step*N = -Start (mod 2^BW) 9044 // 9045 // where BW is the common bit width of Start and Step. 9046 9047 // Get the initial value for the loop. 9048 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9049 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9050 9051 // For now we handle only constant steps. 9052 // 9053 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9054 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9055 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9056 // We have not yet seen any such cases. 9057 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9058 if (!StepC || StepC->getValue()->isZero()) 9059 return getCouldNotCompute(); 9060 9061 // For positive steps (counting up until unsigned overflow): 9062 // N = -Start/Step (as unsigned) 9063 // For negative steps (counting down to zero): 9064 // N = Start/-Step 9065 // First compute the unsigned distance from zero in the direction of Step. 9066 bool CountDown = StepC->getAPInt().isNegative(); 9067 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9068 9069 // Handle unitary steps, which cannot wraparound. 9070 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9071 // N = Distance (as unsigned) 9072 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9073 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9074 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9075 if (MaxBECountBase.ult(MaxBECount)) 9076 MaxBECount = MaxBECountBase; 9077 9078 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9079 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9080 // case, and see if we can improve the bound. 9081 // 9082 // Explicitly handling this here is necessary because getUnsignedRange 9083 // isn't context-sensitive; it doesn't know that we only care about the 9084 // range inside the loop. 9085 const SCEV *Zero = getZero(Distance->getType()); 9086 const SCEV *One = getOne(Distance->getType()); 9087 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9088 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9089 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9090 // as "unsigned_max(Distance + 1) - 1". 9091 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9092 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9093 } 9094 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9095 } 9096 9097 // If the condition controls loop exit (the loop exits only if the expression 9098 // is true) and the addition is no-wrap we can use unsigned divide to 9099 // compute the backedge count. In this case, the step may not divide the 9100 // distance, but we don't care because if the condition is "missed" the loop 9101 // will have undefined behavior due to wrapping. 9102 if (ControlsExit && AddRec->hasNoSelfWrap() && 9103 loopHasNoAbnormalExits(AddRec->getLoop())) { 9104 const SCEV *Exact = 9105 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9106 const SCEV *Max = 9107 Exact == getCouldNotCompute() 9108 ? Exact 9109 : getConstant(getUnsignedRangeMax(Exact)); 9110 return ExitLimit(Exact, Max, false, Predicates); 9111 } 9112 9113 // Solve the general equation. 9114 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9115 getNegativeSCEV(Start), *this); 9116 const SCEV *M = E == getCouldNotCompute() 9117 ? E 9118 : getConstant(getUnsignedRangeMax(E)); 9119 return ExitLimit(E, M, false, Predicates); 9120 } 9121 9122 ScalarEvolution::ExitLimit 9123 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9124 // Loops that look like: while (X == 0) are very strange indeed. We don't 9125 // handle them yet except for the trivial case. This could be expanded in the 9126 // future as needed. 9127 9128 // If the value is a constant, check to see if it is known to be non-zero 9129 // already. If so, the backedge will execute zero times. 9130 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9131 if (!C->getValue()->isZero()) 9132 return getZero(C->getType()); 9133 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9134 } 9135 9136 // We could implement others, but I really doubt anyone writes loops like 9137 // this, and if they did, they would already be constant folded. 9138 return getCouldNotCompute(); 9139 } 9140 9141 std::pair<const BasicBlock *, const BasicBlock *> 9142 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9143 const { 9144 // If the block has a unique predecessor, then there is no path from the 9145 // predecessor to the block that does not go through the direct edge 9146 // from the predecessor to the block. 9147 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9148 return {Pred, BB}; 9149 9150 // A loop's header is defined to be a block that dominates the loop. 9151 // If the header has a unique predecessor outside the loop, it must be 9152 // a block that has exactly one successor that can reach the loop. 9153 if (const Loop *L = LI.getLoopFor(BB)) 9154 return {L->getLoopPredecessor(), L->getHeader()}; 9155 9156 return {nullptr, nullptr}; 9157 } 9158 9159 /// SCEV structural equivalence is usually sufficient for testing whether two 9160 /// expressions are equal, however for the purposes of looking for a condition 9161 /// guarding a loop, it can be useful to be a little more general, since a 9162 /// front-end may have replicated the controlling expression. 9163 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9164 // Quick check to see if they are the same SCEV. 9165 if (A == B) return true; 9166 9167 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9168 // Not all instructions that are "identical" compute the same value. For 9169 // instance, two distinct alloca instructions allocating the same type are 9170 // identical and do not read memory; but compute distinct values. 9171 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9172 }; 9173 9174 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9175 // two different instructions with the same value. Check for this case. 9176 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9177 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9178 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9179 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9180 if (ComputesEqualValues(AI, BI)) 9181 return true; 9182 9183 // Otherwise assume they may have a different value. 9184 return false; 9185 } 9186 9187 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9188 const SCEV *&LHS, const SCEV *&RHS, 9189 unsigned Depth) { 9190 bool Changed = false; 9191 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9192 // '0 != 0'. 9193 auto TrivialCase = [&](bool TriviallyTrue) { 9194 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9195 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9196 return true; 9197 }; 9198 // If we hit the max recursion limit bail out. 9199 if (Depth >= 3) 9200 return false; 9201 9202 // Canonicalize a constant to the right side. 9203 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9204 // Check for both operands constant. 9205 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9206 if (ConstantExpr::getICmp(Pred, 9207 LHSC->getValue(), 9208 RHSC->getValue())->isNullValue()) 9209 return TrivialCase(false); 9210 else 9211 return TrivialCase(true); 9212 } 9213 // Otherwise swap the operands to put the constant on the right. 9214 std::swap(LHS, RHS); 9215 Pred = ICmpInst::getSwappedPredicate(Pred); 9216 Changed = true; 9217 } 9218 9219 // If we're comparing an addrec with a value which is loop-invariant in the 9220 // addrec's loop, put the addrec on the left. Also make a dominance check, 9221 // as both operands could be addrecs loop-invariant in each other's loop. 9222 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9223 const Loop *L = AR->getLoop(); 9224 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9225 std::swap(LHS, RHS); 9226 Pred = ICmpInst::getSwappedPredicate(Pred); 9227 Changed = true; 9228 } 9229 } 9230 9231 // If there's a constant operand, canonicalize comparisons with boundary 9232 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9233 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9234 const APInt &RA = RC->getAPInt(); 9235 9236 bool SimplifiedByConstantRange = false; 9237 9238 if (!ICmpInst::isEquality(Pred)) { 9239 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9240 if (ExactCR.isFullSet()) 9241 return TrivialCase(true); 9242 else if (ExactCR.isEmptySet()) 9243 return TrivialCase(false); 9244 9245 APInt NewRHS; 9246 CmpInst::Predicate NewPred; 9247 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9248 ICmpInst::isEquality(NewPred)) { 9249 // We were able to convert an inequality to an equality. 9250 Pred = NewPred; 9251 RHS = getConstant(NewRHS); 9252 Changed = SimplifiedByConstantRange = true; 9253 } 9254 } 9255 9256 if (!SimplifiedByConstantRange) { 9257 switch (Pred) { 9258 default: 9259 break; 9260 case ICmpInst::ICMP_EQ: 9261 case ICmpInst::ICMP_NE: 9262 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9263 if (!RA) 9264 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9265 if (const SCEVMulExpr *ME = 9266 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9267 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9268 ME->getOperand(0)->isAllOnesValue()) { 9269 RHS = AE->getOperand(1); 9270 LHS = ME->getOperand(1); 9271 Changed = true; 9272 } 9273 break; 9274 9275 9276 // The "Should have been caught earlier!" messages refer to the fact 9277 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9278 // should have fired on the corresponding cases, and canonicalized the 9279 // check to trivial case. 9280 9281 case ICmpInst::ICMP_UGE: 9282 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9283 Pred = ICmpInst::ICMP_UGT; 9284 RHS = getConstant(RA - 1); 9285 Changed = true; 9286 break; 9287 case ICmpInst::ICMP_ULE: 9288 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9289 Pred = ICmpInst::ICMP_ULT; 9290 RHS = getConstant(RA + 1); 9291 Changed = true; 9292 break; 9293 case ICmpInst::ICMP_SGE: 9294 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9295 Pred = ICmpInst::ICMP_SGT; 9296 RHS = getConstant(RA - 1); 9297 Changed = true; 9298 break; 9299 case ICmpInst::ICMP_SLE: 9300 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9301 Pred = ICmpInst::ICMP_SLT; 9302 RHS = getConstant(RA + 1); 9303 Changed = true; 9304 break; 9305 } 9306 } 9307 } 9308 9309 // Check for obvious equality. 9310 if (HasSameValue(LHS, RHS)) { 9311 if (ICmpInst::isTrueWhenEqual(Pred)) 9312 return TrivialCase(true); 9313 if (ICmpInst::isFalseWhenEqual(Pred)) 9314 return TrivialCase(false); 9315 } 9316 9317 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9318 // adding or subtracting 1 from one of the operands. 9319 switch (Pred) { 9320 case ICmpInst::ICMP_SLE: 9321 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9322 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9323 SCEV::FlagNSW); 9324 Pred = ICmpInst::ICMP_SLT; 9325 Changed = true; 9326 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9327 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9328 SCEV::FlagNSW); 9329 Pred = ICmpInst::ICMP_SLT; 9330 Changed = true; 9331 } 9332 break; 9333 case ICmpInst::ICMP_SGE: 9334 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9335 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9336 SCEV::FlagNSW); 9337 Pred = ICmpInst::ICMP_SGT; 9338 Changed = true; 9339 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9340 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9341 SCEV::FlagNSW); 9342 Pred = ICmpInst::ICMP_SGT; 9343 Changed = true; 9344 } 9345 break; 9346 case ICmpInst::ICMP_ULE: 9347 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9348 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9349 SCEV::FlagNUW); 9350 Pred = ICmpInst::ICMP_ULT; 9351 Changed = true; 9352 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9353 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9354 Pred = ICmpInst::ICMP_ULT; 9355 Changed = true; 9356 } 9357 break; 9358 case ICmpInst::ICMP_UGE: 9359 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9360 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9361 Pred = ICmpInst::ICMP_UGT; 9362 Changed = true; 9363 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9364 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9365 SCEV::FlagNUW); 9366 Pred = ICmpInst::ICMP_UGT; 9367 Changed = true; 9368 } 9369 break; 9370 default: 9371 break; 9372 } 9373 9374 // TODO: More simplifications are possible here. 9375 9376 // Recursively simplify until we either hit a recursion limit or nothing 9377 // changes. 9378 if (Changed) 9379 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9380 9381 return Changed; 9382 } 9383 9384 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9385 return getSignedRangeMax(S).isNegative(); 9386 } 9387 9388 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9389 return getSignedRangeMin(S).isStrictlyPositive(); 9390 } 9391 9392 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9393 return !getSignedRangeMin(S).isNegative(); 9394 } 9395 9396 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9397 return !getSignedRangeMax(S).isStrictlyPositive(); 9398 } 9399 9400 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9401 return isKnownNegative(S) || isKnownPositive(S); 9402 } 9403 9404 std::pair<const SCEV *, const SCEV *> 9405 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9406 // Compute SCEV on entry of loop L. 9407 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9408 if (Start == getCouldNotCompute()) 9409 return { Start, Start }; 9410 // Compute post increment SCEV for loop L. 9411 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9412 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9413 return { Start, PostInc }; 9414 } 9415 9416 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9417 const SCEV *LHS, const SCEV *RHS) { 9418 // First collect all loops. 9419 SmallPtrSet<const Loop *, 8> LoopsUsed; 9420 getUsedLoops(LHS, LoopsUsed); 9421 getUsedLoops(RHS, LoopsUsed); 9422 9423 if (LoopsUsed.empty()) 9424 return false; 9425 9426 // Domination relationship must be a linear order on collected loops. 9427 #ifndef NDEBUG 9428 for (auto *L1 : LoopsUsed) 9429 for (auto *L2 : LoopsUsed) 9430 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9431 DT.dominates(L2->getHeader(), L1->getHeader())) && 9432 "Domination relationship is not a linear order"); 9433 #endif 9434 9435 const Loop *MDL = 9436 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9437 [&](const Loop *L1, const Loop *L2) { 9438 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9439 }); 9440 9441 // Get init and post increment value for LHS. 9442 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9443 // if LHS contains unknown non-invariant SCEV then bail out. 9444 if (SplitLHS.first == getCouldNotCompute()) 9445 return false; 9446 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9447 // Get init and post increment value for RHS. 9448 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9449 // if RHS contains unknown non-invariant SCEV then bail out. 9450 if (SplitRHS.first == getCouldNotCompute()) 9451 return false; 9452 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9453 // It is possible that init SCEV contains an invariant load but it does 9454 // not dominate MDL and is not available at MDL loop entry, so we should 9455 // check it here. 9456 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9457 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9458 return false; 9459 9460 // It seems backedge guard check is faster than entry one so in some cases 9461 // it can speed up whole estimation by short circuit 9462 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9463 SplitRHS.second) && 9464 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9465 } 9466 9467 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9468 const SCEV *LHS, const SCEV *RHS) { 9469 // Canonicalize the inputs first. 9470 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9471 9472 if (isKnownViaInduction(Pred, LHS, RHS)) 9473 return true; 9474 9475 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9476 return true; 9477 9478 // Otherwise see what can be done with some simple reasoning. 9479 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9480 } 9481 9482 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9483 const SCEV *LHS, const SCEV *RHS, 9484 const Instruction *Context) { 9485 // TODO: Analyze guards and assumes from Context's block. 9486 return isKnownPredicate(Pred, LHS, RHS) || 9487 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9488 } 9489 9490 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9491 const SCEVAddRecExpr *LHS, 9492 const SCEV *RHS) { 9493 const Loop *L = LHS->getLoop(); 9494 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9495 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9496 } 9497 9498 Optional<ScalarEvolution::MonotonicPredicateType> 9499 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9500 ICmpInst::Predicate Pred, 9501 Optional<const SCEV *> NumIter, 9502 const Instruction *Context) { 9503 assert((!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) && 9504 "provided number of iterations must be computable!"); 9505 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred, NumIter, Context); 9506 9507 #ifndef NDEBUG 9508 // Verify an invariant: inverting the predicate should turn a monotonically 9509 // increasing change to a monotonically decreasing one, and vice versa. 9510 if (Result) { 9511 auto ResultSwapped = getMonotonicPredicateTypeImpl( 9512 LHS, ICmpInst::getSwappedPredicate(Pred), NumIter, Context); 9513 9514 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9515 assert(ResultSwapped.getValue() != Result.getValue() && 9516 "monotonicity should flip as we flip the predicate"); 9517 } 9518 #endif 9519 9520 return Result; 9521 } 9522 9523 Optional<ScalarEvolution::MonotonicPredicateType> 9524 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9525 ICmpInst::Predicate Pred, 9526 Optional<const SCEV *> NumIter, 9527 const Instruction *Context) { 9528 // A zero step value for LHS means the induction variable is essentially a 9529 // loop invariant value. We don't really depend on the predicate actually 9530 // flipping from false to true (for increasing predicates, and the other way 9531 // around for decreasing predicates), all we care about is that *if* the 9532 // predicate changes then it only changes from false to true. 9533 // 9534 // A zero step value in itself is not very useful, but there may be places 9535 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9536 // as general as possible. 9537 9538 // Only handle LE/LT/GE/GT predicates. 9539 if (!ICmpInst::isRelational(Pred)) 9540 return None; 9541 9542 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9543 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9544 "Should be greater or less!"); 9545 9546 bool IsUnsigned = ICmpInst::isUnsigned(Pred); 9547 assert((IsUnsigned || ICmpInst::isSigned(Pred)) && 9548 "Should be either signed or unsigned!"); 9549 // Check if we can prove no-wrap in the relevant range. 9550 9551 const SCEV *Step = LHS->getStepRecurrence(*this); 9552 bool IsStepNonNegative = isKnownNonNegative(Step); 9553 bool IsStepNonPositive = isKnownNonPositive(Step); 9554 // We need to know which direction the iteration is going. 9555 if (!IsStepNonNegative && !IsStepNonPositive) 9556 return None; 9557 9558 auto ProvedNoWrap = [&]() { 9559 // If the AddRec already has the flag, we are done. 9560 if (IsUnsigned ? LHS->hasNoUnsignedWrap() : LHS->hasNoSignedWrap()) 9561 return true; 9562 9563 if (!NumIter) 9564 return false; 9565 // We could not prove no-wrap on all iteration space. Can we prove it for 9566 // first iterations? In order to achieve it, check that: 9567 // 1. The addrec does not self-wrap; 9568 // 2. start <= end for non-negative step and start >= end for non-positive 9569 // step. 9570 bool HasNoSelfWrap = LHS->hasNoSelfWrap(); 9571 if (!HasNoSelfWrap) 9572 // If num iter has same type as the AddRec, and step is +/- 1, even max 9573 // possible number of iterations is not enough to self-wrap. 9574 if (NumIter.getValue()->getType() == LHS->getType()) 9575 if (Step == getOne(LHS->getType()) || 9576 Step == getMinusOne(LHS->getType())) 9577 HasNoSelfWrap = true; 9578 if (!HasNoSelfWrap) 9579 return false; 9580 const SCEV *Start = LHS->getStart(); 9581 const SCEV *End = LHS->evaluateAtIteration(*NumIter, *this); 9582 ICmpInst::Predicate NoOverflowPred = 9583 IsStepNonNegative ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SGE; 9584 if (IsUnsigned) 9585 NoOverflowPred = ICmpInst::getUnsignedPredicate(NoOverflowPred); 9586 return isKnownPredicateAt(NoOverflowPred, Start, End, Context); 9587 }; 9588 9589 // If nothing worked, bail. 9590 if (!ProvedNoWrap()) 9591 return None; 9592 9593 if (IsUnsigned) 9594 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9595 else { 9596 if (IsStepNonNegative) 9597 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9598 9599 if (IsStepNonPositive) 9600 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9601 9602 return None; 9603 } 9604 } 9605 9606 Optional<ScalarEvolution::LoopInvariantPredicate> 9607 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9608 const SCEV *LHS, const SCEV *RHS, 9609 const Loop *L) { 9610 9611 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9612 if (!isLoopInvariant(RHS, L)) { 9613 if (!isLoopInvariant(LHS, L)) 9614 return None; 9615 9616 std::swap(LHS, RHS); 9617 Pred = ICmpInst::getSwappedPredicate(Pred); 9618 } 9619 9620 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9621 if (!ArLHS || ArLHS->getLoop() != L) 9622 return None; 9623 9624 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9625 if (!MonotonicType) 9626 return None; 9627 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9628 // true as the loop iterates, and the backedge is control dependent on 9629 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9630 // 9631 // * if the predicate was false in the first iteration then the predicate 9632 // is never evaluated again, since the loop exits without taking the 9633 // backedge. 9634 // * if the predicate was true in the first iteration then it will 9635 // continue to be true for all future iterations since it is 9636 // monotonically increasing. 9637 // 9638 // For both the above possibilities, we can replace the loop varying 9639 // predicate with its value on the first iteration of the loop (which is 9640 // loop invariant). 9641 // 9642 // A similar reasoning applies for a monotonically decreasing predicate, by 9643 // replacing true with false and false with true in the above two bullets. 9644 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9645 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9646 9647 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9648 return None; 9649 9650 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9651 } 9652 9653 Optional<ScalarEvolution::LoopInvariantPredicate> 9654 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9655 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9656 const Instruction *Context, const SCEV *MaxIter) { 9657 // Try to prove the following set of facts: 9658 // - The predicate is monotonic in the iteration space. 9659 // - If the check does not fail on the 1st iteration: 9660 // - It will not fail on the MaxIter'th iteration. 9661 // If the check does fail on the 1st iteration, we leave the loop and no 9662 // other checks matter. 9663 9664 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9665 if (!isLoopInvariant(RHS, L)) { 9666 if (!isLoopInvariant(LHS, L)) 9667 return None; 9668 9669 std::swap(LHS, RHS); 9670 Pred = ICmpInst::getSwappedPredicate(Pred); 9671 } 9672 9673 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9674 if (!AR || AR->getLoop() != L) 9675 return None; 9676 9677 if (!getMonotonicPredicateType(AR, Pred, MaxIter, Context)) 9678 return None; 9679 9680 // Value of IV on suggested last iteration. 9681 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9682 // Does it still meet the requirement? 9683 if (!isKnownPredicateAt(Pred, Last, RHS, Context)) 9684 return None; 9685 9686 // Everything is fine. 9687 return ScalarEvolution::LoopInvariantPredicate(Pred, AR->getStart(), RHS); 9688 } 9689 9690 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9691 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9692 if (HasSameValue(LHS, RHS)) 9693 return ICmpInst::isTrueWhenEqual(Pred); 9694 9695 // This code is split out from isKnownPredicate because it is called from 9696 // within isLoopEntryGuardedByCond. 9697 9698 auto CheckRanges = 9699 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9700 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9701 .contains(RangeLHS); 9702 }; 9703 9704 // The check at the top of the function catches the case where the values are 9705 // known to be equal. 9706 if (Pred == CmpInst::ICMP_EQ) 9707 return false; 9708 9709 if (Pred == CmpInst::ICMP_NE) 9710 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9711 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9712 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9713 9714 if (CmpInst::isSigned(Pred)) 9715 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9716 9717 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9718 } 9719 9720 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9721 const SCEV *LHS, 9722 const SCEV *RHS) { 9723 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9724 // Return Y via OutY. 9725 auto MatchBinaryAddToConst = 9726 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9727 SCEV::NoWrapFlags ExpectedFlags) { 9728 const SCEV *NonConstOp, *ConstOp; 9729 SCEV::NoWrapFlags FlagsPresent; 9730 9731 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9732 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9733 return false; 9734 9735 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9736 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9737 }; 9738 9739 APInt C; 9740 9741 switch (Pred) { 9742 default: 9743 break; 9744 9745 case ICmpInst::ICMP_SGE: 9746 std::swap(LHS, RHS); 9747 LLVM_FALLTHROUGH; 9748 case ICmpInst::ICMP_SLE: 9749 // X s<= (X + C)<nsw> if C >= 0 9750 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9751 return true; 9752 9753 // (X + C)<nsw> s<= X if C <= 0 9754 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9755 !C.isStrictlyPositive()) 9756 return true; 9757 break; 9758 9759 case ICmpInst::ICMP_SGT: 9760 std::swap(LHS, RHS); 9761 LLVM_FALLTHROUGH; 9762 case ICmpInst::ICMP_SLT: 9763 // X s< (X + C)<nsw> if C > 0 9764 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9765 C.isStrictlyPositive()) 9766 return true; 9767 9768 // (X + C)<nsw> s< X if C < 0 9769 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9770 return true; 9771 break; 9772 9773 case ICmpInst::ICMP_UGE: 9774 std::swap(LHS, RHS); 9775 LLVM_FALLTHROUGH; 9776 case ICmpInst::ICMP_ULE: 9777 // X u<= (X + C)<nuw> for any C 9778 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9779 return true; 9780 break; 9781 9782 case ICmpInst::ICMP_UGT: 9783 std::swap(LHS, RHS); 9784 LLVM_FALLTHROUGH; 9785 case ICmpInst::ICMP_ULT: 9786 // X u< (X + C)<nuw> if C != 0 9787 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9788 return true; 9789 break; 9790 } 9791 9792 return false; 9793 } 9794 9795 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9796 const SCEV *LHS, 9797 const SCEV *RHS) { 9798 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9799 return false; 9800 9801 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9802 // the stack can result in exponential time complexity. 9803 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9804 9805 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9806 // 9807 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9808 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9809 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9810 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9811 // use isKnownPredicate later if needed. 9812 return isKnownNonNegative(RHS) && 9813 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9814 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9815 } 9816 9817 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9818 ICmpInst::Predicate Pred, 9819 const SCEV *LHS, const SCEV *RHS) { 9820 // No need to even try if we know the module has no guards. 9821 if (!HasGuards) 9822 return false; 9823 9824 return any_of(*BB, [&](const Instruction &I) { 9825 using namespace llvm::PatternMatch; 9826 9827 Value *Condition; 9828 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9829 m_Value(Condition))) && 9830 isImpliedCond(Pred, LHS, RHS, Condition, false); 9831 }); 9832 } 9833 9834 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9835 /// protected by a conditional between LHS and RHS. This is used to 9836 /// to eliminate casts. 9837 bool 9838 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9839 ICmpInst::Predicate Pred, 9840 const SCEV *LHS, const SCEV *RHS) { 9841 // Interpret a null as meaning no loop, where there is obviously no guard 9842 // (interprocedural conditions notwithstanding). 9843 if (!L) return true; 9844 9845 if (VerifyIR) 9846 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9847 "This cannot be done on broken IR!"); 9848 9849 9850 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9851 return true; 9852 9853 BasicBlock *Latch = L->getLoopLatch(); 9854 if (!Latch) 9855 return false; 9856 9857 BranchInst *LoopContinuePredicate = 9858 dyn_cast<BranchInst>(Latch->getTerminator()); 9859 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9860 isImpliedCond(Pred, LHS, RHS, 9861 LoopContinuePredicate->getCondition(), 9862 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9863 return true; 9864 9865 // We don't want more than one activation of the following loops on the stack 9866 // -- that can lead to O(n!) time complexity. 9867 if (WalkingBEDominatingConds) 9868 return false; 9869 9870 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9871 9872 // See if we can exploit a trip count to prove the predicate. 9873 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9874 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9875 if (LatchBECount != getCouldNotCompute()) { 9876 // We know that Latch branches back to the loop header exactly 9877 // LatchBECount times. This means the backdege condition at Latch is 9878 // equivalent to "{0,+,1} u< LatchBECount". 9879 Type *Ty = LatchBECount->getType(); 9880 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9881 const SCEV *LoopCounter = 9882 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9883 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9884 LatchBECount)) 9885 return true; 9886 } 9887 9888 // Check conditions due to any @llvm.assume intrinsics. 9889 for (auto &AssumeVH : AC.assumptions()) { 9890 if (!AssumeVH) 9891 continue; 9892 auto *CI = cast<CallInst>(AssumeVH); 9893 if (!DT.dominates(CI, Latch->getTerminator())) 9894 continue; 9895 9896 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9897 return true; 9898 } 9899 9900 // If the loop is not reachable from the entry block, we risk running into an 9901 // infinite loop as we walk up into the dom tree. These loops do not matter 9902 // anyway, so we just return a conservative answer when we see them. 9903 if (!DT.isReachableFromEntry(L->getHeader())) 9904 return false; 9905 9906 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9907 return true; 9908 9909 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9910 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9911 assert(DTN && "should reach the loop header before reaching the root!"); 9912 9913 BasicBlock *BB = DTN->getBlock(); 9914 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9915 return true; 9916 9917 BasicBlock *PBB = BB->getSinglePredecessor(); 9918 if (!PBB) 9919 continue; 9920 9921 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9922 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9923 continue; 9924 9925 Value *Condition = ContinuePredicate->getCondition(); 9926 9927 // If we have an edge `E` within the loop body that dominates the only 9928 // latch, the condition guarding `E` also guards the backedge. This 9929 // reasoning works only for loops with a single latch. 9930 9931 BasicBlockEdge DominatingEdge(PBB, BB); 9932 if (DominatingEdge.isSingleEdge()) { 9933 // We're constructively (and conservatively) enumerating edges within the 9934 // loop body that dominate the latch. The dominator tree better agree 9935 // with us on this: 9936 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9937 9938 if (isImpliedCond(Pred, LHS, RHS, Condition, 9939 BB != ContinuePredicate->getSuccessor(0))) 9940 return true; 9941 } 9942 } 9943 9944 return false; 9945 } 9946 9947 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9948 ICmpInst::Predicate Pred, 9949 const SCEV *LHS, 9950 const SCEV *RHS) { 9951 if (VerifyIR) 9952 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9953 "This cannot be done on broken IR!"); 9954 9955 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9956 return true; 9957 9958 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9959 // the facts (a >= b && a != b) separately. A typical situation is when the 9960 // non-strict comparison is known from ranges and non-equality is known from 9961 // dominating predicates. If we are proving strict comparison, we always try 9962 // to prove non-equality and non-strict comparison separately. 9963 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9964 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9965 bool ProvedNonStrictComparison = false; 9966 bool ProvedNonEquality = false; 9967 9968 if (ProvingStrictComparison) { 9969 ProvedNonStrictComparison = 9970 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9971 ProvedNonEquality = 9972 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9973 if (ProvedNonStrictComparison && ProvedNonEquality) 9974 return true; 9975 } 9976 9977 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9978 auto ProveViaGuard = [&](const BasicBlock *Block) { 9979 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9980 return true; 9981 if (ProvingStrictComparison) { 9982 if (!ProvedNonStrictComparison) 9983 ProvedNonStrictComparison = 9984 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9985 if (!ProvedNonEquality) 9986 ProvedNonEquality = 9987 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9988 if (ProvedNonStrictComparison && ProvedNonEquality) 9989 return true; 9990 } 9991 return false; 9992 }; 9993 9994 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9995 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9996 const Instruction *Context = &BB->front(); 9997 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9998 return true; 9999 if (ProvingStrictComparison) { 10000 if (!ProvedNonStrictComparison) 10001 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 10002 Condition, Inverse, Context); 10003 if (!ProvedNonEquality) 10004 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 10005 Condition, Inverse, Context); 10006 if (ProvedNonStrictComparison && ProvedNonEquality) 10007 return true; 10008 } 10009 return false; 10010 }; 10011 10012 // Starting at the block's predecessor, climb up the predecessor chain, as long 10013 // as there are predecessors that can be found that have unique successors 10014 // leading to the original block. 10015 const Loop *ContainingLoop = LI.getLoopFor(BB); 10016 const BasicBlock *PredBB; 10017 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10018 PredBB = ContainingLoop->getLoopPredecessor(); 10019 else 10020 PredBB = BB->getSinglePredecessor(); 10021 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10022 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10023 if (ProveViaGuard(Pair.first)) 10024 return true; 10025 10026 const BranchInst *LoopEntryPredicate = 10027 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10028 if (!LoopEntryPredicate || 10029 LoopEntryPredicate->isUnconditional()) 10030 continue; 10031 10032 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10033 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10034 return true; 10035 } 10036 10037 // Check conditions due to any @llvm.assume intrinsics. 10038 for (auto &AssumeVH : AC.assumptions()) { 10039 if (!AssumeVH) 10040 continue; 10041 auto *CI = cast<CallInst>(AssumeVH); 10042 if (!DT.dominates(CI, BB)) 10043 continue; 10044 10045 if (ProveViaCond(CI->getArgOperand(0), false)) 10046 return true; 10047 } 10048 10049 return false; 10050 } 10051 10052 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10053 ICmpInst::Predicate Pred, 10054 const SCEV *LHS, 10055 const SCEV *RHS) { 10056 // Interpret a null as meaning no loop, where there is obviously no guard 10057 // (interprocedural conditions notwithstanding). 10058 if (!L) 10059 return false; 10060 10061 // Both LHS and RHS must be available at loop entry. 10062 assert(isAvailableAtLoopEntry(LHS, L) && 10063 "LHS is not available at Loop Entry"); 10064 assert(isAvailableAtLoopEntry(RHS, L) && 10065 "RHS is not available at Loop Entry"); 10066 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10067 } 10068 10069 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10070 const SCEV *RHS, 10071 const Value *FoundCondValue, bool Inverse, 10072 const Instruction *Context) { 10073 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10074 return false; 10075 10076 auto ClearOnExit = 10077 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10078 10079 // Recursively handle And and Or conditions. 10080 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 10081 if (BO->getOpcode() == Instruction::And) { 10082 if (!Inverse) 10083 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10084 Context) || 10085 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10086 Context); 10087 } else if (BO->getOpcode() == Instruction::Or) { 10088 if (Inverse) 10089 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10090 Context) || 10091 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10092 Context); 10093 } 10094 } 10095 10096 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10097 if (!ICI) return false; 10098 10099 // Now that we found a conditional branch that dominates the loop or controls 10100 // the loop latch. Check to see if it is the comparison we are looking for. 10101 ICmpInst::Predicate FoundPred; 10102 if (Inverse) 10103 FoundPred = ICI->getInversePredicate(); 10104 else 10105 FoundPred = ICI->getPredicate(); 10106 10107 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10108 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10109 10110 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10111 } 10112 10113 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10114 const SCEV *RHS, 10115 ICmpInst::Predicate FoundPred, 10116 const SCEV *FoundLHS, const SCEV *FoundRHS, 10117 const Instruction *Context) { 10118 // Balance the types. 10119 if (getTypeSizeInBits(LHS->getType()) < 10120 getTypeSizeInBits(FoundLHS->getType())) { 10121 // For unsigned and equality predicates, try to prove that both found 10122 // operands fit into narrow unsigned range. If so, try to prove facts in 10123 // narrow types. 10124 if (!CmpInst::isSigned(FoundPred)) { 10125 auto *NarrowType = LHS->getType(); 10126 auto *WideType = FoundLHS->getType(); 10127 auto BitWidth = getTypeSizeInBits(NarrowType); 10128 const SCEV *MaxValue = getZeroExtendExpr( 10129 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10130 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10131 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10132 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10133 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10134 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10135 TruncFoundRHS, Context)) 10136 return true; 10137 } 10138 } 10139 10140 if (CmpInst::isSigned(Pred)) { 10141 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10142 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10143 } else { 10144 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10145 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10146 } 10147 } else if (getTypeSizeInBits(LHS->getType()) > 10148 getTypeSizeInBits(FoundLHS->getType())) { 10149 if (CmpInst::isSigned(FoundPred)) { 10150 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10151 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10152 } else { 10153 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10154 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10155 } 10156 } 10157 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10158 FoundRHS, Context); 10159 } 10160 10161 bool ScalarEvolution::isImpliedCondBalancedTypes( 10162 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10163 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10164 const Instruction *Context) { 10165 assert(getTypeSizeInBits(LHS->getType()) == 10166 getTypeSizeInBits(FoundLHS->getType()) && 10167 "Types should be balanced!"); 10168 // Canonicalize the query to match the way instcombine will have 10169 // canonicalized the comparison. 10170 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10171 if (LHS == RHS) 10172 return CmpInst::isTrueWhenEqual(Pred); 10173 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10174 if (FoundLHS == FoundRHS) 10175 return CmpInst::isFalseWhenEqual(FoundPred); 10176 10177 // Check to see if we can make the LHS or RHS match. 10178 if (LHS == FoundRHS || RHS == FoundLHS) { 10179 if (isa<SCEVConstant>(RHS)) { 10180 std::swap(FoundLHS, FoundRHS); 10181 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10182 } else { 10183 std::swap(LHS, RHS); 10184 Pred = ICmpInst::getSwappedPredicate(Pred); 10185 } 10186 } 10187 10188 // Check whether the found predicate is the same as the desired predicate. 10189 if (FoundPred == Pred) 10190 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10191 10192 // Check whether swapping the found predicate makes it the same as the 10193 // desired predicate. 10194 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10195 if (isa<SCEVConstant>(RHS)) 10196 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10197 else 10198 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 10199 LHS, FoundLHS, FoundRHS, Context); 10200 } 10201 10202 // Unsigned comparison is the same as signed comparison when both the operands 10203 // are non-negative. 10204 if (CmpInst::isUnsigned(FoundPred) && 10205 CmpInst::getSignedPredicate(FoundPred) == Pred && 10206 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10207 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10208 10209 // Check if we can make progress by sharpening ranges. 10210 if (FoundPred == ICmpInst::ICMP_NE && 10211 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10212 10213 const SCEVConstant *C = nullptr; 10214 const SCEV *V = nullptr; 10215 10216 if (isa<SCEVConstant>(FoundLHS)) { 10217 C = cast<SCEVConstant>(FoundLHS); 10218 V = FoundRHS; 10219 } else { 10220 C = cast<SCEVConstant>(FoundRHS); 10221 V = FoundLHS; 10222 } 10223 10224 // The guarding predicate tells us that C != V. If the known range 10225 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10226 // range we consider has to correspond to same signedness as the 10227 // predicate we're interested in folding. 10228 10229 APInt Min = ICmpInst::isSigned(Pred) ? 10230 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10231 10232 if (Min == C->getAPInt()) { 10233 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10234 // This is true even if (Min + 1) wraps around -- in case of 10235 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10236 10237 APInt SharperMin = Min + 1; 10238 10239 switch (Pred) { 10240 case ICmpInst::ICMP_SGE: 10241 case ICmpInst::ICMP_UGE: 10242 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10243 // RHS, we're done. 10244 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10245 Context)) 10246 return true; 10247 LLVM_FALLTHROUGH; 10248 10249 case ICmpInst::ICMP_SGT: 10250 case ICmpInst::ICMP_UGT: 10251 // We know from the range information that (V `Pred` Min || 10252 // V == Min). We know from the guarding condition that !(V 10253 // == Min). This gives us 10254 // 10255 // V `Pred` Min || V == Min && !(V == Min) 10256 // => V `Pred` Min 10257 // 10258 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10259 10260 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10261 Context)) 10262 return true; 10263 break; 10264 10265 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10266 case ICmpInst::ICMP_SLE: 10267 case ICmpInst::ICMP_ULE: 10268 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10269 LHS, V, getConstant(SharperMin), Context)) 10270 return true; 10271 LLVM_FALLTHROUGH; 10272 10273 case ICmpInst::ICMP_SLT: 10274 case ICmpInst::ICMP_ULT: 10275 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10276 LHS, V, getConstant(Min), Context)) 10277 return true; 10278 break; 10279 10280 default: 10281 // No change 10282 break; 10283 } 10284 } 10285 } 10286 10287 // Check whether the actual condition is beyond sufficient. 10288 if (FoundPred == ICmpInst::ICMP_EQ) 10289 if (ICmpInst::isTrueWhenEqual(Pred)) 10290 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10291 return true; 10292 if (Pred == ICmpInst::ICMP_NE) 10293 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10294 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10295 Context)) 10296 return true; 10297 10298 // Otherwise assume the worst. 10299 return false; 10300 } 10301 10302 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10303 const SCEV *&L, const SCEV *&R, 10304 SCEV::NoWrapFlags &Flags) { 10305 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10306 if (!AE || AE->getNumOperands() != 2) 10307 return false; 10308 10309 L = AE->getOperand(0); 10310 R = AE->getOperand(1); 10311 Flags = AE->getNoWrapFlags(); 10312 return true; 10313 } 10314 10315 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10316 const SCEV *Less) { 10317 // We avoid subtracting expressions here because this function is usually 10318 // fairly deep in the call stack (i.e. is called many times). 10319 10320 // X - X = 0. 10321 if (More == Less) 10322 return APInt(getTypeSizeInBits(More->getType()), 0); 10323 10324 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10325 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10326 const auto *MAR = cast<SCEVAddRecExpr>(More); 10327 10328 if (LAR->getLoop() != MAR->getLoop()) 10329 return None; 10330 10331 // We look at affine expressions only; not for correctness but to keep 10332 // getStepRecurrence cheap. 10333 if (!LAR->isAffine() || !MAR->isAffine()) 10334 return None; 10335 10336 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10337 return None; 10338 10339 Less = LAR->getStart(); 10340 More = MAR->getStart(); 10341 10342 // fall through 10343 } 10344 10345 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10346 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10347 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10348 return M - L; 10349 } 10350 10351 SCEV::NoWrapFlags Flags; 10352 const SCEV *LLess = nullptr, *RLess = nullptr; 10353 const SCEV *LMore = nullptr, *RMore = nullptr; 10354 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10355 // Compare (X + C1) vs X. 10356 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10357 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10358 if (RLess == More) 10359 return -(C1->getAPInt()); 10360 10361 // Compare X vs (X + C2). 10362 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10363 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10364 if (RMore == Less) 10365 return C2->getAPInt(); 10366 10367 // Compare (X + C1) vs (X + C2). 10368 if (C1 && C2 && RLess == RMore) 10369 return C2->getAPInt() - C1->getAPInt(); 10370 10371 return None; 10372 } 10373 10374 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10375 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10376 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10377 // Try to recognize the following pattern: 10378 // 10379 // FoundRHS = ... 10380 // ... 10381 // loop: 10382 // FoundLHS = {Start,+,W} 10383 // context_bb: // Basic block from the same loop 10384 // known(Pred, FoundLHS, FoundRHS) 10385 // 10386 // If some predicate is known in the context of a loop, it is also known on 10387 // each iteration of this loop, including the first iteration. Therefore, in 10388 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10389 // prove the original pred using this fact. 10390 if (!Context) 10391 return false; 10392 const BasicBlock *ContextBB = Context->getParent(); 10393 // Make sure AR varies in the context block. 10394 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10395 const Loop *L = AR->getLoop(); 10396 // Make sure that context belongs to the loop and executes on 1st iteration 10397 // (if it ever executes at all). 10398 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10399 return false; 10400 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10401 return false; 10402 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10403 } 10404 10405 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10406 const Loop *L = AR->getLoop(); 10407 // Make sure that context belongs to the loop and executes on 1st iteration 10408 // (if it ever executes at all). 10409 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10410 return false; 10411 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10412 return false; 10413 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10414 } 10415 10416 return false; 10417 } 10418 10419 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10420 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10421 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10422 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10423 return false; 10424 10425 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10426 if (!AddRecLHS) 10427 return false; 10428 10429 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10430 if (!AddRecFoundLHS) 10431 return false; 10432 10433 // We'd like to let SCEV reason about control dependencies, so we constrain 10434 // both the inequalities to be about add recurrences on the same loop. This 10435 // way we can use isLoopEntryGuardedByCond later. 10436 10437 const Loop *L = AddRecFoundLHS->getLoop(); 10438 if (L != AddRecLHS->getLoop()) 10439 return false; 10440 10441 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10442 // 10443 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10444 // ... (2) 10445 // 10446 // Informal proof for (2), assuming (1) [*]: 10447 // 10448 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10449 // 10450 // Then 10451 // 10452 // FoundLHS s< FoundRHS s< INT_MIN - C 10453 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10454 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10455 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10456 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10457 // <=> FoundLHS + C s< FoundRHS + C 10458 // 10459 // [*]: (1) can be proved by ruling out overflow. 10460 // 10461 // [**]: This can be proved by analyzing all the four possibilities: 10462 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10463 // (A s>= 0, B s>= 0). 10464 // 10465 // Note: 10466 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10467 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10468 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10469 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10470 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10471 // C)". 10472 10473 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10474 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10475 if (!LDiff || !RDiff || *LDiff != *RDiff) 10476 return false; 10477 10478 if (LDiff->isMinValue()) 10479 return true; 10480 10481 APInt FoundRHSLimit; 10482 10483 if (Pred == CmpInst::ICMP_ULT) { 10484 FoundRHSLimit = -(*RDiff); 10485 } else { 10486 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10487 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10488 } 10489 10490 // Try to prove (1) or (2), as needed. 10491 return isAvailableAtLoopEntry(FoundRHS, L) && 10492 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10493 getConstant(FoundRHSLimit)); 10494 } 10495 10496 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10497 const SCEV *LHS, const SCEV *RHS, 10498 const SCEV *FoundLHS, 10499 const SCEV *FoundRHS, unsigned Depth) { 10500 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10501 10502 auto ClearOnExit = make_scope_exit([&]() { 10503 if (LPhi) { 10504 bool Erased = PendingMerges.erase(LPhi); 10505 assert(Erased && "Failed to erase LPhi!"); 10506 (void)Erased; 10507 } 10508 if (RPhi) { 10509 bool Erased = PendingMerges.erase(RPhi); 10510 assert(Erased && "Failed to erase RPhi!"); 10511 (void)Erased; 10512 } 10513 }); 10514 10515 // Find respective Phis and check that they are not being pending. 10516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10517 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10518 if (!PendingMerges.insert(Phi).second) 10519 return false; 10520 LPhi = Phi; 10521 } 10522 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10523 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10524 // If we detect a loop of Phi nodes being processed by this method, for 10525 // example: 10526 // 10527 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10528 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10529 // 10530 // we don't want to deal with a case that complex, so return conservative 10531 // answer false. 10532 if (!PendingMerges.insert(Phi).second) 10533 return false; 10534 RPhi = Phi; 10535 } 10536 10537 // If none of LHS, RHS is a Phi, nothing to do here. 10538 if (!LPhi && !RPhi) 10539 return false; 10540 10541 // If there is a SCEVUnknown Phi we are interested in, make it left. 10542 if (!LPhi) { 10543 std::swap(LHS, RHS); 10544 std::swap(FoundLHS, FoundRHS); 10545 std::swap(LPhi, RPhi); 10546 Pred = ICmpInst::getSwappedPredicate(Pred); 10547 } 10548 10549 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10550 const BasicBlock *LBB = LPhi->getParent(); 10551 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10552 10553 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10554 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10555 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10556 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10557 }; 10558 10559 if (RPhi && RPhi->getParent() == LBB) { 10560 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10561 // If we compare two Phis from the same block, and for each entry block 10562 // the predicate is true for incoming values from this block, then the 10563 // predicate is also true for the Phis. 10564 for (const BasicBlock *IncBB : predecessors(LBB)) { 10565 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10566 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10567 if (!ProvedEasily(L, R)) 10568 return false; 10569 } 10570 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10571 // Case two: RHS is also a Phi from the same basic block, and it is an 10572 // AddRec. It means that there is a loop which has both AddRec and Unknown 10573 // PHIs, for it we can compare incoming values of AddRec from above the loop 10574 // and latch with their respective incoming values of LPhi. 10575 // TODO: Generalize to handle loops with many inputs in a header. 10576 if (LPhi->getNumIncomingValues() != 2) return false; 10577 10578 auto *RLoop = RAR->getLoop(); 10579 auto *Predecessor = RLoop->getLoopPredecessor(); 10580 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10581 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10582 if (!ProvedEasily(L1, RAR->getStart())) 10583 return false; 10584 auto *Latch = RLoop->getLoopLatch(); 10585 assert(Latch && "Loop with AddRec with no latch?"); 10586 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10587 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10588 return false; 10589 } else { 10590 // In all other cases go over inputs of LHS and compare each of them to RHS, 10591 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10592 // At this point RHS is either a non-Phi, or it is a Phi from some block 10593 // different from LBB. 10594 for (const BasicBlock *IncBB : predecessors(LBB)) { 10595 // Check that RHS is available in this block. 10596 if (!dominates(RHS, IncBB)) 10597 return false; 10598 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10599 if (!ProvedEasily(L, RHS)) 10600 return false; 10601 } 10602 } 10603 return true; 10604 } 10605 10606 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10607 const SCEV *LHS, const SCEV *RHS, 10608 const SCEV *FoundLHS, 10609 const SCEV *FoundRHS, 10610 const Instruction *Context) { 10611 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10612 return true; 10613 10614 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10615 return true; 10616 10617 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10618 Context)) 10619 return true; 10620 10621 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10622 FoundLHS, FoundRHS) || 10623 // ~x < ~y --> x > y 10624 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10625 getNotSCEV(FoundRHS), 10626 getNotSCEV(FoundLHS)); 10627 } 10628 10629 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10630 template <typename MinMaxExprType> 10631 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10632 const SCEV *Candidate) { 10633 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10634 if (!MinMaxExpr) 10635 return false; 10636 10637 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10638 } 10639 10640 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10641 ICmpInst::Predicate Pred, 10642 const SCEV *LHS, const SCEV *RHS) { 10643 // If both sides are affine addrecs for the same loop, with equal 10644 // steps, and we know the recurrences don't wrap, then we only 10645 // need to check the predicate on the starting values. 10646 10647 if (!ICmpInst::isRelational(Pred)) 10648 return false; 10649 10650 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10651 if (!LAR) 10652 return false; 10653 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10654 if (!RAR) 10655 return false; 10656 if (LAR->getLoop() != RAR->getLoop()) 10657 return false; 10658 if (!LAR->isAffine() || !RAR->isAffine()) 10659 return false; 10660 10661 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10662 return false; 10663 10664 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10665 SCEV::FlagNSW : SCEV::FlagNUW; 10666 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10667 return false; 10668 10669 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10670 } 10671 10672 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10673 /// expression? 10674 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10675 ICmpInst::Predicate Pred, 10676 const SCEV *LHS, const SCEV *RHS) { 10677 switch (Pred) { 10678 default: 10679 return false; 10680 10681 case ICmpInst::ICMP_SGE: 10682 std::swap(LHS, RHS); 10683 LLVM_FALLTHROUGH; 10684 case ICmpInst::ICMP_SLE: 10685 return 10686 // min(A, ...) <= A 10687 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10688 // A <= max(A, ...) 10689 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10690 10691 case ICmpInst::ICMP_UGE: 10692 std::swap(LHS, RHS); 10693 LLVM_FALLTHROUGH; 10694 case ICmpInst::ICMP_ULE: 10695 return 10696 // min(A, ...) <= A 10697 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10698 // A <= max(A, ...) 10699 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10700 } 10701 10702 llvm_unreachable("covered switch fell through?!"); 10703 } 10704 10705 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10706 const SCEV *LHS, const SCEV *RHS, 10707 const SCEV *FoundLHS, 10708 const SCEV *FoundRHS, 10709 unsigned Depth) { 10710 assert(getTypeSizeInBits(LHS->getType()) == 10711 getTypeSizeInBits(RHS->getType()) && 10712 "LHS and RHS have different sizes?"); 10713 assert(getTypeSizeInBits(FoundLHS->getType()) == 10714 getTypeSizeInBits(FoundRHS->getType()) && 10715 "FoundLHS and FoundRHS have different sizes?"); 10716 // We want to avoid hurting the compile time with analysis of too big trees. 10717 if (Depth > MaxSCEVOperationsImplicationDepth) 10718 return false; 10719 10720 // We only want to work with GT comparison so far. 10721 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10722 Pred = CmpInst::getSwappedPredicate(Pred); 10723 std::swap(LHS, RHS); 10724 std::swap(FoundLHS, FoundRHS); 10725 } 10726 10727 // For unsigned, try to reduce it to corresponding signed comparison. 10728 if (Pred == ICmpInst::ICMP_UGT) 10729 // We can replace unsigned predicate with its signed counterpart if all 10730 // involved values are non-negative. 10731 // TODO: We could have better support for unsigned. 10732 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10733 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10734 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10735 // use this fact to prove that LHS and RHS are non-negative. 10736 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10737 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10738 FoundRHS) && 10739 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10740 FoundRHS)) 10741 Pred = ICmpInst::ICMP_SGT; 10742 } 10743 10744 if (Pred != ICmpInst::ICMP_SGT) 10745 return false; 10746 10747 auto GetOpFromSExt = [&](const SCEV *S) { 10748 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10749 return Ext->getOperand(); 10750 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10751 // the constant in some cases. 10752 return S; 10753 }; 10754 10755 // Acquire values from extensions. 10756 auto *OrigLHS = LHS; 10757 auto *OrigFoundLHS = FoundLHS; 10758 LHS = GetOpFromSExt(LHS); 10759 FoundLHS = GetOpFromSExt(FoundLHS); 10760 10761 // Is the SGT predicate can be proved trivially or using the found context. 10762 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10763 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10764 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10765 FoundRHS, Depth + 1); 10766 }; 10767 10768 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10769 // We want to avoid creation of any new non-constant SCEV. Since we are 10770 // going to compare the operands to RHS, we should be certain that we don't 10771 // need any size extensions for this. So let's decline all cases when the 10772 // sizes of types of LHS and RHS do not match. 10773 // TODO: Maybe try to get RHS from sext to catch more cases? 10774 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10775 return false; 10776 10777 // Should not overflow. 10778 if (!LHSAddExpr->hasNoSignedWrap()) 10779 return false; 10780 10781 auto *LL = LHSAddExpr->getOperand(0); 10782 auto *LR = LHSAddExpr->getOperand(1); 10783 auto *MinusOne = getMinusOne(RHS->getType()); 10784 10785 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10786 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10787 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10788 }; 10789 // Try to prove the following rule: 10790 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10791 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10792 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10793 return true; 10794 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10795 Value *LL, *LR; 10796 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10797 10798 using namespace llvm::PatternMatch; 10799 10800 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10801 // Rules for division. 10802 // We are going to perform some comparisons with Denominator and its 10803 // derivative expressions. In general case, creating a SCEV for it may 10804 // lead to a complex analysis of the entire graph, and in particular it 10805 // can request trip count recalculation for the same loop. This would 10806 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10807 // this, we only want to create SCEVs that are constants in this section. 10808 // So we bail if Denominator is not a constant. 10809 if (!isa<ConstantInt>(LR)) 10810 return false; 10811 10812 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10813 10814 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10815 // then a SCEV for the numerator already exists and matches with FoundLHS. 10816 auto *Numerator = getExistingSCEV(LL); 10817 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10818 return false; 10819 10820 // Make sure that the numerator matches with FoundLHS and the denominator 10821 // is positive. 10822 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10823 return false; 10824 10825 auto *DTy = Denominator->getType(); 10826 auto *FRHSTy = FoundRHS->getType(); 10827 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10828 // One of types is a pointer and another one is not. We cannot extend 10829 // them properly to a wider type, so let us just reject this case. 10830 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10831 // to avoid this check. 10832 return false; 10833 10834 // Given that: 10835 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10836 auto *WTy = getWiderType(DTy, FRHSTy); 10837 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10838 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10839 10840 // Try to prove the following rule: 10841 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10842 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10843 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10844 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10845 if (isKnownNonPositive(RHS) && 10846 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10847 return true; 10848 10849 // Try to prove the following rule: 10850 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10851 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10852 // If we divide it by Denominator > 2, then: 10853 // 1. If FoundLHS is negative, then the result is 0. 10854 // 2. If FoundLHS is non-negative, then the result is non-negative. 10855 // Anyways, the result is non-negative. 10856 auto *MinusOne = getMinusOne(WTy); 10857 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10858 if (isKnownNegative(RHS) && 10859 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10860 return true; 10861 } 10862 } 10863 10864 // If our expression contained SCEVUnknown Phis, and we split it down and now 10865 // need to prove something for them, try to prove the predicate for every 10866 // possible incoming values of those Phis. 10867 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10868 return true; 10869 10870 return false; 10871 } 10872 10873 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10874 const SCEV *LHS, const SCEV *RHS) { 10875 // zext x u<= sext x, sext x s<= zext x 10876 switch (Pred) { 10877 case ICmpInst::ICMP_SGE: 10878 std::swap(LHS, RHS); 10879 LLVM_FALLTHROUGH; 10880 case ICmpInst::ICMP_SLE: { 10881 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10882 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10883 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10884 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10885 return true; 10886 break; 10887 } 10888 case ICmpInst::ICMP_UGE: 10889 std::swap(LHS, RHS); 10890 LLVM_FALLTHROUGH; 10891 case ICmpInst::ICMP_ULE: { 10892 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10893 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10894 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10895 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10896 return true; 10897 break; 10898 } 10899 default: 10900 break; 10901 }; 10902 return false; 10903 } 10904 10905 bool 10906 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10907 const SCEV *LHS, const SCEV *RHS) { 10908 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10909 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10910 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10911 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10912 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10913 } 10914 10915 bool 10916 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10917 const SCEV *LHS, const SCEV *RHS, 10918 const SCEV *FoundLHS, 10919 const SCEV *FoundRHS) { 10920 switch (Pred) { 10921 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10922 case ICmpInst::ICMP_EQ: 10923 case ICmpInst::ICMP_NE: 10924 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10925 return true; 10926 break; 10927 case ICmpInst::ICMP_SLT: 10928 case ICmpInst::ICMP_SLE: 10929 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10930 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10931 return true; 10932 break; 10933 case ICmpInst::ICMP_SGT: 10934 case ICmpInst::ICMP_SGE: 10935 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10936 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10937 return true; 10938 break; 10939 case ICmpInst::ICMP_ULT: 10940 case ICmpInst::ICMP_ULE: 10941 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10942 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10943 return true; 10944 break; 10945 case ICmpInst::ICMP_UGT: 10946 case ICmpInst::ICMP_UGE: 10947 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10948 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10949 return true; 10950 break; 10951 } 10952 10953 // Maybe it can be proved via operations? 10954 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10955 return true; 10956 10957 return false; 10958 } 10959 10960 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10961 const SCEV *LHS, 10962 const SCEV *RHS, 10963 const SCEV *FoundLHS, 10964 const SCEV *FoundRHS) { 10965 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10966 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10967 // reduce the compile time impact of this optimization. 10968 return false; 10969 10970 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10971 if (!Addend) 10972 return false; 10973 10974 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10975 10976 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10977 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10978 ConstantRange FoundLHSRange = 10979 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10980 10981 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10982 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10983 10984 // We can also compute the range of values for `LHS` that satisfy the 10985 // consequent, "`LHS` `Pred` `RHS`": 10986 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10987 ConstantRange SatisfyingLHSRange = 10988 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10989 10990 // The antecedent implies the consequent if every value of `LHS` that 10991 // satisfies the antecedent also satisfies the consequent. 10992 return SatisfyingLHSRange.contains(LHSRange); 10993 } 10994 10995 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10996 bool IsSigned, bool NoWrap) { 10997 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10998 10999 if (NoWrap) return false; 11000 11001 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11002 const SCEV *One = getOne(Stride->getType()); 11003 11004 if (IsSigned) { 11005 APInt MaxRHS = getSignedRangeMax(RHS); 11006 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11007 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11008 11009 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11010 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11011 } 11012 11013 APInt MaxRHS = getUnsignedRangeMax(RHS); 11014 APInt MaxValue = APInt::getMaxValue(BitWidth); 11015 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11016 11017 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11018 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11019 } 11020 11021 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11022 bool IsSigned, bool NoWrap) { 11023 if (NoWrap) return false; 11024 11025 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11026 const SCEV *One = getOne(Stride->getType()); 11027 11028 if (IsSigned) { 11029 APInt MinRHS = getSignedRangeMin(RHS); 11030 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11031 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11032 11033 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11034 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11035 } 11036 11037 APInt MinRHS = getUnsignedRangeMin(RHS); 11038 APInt MinValue = APInt::getMinValue(BitWidth); 11039 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11040 11041 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11042 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11043 } 11044 11045 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 11046 bool Equality) { 11047 const SCEV *One = getOne(Step->getType()); 11048 Delta = Equality ? getAddExpr(Delta, Step) 11049 : getAddExpr(Delta, getMinusSCEV(Step, One)); 11050 return getUDivExpr(Delta, Step); 11051 } 11052 11053 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11054 const SCEV *Stride, 11055 const SCEV *End, 11056 unsigned BitWidth, 11057 bool IsSigned) { 11058 11059 assert(!isKnownNonPositive(Stride) && 11060 "Stride is expected strictly positive!"); 11061 // Calculate the maximum backedge count based on the range of values 11062 // permitted by Start, End, and Stride. 11063 const SCEV *MaxBECount; 11064 APInt MinStart = 11065 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11066 11067 APInt StrideForMaxBECount = 11068 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11069 11070 // We already know that the stride is positive, so we paper over conservatism 11071 // in our range computation by forcing StrideForMaxBECount to be at least one. 11072 // In theory this is unnecessary, but we expect MaxBECount to be a 11073 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11074 // is nothing to constant fold it to). 11075 APInt One(BitWidth, 1, IsSigned); 11076 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11077 11078 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11079 : APInt::getMaxValue(BitWidth); 11080 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11081 11082 // Although End can be a MAX expression we estimate MaxEnd considering only 11083 // the case End = RHS of the loop termination condition. This is safe because 11084 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11085 // taken count. 11086 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11087 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11088 11089 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11090 getConstant(StrideForMaxBECount) /* Step */, 11091 false /* Equality */); 11092 11093 return MaxBECount; 11094 } 11095 11096 ScalarEvolution::ExitLimit 11097 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11098 const Loop *L, bool IsSigned, 11099 bool ControlsExit, bool AllowPredicates) { 11100 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11101 11102 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11103 bool PredicatedIV = false; 11104 11105 if (!IV && AllowPredicates) { 11106 // Try to make this an AddRec using runtime tests, in the first X 11107 // iterations of this loop, where X is the SCEV expression found by the 11108 // algorithm below. 11109 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11110 PredicatedIV = true; 11111 } 11112 11113 // Avoid weird loops 11114 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11115 return getCouldNotCompute(); 11116 11117 bool NoWrap = ControlsExit && 11118 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11119 11120 const SCEV *Stride = IV->getStepRecurrence(*this); 11121 11122 bool PositiveStride = isKnownPositive(Stride); 11123 11124 // Avoid negative or zero stride values. 11125 if (!PositiveStride) { 11126 // We can compute the correct backedge taken count for loops with unknown 11127 // strides if we can prove that the loop is not an infinite loop with side 11128 // effects. Here's the loop structure we are trying to handle - 11129 // 11130 // i = start 11131 // do { 11132 // A[i] = i; 11133 // i += s; 11134 // } while (i < end); 11135 // 11136 // The backedge taken count for such loops is evaluated as - 11137 // (max(end, start + stride) - start - 1) /u stride 11138 // 11139 // The additional preconditions that we need to check to prove correctness 11140 // of the above formula is as follows - 11141 // 11142 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11143 // NoWrap flag). 11144 // b) loop is single exit with no side effects. 11145 // 11146 // 11147 // Precondition a) implies that if the stride is negative, this is a single 11148 // trip loop. The backedge taken count formula reduces to zero in this case. 11149 // 11150 // Precondition b) implies that the unknown stride cannot be zero otherwise 11151 // we have UB. 11152 // 11153 // The positive stride case is the same as isKnownPositive(Stride) returning 11154 // true (original behavior of the function). 11155 // 11156 // We want to make sure that the stride is truly unknown as there are edge 11157 // cases where ScalarEvolution propagates no wrap flags to the 11158 // post-increment/decrement IV even though the increment/decrement operation 11159 // itself is wrapping. The computed backedge taken count may be wrong in 11160 // such cases. This is prevented by checking that the stride is not known to 11161 // be either positive or non-positive. For example, no wrap flags are 11162 // propagated to the post-increment IV of this loop with a trip count of 2 - 11163 // 11164 // unsigned char i; 11165 // for(i=127; i<128; i+=129) 11166 // A[i] = i; 11167 // 11168 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11169 !loopHasNoSideEffects(L)) 11170 return getCouldNotCompute(); 11171 } else if (!Stride->isOne() && 11172 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 11173 // Avoid proven overflow cases: this will ensure that the backedge taken 11174 // count will not generate any unsigned overflow. Relaxed no-overflow 11175 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11176 // undefined behaviors like the case of C language. 11177 return getCouldNotCompute(); 11178 11179 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11180 : ICmpInst::ICMP_ULT; 11181 const SCEV *Start = IV->getStart(); 11182 const SCEV *End = RHS; 11183 // When the RHS is not invariant, we do not know the end bound of the loop and 11184 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11185 // calculate the MaxBECount, given the start, stride and max value for the end 11186 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11187 // checked above). 11188 if (!isLoopInvariant(RHS, L)) { 11189 const SCEV *MaxBECount = computeMaxBECountForLT( 11190 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11191 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11192 false /*MaxOrZero*/, Predicates); 11193 } 11194 // If the backedge is taken at least once, then it will be taken 11195 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11196 // is the LHS value of the less-than comparison the first time it is evaluated 11197 // and End is the RHS. 11198 const SCEV *BECountIfBackedgeTaken = 11199 computeBECount(getMinusSCEV(End, Start), Stride, false); 11200 // If the loop entry is guarded by the result of the backedge test of the 11201 // first loop iteration, then we know the backedge will be taken at least 11202 // once and so the backedge taken count is as above. If not then we use the 11203 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11204 // as if the backedge is taken at least once max(End,Start) is End and so the 11205 // result is as above, and if not max(End,Start) is Start so we get a backedge 11206 // count of zero. 11207 const SCEV *BECount; 11208 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11209 BECount = BECountIfBackedgeTaken; 11210 else { 11211 // If we know that RHS >= Start in the context of loop, then we know that 11212 // max(RHS, Start) = RHS at this point. 11213 if (isLoopEntryGuardedByCond( 11214 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11215 End = RHS; 11216 else 11217 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11218 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 11219 } 11220 11221 const SCEV *MaxBECount; 11222 bool MaxOrZero = false; 11223 if (isa<SCEVConstant>(BECount)) 11224 MaxBECount = BECount; 11225 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11226 // If we know exactly how many times the backedge will be taken if it's 11227 // taken at least once, then the backedge count will either be that or 11228 // zero. 11229 MaxBECount = BECountIfBackedgeTaken; 11230 MaxOrZero = true; 11231 } else { 11232 MaxBECount = computeMaxBECountForLT( 11233 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11234 } 11235 11236 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11237 !isa<SCEVCouldNotCompute>(BECount)) 11238 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11239 11240 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11241 } 11242 11243 ScalarEvolution::ExitLimit 11244 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11245 const Loop *L, bool IsSigned, 11246 bool ControlsExit, bool AllowPredicates) { 11247 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11248 // We handle only IV > Invariant 11249 if (!isLoopInvariant(RHS, L)) 11250 return getCouldNotCompute(); 11251 11252 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11253 if (!IV && AllowPredicates) 11254 // Try to make this an AddRec using runtime tests, in the first X 11255 // iterations of this loop, where X is the SCEV expression found by the 11256 // algorithm below. 11257 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11258 11259 // Avoid weird loops 11260 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11261 return getCouldNotCompute(); 11262 11263 bool NoWrap = ControlsExit && 11264 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11265 11266 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11267 11268 // Avoid negative or zero stride values 11269 if (!isKnownPositive(Stride)) 11270 return getCouldNotCompute(); 11271 11272 // Avoid proven overflow cases: this will ensure that the backedge taken count 11273 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11274 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11275 // behaviors like the case of C language. 11276 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 11277 return getCouldNotCompute(); 11278 11279 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11280 : ICmpInst::ICMP_UGT; 11281 11282 const SCEV *Start = IV->getStart(); 11283 const SCEV *End = RHS; 11284 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11285 // If we know that Start >= RHS in the context of loop, then we know that 11286 // min(RHS, Start) = RHS at this point. 11287 if (isLoopEntryGuardedByCond( 11288 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11289 End = RHS; 11290 else 11291 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11292 } 11293 11294 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 11295 11296 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11297 : getUnsignedRangeMax(Start); 11298 11299 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11300 : getUnsignedRangeMin(Stride); 11301 11302 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11303 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11304 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11305 11306 // Although End can be a MIN expression we estimate MinEnd considering only 11307 // the case End = RHS. This is safe because in the other case (Start - End) 11308 // is zero, leading to a zero maximum backedge taken count. 11309 APInt MinEnd = 11310 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11311 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11312 11313 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11314 ? BECount 11315 : computeBECount(getConstant(MaxStart - MinEnd), 11316 getConstant(MinStride), false); 11317 11318 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11319 MaxBECount = BECount; 11320 11321 return ExitLimit(BECount, MaxBECount, false, Predicates); 11322 } 11323 11324 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11325 ScalarEvolution &SE) const { 11326 if (Range.isFullSet()) // Infinite loop. 11327 return SE.getCouldNotCompute(); 11328 11329 // If the start is a non-zero constant, shift the range to simplify things. 11330 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11331 if (!SC->getValue()->isZero()) { 11332 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 11333 Operands[0] = SE.getZero(SC->getType()); 11334 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11335 getNoWrapFlags(FlagNW)); 11336 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11337 return ShiftedAddRec->getNumIterationsInRange( 11338 Range.subtract(SC->getAPInt()), SE); 11339 // This is strange and shouldn't happen. 11340 return SE.getCouldNotCompute(); 11341 } 11342 11343 // The only time we can solve this is when we have all constant indices. 11344 // Otherwise, we cannot determine the overflow conditions. 11345 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11346 return SE.getCouldNotCompute(); 11347 11348 // Okay at this point we know that all elements of the chrec are constants and 11349 // that the start element is zero. 11350 11351 // First check to see if the range contains zero. If not, the first 11352 // iteration exits. 11353 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11354 if (!Range.contains(APInt(BitWidth, 0))) 11355 return SE.getZero(getType()); 11356 11357 if (isAffine()) { 11358 // If this is an affine expression then we have this situation: 11359 // Solve {0,+,A} in Range === Ax in Range 11360 11361 // We know that zero is in the range. If A is positive then we know that 11362 // the upper value of the range must be the first possible exit value. 11363 // If A is negative then the lower of the range is the last possible loop 11364 // value. Also note that we already checked for a full range. 11365 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11366 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11367 11368 // The exit value should be (End+A)/A. 11369 APInt ExitVal = (End + A).udiv(A); 11370 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11371 11372 // Evaluate at the exit value. If we really did fall out of the valid 11373 // range, then we computed our trip count, otherwise wrap around or other 11374 // things must have happened. 11375 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11376 if (Range.contains(Val->getValue())) 11377 return SE.getCouldNotCompute(); // Something strange happened 11378 11379 // Ensure that the previous value is in the range. This is a sanity check. 11380 assert(Range.contains( 11381 EvaluateConstantChrecAtConstant(this, 11382 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11383 "Linear scev computation is off in a bad way!"); 11384 return SE.getConstant(ExitValue); 11385 } 11386 11387 if (isQuadratic()) { 11388 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11389 return SE.getConstant(S.getValue()); 11390 } 11391 11392 return SE.getCouldNotCompute(); 11393 } 11394 11395 const SCEVAddRecExpr * 11396 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11397 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11398 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11399 // but in this case we cannot guarantee that the value returned will be an 11400 // AddRec because SCEV does not have a fixed point where it stops 11401 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11402 // may happen if we reach arithmetic depth limit while simplifying. So we 11403 // construct the returned value explicitly. 11404 SmallVector<const SCEV *, 3> Ops; 11405 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11406 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11407 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11408 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11409 // We know that the last operand is not a constant zero (otherwise it would 11410 // have been popped out earlier). This guarantees us that if the result has 11411 // the same last operand, then it will also not be popped out, meaning that 11412 // the returned value will be an AddRec. 11413 const SCEV *Last = getOperand(getNumOperands() - 1); 11414 assert(!Last->isZero() && "Recurrency with zero step?"); 11415 Ops.push_back(Last); 11416 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11417 SCEV::FlagAnyWrap)); 11418 } 11419 11420 // Return true when S contains at least an undef value. 11421 static inline bool containsUndefs(const SCEV *S) { 11422 return SCEVExprContains(S, [](const SCEV *S) { 11423 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11424 return isa<UndefValue>(SU->getValue()); 11425 return false; 11426 }); 11427 } 11428 11429 namespace { 11430 11431 // Collect all steps of SCEV expressions. 11432 struct SCEVCollectStrides { 11433 ScalarEvolution &SE; 11434 SmallVectorImpl<const SCEV *> &Strides; 11435 11436 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11437 : SE(SE), Strides(S) {} 11438 11439 bool follow(const SCEV *S) { 11440 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11441 Strides.push_back(AR->getStepRecurrence(SE)); 11442 return true; 11443 } 11444 11445 bool isDone() const { return false; } 11446 }; 11447 11448 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11449 struct SCEVCollectTerms { 11450 SmallVectorImpl<const SCEV *> &Terms; 11451 11452 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11453 11454 bool follow(const SCEV *S) { 11455 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11456 isa<SCEVSignExtendExpr>(S)) { 11457 if (!containsUndefs(S)) 11458 Terms.push_back(S); 11459 11460 // Stop recursion: once we collected a term, do not walk its operands. 11461 return false; 11462 } 11463 11464 // Keep looking. 11465 return true; 11466 } 11467 11468 bool isDone() const { return false; } 11469 }; 11470 11471 // Check if a SCEV contains an AddRecExpr. 11472 struct SCEVHasAddRec { 11473 bool &ContainsAddRec; 11474 11475 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11476 ContainsAddRec = false; 11477 } 11478 11479 bool follow(const SCEV *S) { 11480 if (isa<SCEVAddRecExpr>(S)) { 11481 ContainsAddRec = true; 11482 11483 // Stop recursion: once we collected a term, do not walk its operands. 11484 return false; 11485 } 11486 11487 // Keep looking. 11488 return true; 11489 } 11490 11491 bool isDone() const { return false; } 11492 }; 11493 11494 // Find factors that are multiplied with an expression that (possibly as a 11495 // subexpression) contains an AddRecExpr. In the expression: 11496 // 11497 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11498 // 11499 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11500 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11501 // parameters as they form a product with an induction variable. 11502 // 11503 // This collector expects all array size parameters to be in the same MulExpr. 11504 // It might be necessary to later add support for collecting parameters that are 11505 // spread over different nested MulExpr. 11506 struct SCEVCollectAddRecMultiplies { 11507 SmallVectorImpl<const SCEV *> &Terms; 11508 ScalarEvolution &SE; 11509 11510 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11511 : Terms(T), SE(SE) {} 11512 11513 bool follow(const SCEV *S) { 11514 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11515 bool HasAddRec = false; 11516 SmallVector<const SCEV *, 0> Operands; 11517 for (auto Op : Mul->operands()) { 11518 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11519 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11520 Operands.push_back(Op); 11521 } else if (Unknown) { 11522 HasAddRec = true; 11523 } else { 11524 bool ContainsAddRec = false; 11525 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11526 visitAll(Op, ContiansAddRec); 11527 HasAddRec |= ContainsAddRec; 11528 } 11529 } 11530 if (Operands.size() == 0) 11531 return true; 11532 11533 if (!HasAddRec) 11534 return false; 11535 11536 Terms.push_back(SE.getMulExpr(Operands)); 11537 // Stop recursion: once we collected a term, do not walk its operands. 11538 return false; 11539 } 11540 11541 // Keep looking. 11542 return true; 11543 } 11544 11545 bool isDone() const { return false; } 11546 }; 11547 11548 } // end anonymous namespace 11549 11550 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11551 /// two places: 11552 /// 1) The strides of AddRec expressions. 11553 /// 2) Unknowns that are multiplied with AddRec expressions. 11554 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11555 SmallVectorImpl<const SCEV *> &Terms) { 11556 SmallVector<const SCEV *, 4> Strides; 11557 SCEVCollectStrides StrideCollector(*this, Strides); 11558 visitAll(Expr, StrideCollector); 11559 11560 LLVM_DEBUG({ 11561 dbgs() << "Strides:\n"; 11562 for (const SCEV *S : Strides) 11563 dbgs() << *S << "\n"; 11564 }); 11565 11566 for (const SCEV *S : Strides) { 11567 SCEVCollectTerms TermCollector(Terms); 11568 visitAll(S, TermCollector); 11569 } 11570 11571 LLVM_DEBUG({ 11572 dbgs() << "Terms:\n"; 11573 for (const SCEV *T : Terms) 11574 dbgs() << *T << "\n"; 11575 }); 11576 11577 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11578 visitAll(Expr, MulCollector); 11579 } 11580 11581 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11582 SmallVectorImpl<const SCEV *> &Terms, 11583 SmallVectorImpl<const SCEV *> &Sizes) { 11584 int Last = Terms.size() - 1; 11585 const SCEV *Step = Terms[Last]; 11586 11587 // End of recursion. 11588 if (Last == 0) { 11589 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11590 SmallVector<const SCEV *, 2> Qs; 11591 for (const SCEV *Op : M->operands()) 11592 if (!isa<SCEVConstant>(Op)) 11593 Qs.push_back(Op); 11594 11595 Step = SE.getMulExpr(Qs); 11596 } 11597 11598 Sizes.push_back(Step); 11599 return true; 11600 } 11601 11602 for (const SCEV *&Term : Terms) { 11603 // Normalize the terms before the next call to findArrayDimensionsRec. 11604 const SCEV *Q, *R; 11605 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11606 11607 // Bail out when GCD does not evenly divide one of the terms. 11608 if (!R->isZero()) 11609 return false; 11610 11611 Term = Q; 11612 } 11613 11614 // Remove all SCEVConstants. 11615 Terms.erase( 11616 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11617 Terms.end()); 11618 11619 if (Terms.size() > 0) 11620 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11621 return false; 11622 11623 Sizes.push_back(Step); 11624 return true; 11625 } 11626 11627 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11628 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11629 for (const SCEV *T : Terms) 11630 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11631 return true; 11632 11633 return false; 11634 } 11635 11636 // Return the number of product terms in S. 11637 static inline int numberOfTerms(const SCEV *S) { 11638 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11639 return Expr->getNumOperands(); 11640 return 1; 11641 } 11642 11643 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11644 if (isa<SCEVConstant>(T)) 11645 return nullptr; 11646 11647 if (isa<SCEVUnknown>(T)) 11648 return T; 11649 11650 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11651 SmallVector<const SCEV *, 2> Factors; 11652 for (const SCEV *Op : M->operands()) 11653 if (!isa<SCEVConstant>(Op)) 11654 Factors.push_back(Op); 11655 11656 return SE.getMulExpr(Factors); 11657 } 11658 11659 return T; 11660 } 11661 11662 /// Return the size of an element read or written by Inst. 11663 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11664 Type *Ty; 11665 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11666 Ty = Store->getValueOperand()->getType(); 11667 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11668 Ty = Load->getType(); 11669 else 11670 return nullptr; 11671 11672 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11673 return getSizeOfExpr(ETy, Ty); 11674 } 11675 11676 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11677 SmallVectorImpl<const SCEV *> &Sizes, 11678 const SCEV *ElementSize) { 11679 if (Terms.size() < 1 || !ElementSize) 11680 return; 11681 11682 // Early return when Terms do not contain parameters: we do not delinearize 11683 // non parametric SCEVs. 11684 if (!containsParameters(Terms)) 11685 return; 11686 11687 LLVM_DEBUG({ 11688 dbgs() << "Terms:\n"; 11689 for (const SCEV *T : Terms) 11690 dbgs() << *T << "\n"; 11691 }); 11692 11693 // Remove duplicates. 11694 array_pod_sort(Terms.begin(), Terms.end()); 11695 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11696 11697 // Put larger terms first. 11698 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11699 return numberOfTerms(LHS) > numberOfTerms(RHS); 11700 }); 11701 11702 // Try to divide all terms by the element size. If term is not divisible by 11703 // element size, proceed with the original term. 11704 for (const SCEV *&Term : Terms) { 11705 const SCEV *Q, *R; 11706 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11707 if (!Q->isZero()) 11708 Term = Q; 11709 } 11710 11711 SmallVector<const SCEV *, 4> NewTerms; 11712 11713 // Remove constant factors. 11714 for (const SCEV *T : Terms) 11715 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11716 NewTerms.push_back(NewT); 11717 11718 LLVM_DEBUG({ 11719 dbgs() << "Terms after sorting:\n"; 11720 for (const SCEV *T : NewTerms) 11721 dbgs() << *T << "\n"; 11722 }); 11723 11724 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11725 Sizes.clear(); 11726 return; 11727 } 11728 11729 // The last element to be pushed into Sizes is the size of an element. 11730 Sizes.push_back(ElementSize); 11731 11732 LLVM_DEBUG({ 11733 dbgs() << "Sizes:\n"; 11734 for (const SCEV *S : Sizes) 11735 dbgs() << *S << "\n"; 11736 }); 11737 } 11738 11739 void ScalarEvolution::computeAccessFunctions( 11740 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11741 SmallVectorImpl<const SCEV *> &Sizes) { 11742 // Early exit in case this SCEV is not an affine multivariate function. 11743 if (Sizes.empty()) 11744 return; 11745 11746 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11747 if (!AR->isAffine()) 11748 return; 11749 11750 const SCEV *Res = Expr; 11751 int Last = Sizes.size() - 1; 11752 for (int i = Last; i >= 0; i--) { 11753 const SCEV *Q, *R; 11754 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11755 11756 LLVM_DEBUG({ 11757 dbgs() << "Res: " << *Res << "\n"; 11758 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11759 dbgs() << "Res divided by Sizes[i]:\n"; 11760 dbgs() << "Quotient: " << *Q << "\n"; 11761 dbgs() << "Remainder: " << *R << "\n"; 11762 }); 11763 11764 Res = Q; 11765 11766 // Do not record the last subscript corresponding to the size of elements in 11767 // the array. 11768 if (i == Last) { 11769 11770 // Bail out if the remainder is too complex. 11771 if (isa<SCEVAddRecExpr>(R)) { 11772 Subscripts.clear(); 11773 Sizes.clear(); 11774 return; 11775 } 11776 11777 continue; 11778 } 11779 11780 // Record the access function for the current subscript. 11781 Subscripts.push_back(R); 11782 } 11783 11784 // Also push in last position the remainder of the last division: it will be 11785 // the access function of the innermost dimension. 11786 Subscripts.push_back(Res); 11787 11788 std::reverse(Subscripts.begin(), Subscripts.end()); 11789 11790 LLVM_DEBUG({ 11791 dbgs() << "Subscripts:\n"; 11792 for (const SCEV *S : Subscripts) 11793 dbgs() << *S << "\n"; 11794 }); 11795 } 11796 11797 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11798 /// sizes of an array access. Returns the remainder of the delinearization that 11799 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11800 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11801 /// expressions in the stride and base of a SCEV corresponding to the 11802 /// computation of a GCD (greatest common divisor) of base and stride. When 11803 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11804 /// 11805 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11806 /// 11807 /// void foo(long n, long m, long o, double A[n][m][o]) { 11808 /// 11809 /// for (long i = 0; i < n; i++) 11810 /// for (long j = 0; j < m; j++) 11811 /// for (long k = 0; k < o; k++) 11812 /// A[i][j][k] = 1.0; 11813 /// } 11814 /// 11815 /// the delinearization input is the following AddRec SCEV: 11816 /// 11817 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11818 /// 11819 /// From this SCEV, we are able to say that the base offset of the access is %A 11820 /// because it appears as an offset that does not divide any of the strides in 11821 /// the loops: 11822 /// 11823 /// CHECK: Base offset: %A 11824 /// 11825 /// and then SCEV->delinearize determines the size of some of the dimensions of 11826 /// the array as these are the multiples by which the strides are happening: 11827 /// 11828 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11829 /// 11830 /// Note that the outermost dimension remains of UnknownSize because there are 11831 /// no strides that would help identifying the size of the last dimension: when 11832 /// the array has been statically allocated, one could compute the size of that 11833 /// dimension by dividing the overall size of the array by the size of the known 11834 /// dimensions: %m * %o * 8. 11835 /// 11836 /// Finally delinearize provides the access functions for the array reference 11837 /// that does correspond to A[i][j][k] of the above C testcase: 11838 /// 11839 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11840 /// 11841 /// The testcases are checking the output of a function pass: 11842 /// DelinearizationPass that walks through all loads and stores of a function 11843 /// asking for the SCEV of the memory access with respect to all enclosing 11844 /// loops, calling SCEV->delinearize on that and printing the results. 11845 void ScalarEvolution::delinearize(const SCEV *Expr, 11846 SmallVectorImpl<const SCEV *> &Subscripts, 11847 SmallVectorImpl<const SCEV *> &Sizes, 11848 const SCEV *ElementSize) { 11849 // First step: collect parametric terms. 11850 SmallVector<const SCEV *, 4> Terms; 11851 collectParametricTerms(Expr, Terms); 11852 11853 if (Terms.empty()) 11854 return; 11855 11856 // Second step: find subscript sizes. 11857 findArrayDimensions(Terms, Sizes, ElementSize); 11858 11859 if (Sizes.empty()) 11860 return; 11861 11862 // Third step: compute the access functions for each subscript. 11863 computeAccessFunctions(Expr, Subscripts, Sizes); 11864 11865 if (Subscripts.empty()) 11866 return; 11867 11868 LLVM_DEBUG({ 11869 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11870 dbgs() << "ArrayDecl[UnknownSize]"; 11871 for (const SCEV *S : Sizes) 11872 dbgs() << "[" << *S << "]"; 11873 11874 dbgs() << "\nArrayRef"; 11875 for (const SCEV *S : Subscripts) 11876 dbgs() << "[" << *S << "]"; 11877 dbgs() << "\n"; 11878 }); 11879 } 11880 11881 bool ScalarEvolution::getIndexExpressionsFromGEP( 11882 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11883 SmallVectorImpl<int> &Sizes) { 11884 assert(Subscripts.empty() && Sizes.empty() && 11885 "Expected output lists to be empty on entry to this function."); 11886 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11887 Type *Ty = GEP->getPointerOperandType(); 11888 bool DroppedFirstDim = false; 11889 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11890 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11891 if (i == 1) { 11892 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11893 Ty = PtrTy->getElementType(); 11894 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11895 Ty = ArrayTy->getElementType(); 11896 } else { 11897 Subscripts.clear(); 11898 Sizes.clear(); 11899 return false; 11900 } 11901 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11902 if (Const->getValue()->isZero()) { 11903 DroppedFirstDim = true; 11904 continue; 11905 } 11906 Subscripts.push_back(Expr); 11907 continue; 11908 } 11909 11910 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11911 if (!ArrayTy) { 11912 Subscripts.clear(); 11913 Sizes.clear(); 11914 return false; 11915 } 11916 11917 Subscripts.push_back(Expr); 11918 if (!(DroppedFirstDim && i == 2)) 11919 Sizes.push_back(ArrayTy->getNumElements()); 11920 11921 Ty = ArrayTy->getElementType(); 11922 } 11923 return !Subscripts.empty(); 11924 } 11925 11926 //===----------------------------------------------------------------------===// 11927 // SCEVCallbackVH Class Implementation 11928 //===----------------------------------------------------------------------===// 11929 11930 void ScalarEvolution::SCEVCallbackVH::deleted() { 11931 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11932 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11933 SE->ConstantEvolutionLoopExitValue.erase(PN); 11934 SE->eraseValueFromMap(getValPtr()); 11935 // this now dangles! 11936 } 11937 11938 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11939 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11940 11941 // Forget all the expressions associated with users of the old value, 11942 // so that future queries will recompute the expressions using the new 11943 // value. 11944 Value *Old = getValPtr(); 11945 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11946 SmallPtrSet<User *, 8> Visited; 11947 while (!Worklist.empty()) { 11948 User *U = Worklist.pop_back_val(); 11949 // Deleting the Old value will cause this to dangle. Postpone 11950 // that until everything else is done. 11951 if (U == Old) 11952 continue; 11953 if (!Visited.insert(U).second) 11954 continue; 11955 if (PHINode *PN = dyn_cast<PHINode>(U)) 11956 SE->ConstantEvolutionLoopExitValue.erase(PN); 11957 SE->eraseValueFromMap(U); 11958 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11959 } 11960 // Delete the Old value. 11961 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11962 SE->ConstantEvolutionLoopExitValue.erase(PN); 11963 SE->eraseValueFromMap(Old); 11964 // this now dangles! 11965 } 11966 11967 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11968 : CallbackVH(V), SE(se) {} 11969 11970 //===----------------------------------------------------------------------===// 11971 // ScalarEvolution Class Implementation 11972 //===----------------------------------------------------------------------===// 11973 11974 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11975 AssumptionCache &AC, DominatorTree &DT, 11976 LoopInfo &LI) 11977 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11978 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11979 LoopDispositions(64), BlockDispositions(64) { 11980 // To use guards for proving predicates, we need to scan every instruction in 11981 // relevant basic blocks, and not just terminators. Doing this is a waste of 11982 // time if the IR does not actually contain any calls to 11983 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11984 // 11985 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11986 // to _add_ guards to the module when there weren't any before, and wants 11987 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11988 // efficient in lieu of being smart in that rather obscure case. 11989 11990 auto *GuardDecl = F.getParent()->getFunction( 11991 Intrinsic::getName(Intrinsic::experimental_guard)); 11992 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11993 } 11994 11995 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11996 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11997 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11998 ValueExprMap(std::move(Arg.ValueExprMap)), 11999 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12000 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12001 PendingMerges(std::move(Arg.PendingMerges)), 12002 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12003 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12004 PredicatedBackedgeTakenCounts( 12005 std::move(Arg.PredicatedBackedgeTakenCounts)), 12006 ConstantEvolutionLoopExitValue( 12007 std::move(Arg.ConstantEvolutionLoopExitValue)), 12008 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12009 LoopDispositions(std::move(Arg.LoopDispositions)), 12010 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12011 BlockDispositions(std::move(Arg.BlockDispositions)), 12012 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12013 SignedRanges(std::move(Arg.SignedRanges)), 12014 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12015 UniquePreds(std::move(Arg.UniquePreds)), 12016 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12017 LoopUsers(std::move(Arg.LoopUsers)), 12018 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12019 FirstUnknown(Arg.FirstUnknown) { 12020 Arg.FirstUnknown = nullptr; 12021 } 12022 12023 ScalarEvolution::~ScalarEvolution() { 12024 // Iterate through all the SCEVUnknown instances and call their 12025 // destructors, so that they release their references to their values. 12026 for (SCEVUnknown *U = FirstUnknown; U;) { 12027 SCEVUnknown *Tmp = U; 12028 U = U->Next; 12029 Tmp->~SCEVUnknown(); 12030 } 12031 FirstUnknown = nullptr; 12032 12033 ExprValueMap.clear(); 12034 ValueExprMap.clear(); 12035 HasRecMap.clear(); 12036 12037 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 12038 // that a loop had multiple computable exits. 12039 for (auto &BTCI : BackedgeTakenCounts) 12040 BTCI.second.clear(); 12041 for (auto &BTCI : PredicatedBackedgeTakenCounts) 12042 BTCI.second.clear(); 12043 12044 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12045 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12046 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12047 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12048 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12049 } 12050 12051 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12052 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12053 } 12054 12055 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12056 const Loop *L) { 12057 // Print all inner loops first 12058 for (Loop *I : *L) 12059 PrintLoopInfo(OS, SE, I); 12060 12061 OS << "Loop "; 12062 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12063 OS << ": "; 12064 12065 SmallVector<BasicBlock *, 8> ExitingBlocks; 12066 L->getExitingBlocks(ExitingBlocks); 12067 if (ExitingBlocks.size() != 1) 12068 OS << "<multiple exits> "; 12069 12070 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12071 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12072 else 12073 OS << "Unpredictable backedge-taken count.\n"; 12074 12075 if (ExitingBlocks.size() > 1) 12076 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12077 OS << " exit count for " << ExitingBlock->getName() << ": " 12078 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12079 } 12080 12081 OS << "Loop "; 12082 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12083 OS << ": "; 12084 12085 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12086 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12087 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12088 OS << ", actual taken count either this or zero."; 12089 } else { 12090 OS << "Unpredictable max backedge-taken count. "; 12091 } 12092 12093 OS << "\n" 12094 "Loop "; 12095 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12096 OS << ": "; 12097 12098 SCEVUnionPredicate Pred; 12099 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12100 if (!isa<SCEVCouldNotCompute>(PBT)) { 12101 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12102 OS << " Predicates:\n"; 12103 Pred.print(OS, 4); 12104 } else { 12105 OS << "Unpredictable predicated backedge-taken count. "; 12106 } 12107 OS << "\n"; 12108 12109 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12110 OS << "Loop "; 12111 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12112 OS << ": "; 12113 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12114 } 12115 } 12116 12117 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12118 switch (LD) { 12119 case ScalarEvolution::LoopVariant: 12120 return "Variant"; 12121 case ScalarEvolution::LoopInvariant: 12122 return "Invariant"; 12123 case ScalarEvolution::LoopComputable: 12124 return "Computable"; 12125 } 12126 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12127 } 12128 12129 void ScalarEvolution::print(raw_ostream &OS) const { 12130 // ScalarEvolution's implementation of the print method is to print 12131 // out SCEV values of all instructions that are interesting. Doing 12132 // this potentially causes it to create new SCEV objects though, 12133 // which technically conflicts with the const qualifier. This isn't 12134 // observable from outside the class though, so casting away the 12135 // const isn't dangerous. 12136 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12137 12138 if (ClassifyExpressions) { 12139 OS << "Classifying expressions for: "; 12140 F.printAsOperand(OS, /*PrintType=*/false); 12141 OS << "\n"; 12142 for (Instruction &I : instructions(F)) 12143 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12144 OS << I << '\n'; 12145 OS << " --> "; 12146 const SCEV *SV = SE.getSCEV(&I); 12147 SV->print(OS); 12148 if (!isa<SCEVCouldNotCompute>(SV)) { 12149 OS << " U: "; 12150 SE.getUnsignedRange(SV).print(OS); 12151 OS << " S: "; 12152 SE.getSignedRange(SV).print(OS); 12153 } 12154 12155 const Loop *L = LI.getLoopFor(I.getParent()); 12156 12157 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12158 if (AtUse != SV) { 12159 OS << " --> "; 12160 AtUse->print(OS); 12161 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12162 OS << " U: "; 12163 SE.getUnsignedRange(AtUse).print(OS); 12164 OS << " S: "; 12165 SE.getSignedRange(AtUse).print(OS); 12166 } 12167 } 12168 12169 if (L) { 12170 OS << "\t\t" "Exits: "; 12171 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12172 if (!SE.isLoopInvariant(ExitValue, L)) { 12173 OS << "<<Unknown>>"; 12174 } else { 12175 OS << *ExitValue; 12176 } 12177 12178 bool First = true; 12179 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12180 if (First) { 12181 OS << "\t\t" "LoopDispositions: { "; 12182 First = false; 12183 } else { 12184 OS << ", "; 12185 } 12186 12187 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12188 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12189 } 12190 12191 for (auto *InnerL : depth_first(L)) { 12192 if (InnerL == L) 12193 continue; 12194 if (First) { 12195 OS << "\t\t" "LoopDispositions: { "; 12196 First = false; 12197 } else { 12198 OS << ", "; 12199 } 12200 12201 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12202 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12203 } 12204 12205 OS << " }"; 12206 } 12207 12208 OS << "\n"; 12209 } 12210 } 12211 12212 OS << "Determining loop execution counts for: "; 12213 F.printAsOperand(OS, /*PrintType=*/false); 12214 OS << "\n"; 12215 for (Loop *I : LI) 12216 PrintLoopInfo(OS, &SE, I); 12217 } 12218 12219 ScalarEvolution::LoopDisposition 12220 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12221 auto &Values = LoopDispositions[S]; 12222 for (auto &V : Values) { 12223 if (V.getPointer() == L) 12224 return V.getInt(); 12225 } 12226 Values.emplace_back(L, LoopVariant); 12227 LoopDisposition D = computeLoopDisposition(S, L); 12228 auto &Values2 = LoopDispositions[S]; 12229 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12230 if (V.getPointer() == L) { 12231 V.setInt(D); 12232 break; 12233 } 12234 } 12235 return D; 12236 } 12237 12238 ScalarEvolution::LoopDisposition 12239 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12240 switch (S->getSCEVType()) { 12241 case scConstant: 12242 return LoopInvariant; 12243 case scPtrToInt: 12244 case scTruncate: 12245 case scZeroExtend: 12246 case scSignExtend: 12247 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12248 case scAddRecExpr: { 12249 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12250 12251 // If L is the addrec's loop, it's computable. 12252 if (AR->getLoop() == L) 12253 return LoopComputable; 12254 12255 // Add recurrences are never invariant in the function-body (null loop). 12256 if (!L) 12257 return LoopVariant; 12258 12259 // Everything that is not defined at loop entry is variant. 12260 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12261 return LoopVariant; 12262 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12263 " dominate the contained loop's header?"); 12264 12265 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12266 if (AR->getLoop()->contains(L)) 12267 return LoopInvariant; 12268 12269 // This recurrence is variant w.r.t. L if any of its operands 12270 // are variant. 12271 for (auto *Op : AR->operands()) 12272 if (!isLoopInvariant(Op, L)) 12273 return LoopVariant; 12274 12275 // Otherwise it's loop-invariant. 12276 return LoopInvariant; 12277 } 12278 case scAddExpr: 12279 case scMulExpr: 12280 case scUMaxExpr: 12281 case scSMaxExpr: 12282 case scUMinExpr: 12283 case scSMinExpr: { 12284 bool HasVarying = false; 12285 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12286 LoopDisposition D = getLoopDisposition(Op, L); 12287 if (D == LoopVariant) 12288 return LoopVariant; 12289 if (D == LoopComputable) 12290 HasVarying = true; 12291 } 12292 return HasVarying ? LoopComputable : LoopInvariant; 12293 } 12294 case scUDivExpr: { 12295 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12296 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12297 if (LD == LoopVariant) 12298 return LoopVariant; 12299 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12300 if (RD == LoopVariant) 12301 return LoopVariant; 12302 return (LD == LoopInvariant && RD == LoopInvariant) ? 12303 LoopInvariant : LoopComputable; 12304 } 12305 case scUnknown: 12306 // All non-instruction values are loop invariant. All instructions are loop 12307 // invariant if they are not contained in the specified loop. 12308 // Instructions are never considered invariant in the function body 12309 // (null loop) because they are defined within the "loop". 12310 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12311 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12312 return LoopInvariant; 12313 case scCouldNotCompute: 12314 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12315 } 12316 llvm_unreachable("Unknown SCEV kind!"); 12317 } 12318 12319 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12320 return getLoopDisposition(S, L) == LoopInvariant; 12321 } 12322 12323 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12324 return getLoopDisposition(S, L) == LoopComputable; 12325 } 12326 12327 ScalarEvolution::BlockDisposition 12328 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12329 auto &Values = BlockDispositions[S]; 12330 for (auto &V : Values) { 12331 if (V.getPointer() == BB) 12332 return V.getInt(); 12333 } 12334 Values.emplace_back(BB, DoesNotDominateBlock); 12335 BlockDisposition D = computeBlockDisposition(S, BB); 12336 auto &Values2 = BlockDispositions[S]; 12337 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12338 if (V.getPointer() == BB) { 12339 V.setInt(D); 12340 break; 12341 } 12342 } 12343 return D; 12344 } 12345 12346 ScalarEvolution::BlockDisposition 12347 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12348 switch (S->getSCEVType()) { 12349 case scConstant: 12350 return ProperlyDominatesBlock; 12351 case scPtrToInt: 12352 case scTruncate: 12353 case scZeroExtend: 12354 case scSignExtend: 12355 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12356 case scAddRecExpr: { 12357 // This uses a "dominates" query instead of "properly dominates" query 12358 // to test for proper dominance too, because the instruction which 12359 // produces the addrec's value is a PHI, and a PHI effectively properly 12360 // dominates its entire containing block. 12361 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12362 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12363 return DoesNotDominateBlock; 12364 12365 // Fall through into SCEVNAryExpr handling. 12366 LLVM_FALLTHROUGH; 12367 } 12368 case scAddExpr: 12369 case scMulExpr: 12370 case scUMaxExpr: 12371 case scSMaxExpr: 12372 case scUMinExpr: 12373 case scSMinExpr: { 12374 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12375 bool Proper = true; 12376 for (const SCEV *NAryOp : NAry->operands()) { 12377 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12378 if (D == DoesNotDominateBlock) 12379 return DoesNotDominateBlock; 12380 if (D == DominatesBlock) 12381 Proper = false; 12382 } 12383 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12384 } 12385 case scUDivExpr: { 12386 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12387 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12388 BlockDisposition LD = getBlockDisposition(LHS, BB); 12389 if (LD == DoesNotDominateBlock) 12390 return DoesNotDominateBlock; 12391 BlockDisposition RD = getBlockDisposition(RHS, BB); 12392 if (RD == DoesNotDominateBlock) 12393 return DoesNotDominateBlock; 12394 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12395 ProperlyDominatesBlock : DominatesBlock; 12396 } 12397 case scUnknown: 12398 if (Instruction *I = 12399 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12400 if (I->getParent() == BB) 12401 return DominatesBlock; 12402 if (DT.properlyDominates(I->getParent(), BB)) 12403 return ProperlyDominatesBlock; 12404 return DoesNotDominateBlock; 12405 } 12406 return ProperlyDominatesBlock; 12407 case scCouldNotCompute: 12408 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12409 } 12410 llvm_unreachable("Unknown SCEV kind!"); 12411 } 12412 12413 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12414 return getBlockDisposition(S, BB) >= DominatesBlock; 12415 } 12416 12417 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12418 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12419 } 12420 12421 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12422 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12423 } 12424 12425 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 12426 auto IsS = [&](const SCEV *X) { return S == X; }; 12427 auto ContainsS = [&](const SCEV *X) { 12428 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12429 }; 12430 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12431 } 12432 12433 void 12434 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12435 ValuesAtScopes.erase(S); 12436 LoopDispositions.erase(S); 12437 BlockDispositions.erase(S); 12438 UnsignedRanges.erase(S); 12439 SignedRanges.erase(S); 12440 ExprValueMap.erase(S); 12441 HasRecMap.erase(S); 12442 MinTrailingZerosCache.erase(S); 12443 12444 for (auto I = PredicatedSCEVRewrites.begin(); 12445 I != PredicatedSCEVRewrites.end();) { 12446 std::pair<const SCEV *, const Loop *> Entry = I->first; 12447 if (Entry.first == S) 12448 PredicatedSCEVRewrites.erase(I++); 12449 else 12450 ++I; 12451 } 12452 12453 auto RemoveSCEVFromBackedgeMap = 12454 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12455 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12456 BackedgeTakenInfo &BEInfo = I->second; 12457 if (BEInfo.hasOperand(S, this)) { 12458 BEInfo.clear(); 12459 Map.erase(I++); 12460 } else 12461 ++I; 12462 } 12463 }; 12464 12465 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12466 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12467 } 12468 12469 void 12470 ScalarEvolution::getUsedLoops(const SCEV *S, 12471 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12472 struct FindUsedLoops { 12473 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12474 : LoopsUsed(LoopsUsed) {} 12475 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12476 bool follow(const SCEV *S) { 12477 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12478 LoopsUsed.insert(AR->getLoop()); 12479 return true; 12480 } 12481 12482 bool isDone() const { return false; } 12483 }; 12484 12485 FindUsedLoops F(LoopsUsed); 12486 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12487 } 12488 12489 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12490 SmallPtrSet<const Loop *, 8> LoopsUsed; 12491 getUsedLoops(S, LoopsUsed); 12492 for (auto *L : LoopsUsed) 12493 LoopUsers[L].push_back(S); 12494 } 12495 12496 void ScalarEvolution::verify() const { 12497 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12498 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12499 12500 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12501 12502 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12503 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12504 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12505 12506 const SCEV *visitConstant(const SCEVConstant *Constant) { 12507 return SE.getConstant(Constant->getAPInt()); 12508 } 12509 12510 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12511 return SE.getUnknown(Expr->getValue()); 12512 } 12513 12514 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12515 return SE.getCouldNotCompute(); 12516 } 12517 }; 12518 12519 SCEVMapper SCM(SE2); 12520 12521 while (!LoopStack.empty()) { 12522 auto *L = LoopStack.pop_back_val(); 12523 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12524 12525 auto *CurBECount = SCM.visit( 12526 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12527 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12528 12529 if (CurBECount == SE2.getCouldNotCompute() || 12530 NewBECount == SE2.getCouldNotCompute()) { 12531 // NB! This situation is legal, but is very suspicious -- whatever pass 12532 // change the loop to make a trip count go from could not compute to 12533 // computable or vice-versa *should have* invalidated SCEV. However, we 12534 // choose not to assert here (for now) since we don't want false 12535 // positives. 12536 continue; 12537 } 12538 12539 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12540 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12541 // not propagate undef aggressively). This means we can (and do) fail 12542 // verification in cases where a transform makes the trip count of a loop 12543 // go from "undef" to "undef+1" (say). The transform is fine, since in 12544 // both cases the loop iterates "undef" times, but SCEV thinks we 12545 // increased the trip count of the loop by 1 incorrectly. 12546 continue; 12547 } 12548 12549 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12550 SE.getTypeSizeInBits(NewBECount->getType())) 12551 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12552 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12553 SE.getTypeSizeInBits(NewBECount->getType())) 12554 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12555 12556 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12557 12558 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12559 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12560 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12561 dbgs() << "Old: " << *CurBECount << "\n"; 12562 dbgs() << "New: " << *NewBECount << "\n"; 12563 dbgs() << "Delta: " << *Delta << "\n"; 12564 std::abort(); 12565 } 12566 } 12567 12568 // Collect all valid loops currently in LoopInfo. 12569 SmallPtrSet<Loop *, 32> ValidLoops; 12570 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12571 while (!Worklist.empty()) { 12572 Loop *L = Worklist.pop_back_val(); 12573 if (ValidLoops.contains(L)) 12574 continue; 12575 ValidLoops.insert(L); 12576 Worklist.append(L->begin(), L->end()); 12577 } 12578 // Check for SCEV expressions referencing invalid/deleted loops. 12579 for (auto &KV : ValueExprMap) { 12580 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12581 if (!AR) 12582 continue; 12583 assert(ValidLoops.contains(AR->getLoop()) && 12584 "AddRec references invalid loop"); 12585 } 12586 } 12587 12588 bool ScalarEvolution::invalidate( 12589 Function &F, const PreservedAnalyses &PA, 12590 FunctionAnalysisManager::Invalidator &Inv) { 12591 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12592 // of its dependencies is invalidated. 12593 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12594 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12595 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12596 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12597 Inv.invalidate<LoopAnalysis>(F, PA); 12598 } 12599 12600 AnalysisKey ScalarEvolutionAnalysis::Key; 12601 12602 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12603 FunctionAnalysisManager &AM) { 12604 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12605 AM.getResult<AssumptionAnalysis>(F), 12606 AM.getResult<DominatorTreeAnalysis>(F), 12607 AM.getResult<LoopAnalysis>(F)); 12608 } 12609 12610 PreservedAnalyses 12611 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12612 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12613 return PreservedAnalyses::all(); 12614 } 12615 12616 PreservedAnalyses 12617 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12618 // For compatibility with opt's -analyze feature under legacy pass manager 12619 // which was not ported to NPM. This keeps tests using 12620 // update_analyze_test_checks.py working. 12621 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12622 << F.getName() << "':\n"; 12623 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12624 return PreservedAnalyses::all(); 12625 } 12626 12627 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12628 "Scalar Evolution Analysis", false, true) 12629 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12630 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12631 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12632 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12633 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12634 "Scalar Evolution Analysis", false, true) 12635 12636 char ScalarEvolutionWrapperPass::ID = 0; 12637 12638 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12639 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12640 } 12641 12642 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12643 SE.reset(new ScalarEvolution( 12644 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12645 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12646 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12647 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12648 return false; 12649 } 12650 12651 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12652 12653 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12654 SE->print(OS); 12655 } 12656 12657 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12658 if (!VerifySCEV) 12659 return; 12660 12661 SE->verify(); 12662 } 12663 12664 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12665 AU.setPreservesAll(); 12666 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12667 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12668 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12669 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12670 } 12671 12672 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12673 const SCEV *RHS) { 12674 FoldingSetNodeID ID; 12675 assert(LHS->getType() == RHS->getType() && 12676 "Type mismatch between LHS and RHS"); 12677 // Unique this node based on the arguments 12678 ID.AddInteger(SCEVPredicate::P_Equal); 12679 ID.AddPointer(LHS); 12680 ID.AddPointer(RHS); 12681 void *IP = nullptr; 12682 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12683 return S; 12684 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12685 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12686 UniquePreds.InsertNode(Eq, IP); 12687 return Eq; 12688 } 12689 12690 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12691 const SCEVAddRecExpr *AR, 12692 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12693 FoldingSetNodeID ID; 12694 // Unique this node based on the arguments 12695 ID.AddInteger(SCEVPredicate::P_Wrap); 12696 ID.AddPointer(AR); 12697 ID.AddInteger(AddedFlags); 12698 void *IP = nullptr; 12699 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12700 return S; 12701 auto *OF = new (SCEVAllocator) 12702 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12703 UniquePreds.InsertNode(OF, IP); 12704 return OF; 12705 } 12706 12707 namespace { 12708 12709 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12710 public: 12711 12712 /// Rewrites \p S in the context of a loop L and the SCEV predication 12713 /// infrastructure. 12714 /// 12715 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12716 /// equivalences present in \p Pred. 12717 /// 12718 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12719 /// \p NewPreds such that the result will be an AddRecExpr. 12720 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12721 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12722 SCEVUnionPredicate *Pred) { 12723 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12724 return Rewriter.visit(S); 12725 } 12726 12727 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12728 if (Pred) { 12729 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12730 for (auto *Pred : ExprPreds) 12731 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12732 if (IPred->getLHS() == Expr) 12733 return IPred->getRHS(); 12734 } 12735 return convertToAddRecWithPreds(Expr); 12736 } 12737 12738 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12739 const SCEV *Operand = visit(Expr->getOperand()); 12740 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12741 if (AR && AR->getLoop() == L && AR->isAffine()) { 12742 // This couldn't be folded because the operand didn't have the nuw 12743 // flag. Add the nusw flag as an assumption that we could make. 12744 const SCEV *Step = AR->getStepRecurrence(SE); 12745 Type *Ty = Expr->getType(); 12746 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12747 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12748 SE.getSignExtendExpr(Step, Ty), L, 12749 AR->getNoWrapFlags()); 12750 } 12751 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12752 } 12753 12754 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12755 const SCEV *Operand = visit(Expr->getOperand()); 12756 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12757 if (AR && AR->getLoop() == L && AR->isAffine()) { 12758 // This couldn't be folded because the operand didn't have the nsw 12759 // flag. Add the nssw flag as an assumption that we could make. 12760 const SCEV *Step = AR->getStepRecurrence(SE); 12761 Type *Ty = Expr->getType(); 12762 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12763 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12764 SE.getSignExtendExpr(Step, Ty), L, 12765 AR->getNoWrapFlags()); 12766 } 12767 return SE.getSignExtendExpr(Operand, Expr->getType()); 12768 } 12769 12770 private: 12771 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12772 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12773 SCEVUnionPredicate *Pred) 12774 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12775 12776 bool addOverflowAssumption(const SCEVPredicate *P) { 12777 if (!NewPreds) { 12778 // Check if we've already made this assumption. 12779 return Pred && Pred->implies(P); 12780 } 12781 NewPreds->insert(P); 12782 return true; 12783 } 12784 12785 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12786 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12787 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12788 return addOverflowAssumption(A); 12789 } 12790 12791 // If \p Expr represents a PHINode, we try to see if it can be represented 12792 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12793 // to add this predicate as a runtime overflow check, we return the AddRec. 12794 // If \p Expr does not meet these conditions (is not a PHI node, or we 12795 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12796 // return \p Expr. 12797 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12798 if (!isa<PHINode>(Expr->getValue())) 12799 return Expr; 12800 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12801 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12802 if (!PredicatedRewrite) 12803 return Expr; 12804 for (auto *P : PredicatedRewrite->second){ 12805 // Wrap predicates from outer loops are not supported. 12806 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12807 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12808 if (L != AR->getLoop()) 12809 return Expr; 12810 } 12811 if (!addOverflowAssumption(P)) 12812 return Expr; 12813 } 12814 return PredicatedRewrite->first; 12815 } 12816 12817 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12818 SCEVUnionPredicate *Pred; 12819 const Loop *L; 12820 }; 12821 12822 } // end anonymous namespace 12823 12824 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12825 SCEVUnionPredicate &Preds) { 12826 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12827 } 12828 12829 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12830 const SCEV *S, const Loop *L, 12831 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12832 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12833 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12834 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12835 12836 if (!AddRec) 12837 return nullptr; 12838 12839 // Since the transformation was successful, we can now transfer the SCEV 12840 // predicates. 12841 for (auto *P : TransformPreds) 12842 Preds.insert(P); 12843 12844 return AddRec; 12845 } 12846 12847 /// SCEV predicates 12848 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12849 SCEVPredicateKind Kind) 12850 : FastID(ID), Kind(Kind) {} 12851 12852 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12853 const SCEV *LHS, const SCEV *RHS) 12854 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12855 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12856 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12857 } 12858 12859 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12860 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12861 12862 if (!Op) 12863 return false; 12864 12865 return Op->LHS == LHS && Op->RHS == RHS; 12866 } 12867 12868 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12869 12870 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12871 12872 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12873 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12874 } 12875 12876 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12877 const SCEVAddRecExpr *AR, 12878 IncrementWrapFlags Flags) 12879 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12880 12881 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12882 12883 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12884 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12885 12886 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12887 } 12888 12889 bool SCEVWrapPredicate::isAlwaysTrue() const { 12890 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12891 IncrementWrapFlags IFlags = Flags; 12892 12893 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12894 IFlags = clearFlags(IFlags, IncrementNSSW); 12895 12896 return IFlags == IncrementAnyWrap; 12897 } 12898 12899 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12900 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12901 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12902 OS << "<nusw>"; 12903 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12904 OS << "<nssw>"; 12905 OS << "\n"; 12906 } 12907 12908 SCEVWrapPredicate::IncrementWrapFlags 12909 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12910 ScalarEvolution &SE) { 12911 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12912 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12913 12914 // We can safely transfer the NSW flag as NSSW. 12915 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12916 ImpliedFlags = IncrementNSSW; 12917 12918 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12919 // If the increment is positive, the SCEV NUW flag will also imply the 12920 // WrapPredicate NUSW flag. 12921 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12922 if (Step->getValue()->getValue().isNonNegative()) 12923 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12924 } 12925 12926 return ImpliedFlags; 12927 } 12928 12929 /// Union predicates don't get cached so create a dummy set ID for it. 12930 SCEVUnionPredicate::SCEVUnionPredicate() 12931 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12932 12933 bool SCEVUnionPredicate::isAlwaysTrue() const { 12934 return all_of(Preds, 12935 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12936 } 12937 12938 ArrayRef<const SCEVPredicate *> 12939 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12940 auto I = SCEVToPreds.find(Expr); 12941 if (I == SCEVToPreds.end()) 12942 return ArrayRef<const SCEVPredicate *>(); 12943 return I->second; 12944 } 12945 12946 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12947 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12948 return all_of(Set->Preds, 12949 [this](const SCEVPredicate *I) { return this->implies(I); }); 12950 12951 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12952 if (ScevPredsIt == SCEVToPreds.end()) 12953 return false; 12954 auto &SCEVPreds = ScevPredsIt->second; 12955 12956 return any_of(SCEVPreds, 12957 [N](const SCEVPredicate *I) { return I->implies(N); }); 12958 } 12959 12960 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12961 12962 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12963 for (auto Pred : Preds) 12964 Pred->print(OS, Depth); 12965 } 12966 12967 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12968 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12969 for (auto Pred : Set->Preds) 12970 add(Pred); 12971 return; 12972 } 12973 12974 if (implies(N)) 12975 return; 12976 12977 const SCEV *Key = N->getExpr(); 12978 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12979 " associated expression!"); 12980 12981 SCEVToPreds[Key].push_back(N); 12982 Preds.push_back(N); 12983 } 12984 12985 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12986 Loop &L) 12987 : SE(SE), L(L) {} 12988 12989 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12990 const SCEV *Expr = SE.getSCEV(V); 12991 RewriteEntry &Entry = RewriteMap[Expr]; 12992 12993 // If we already have an entry and the version matches, return it. 12994 if (Entry.second && Generation == Entry.first) 12995 return Entry.second; 12996 12997 // We found an entry but it's stale. Rewrite the stale entry 12998 // according to the current predicate. 12999 if (Entry.second) 13000 Expr = Entry.second; 13001 13002 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13003 Entry = {Generation, NewSCEV}; 13004 13005 return NewSCEV; 13006 } 13007 13008 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13009 if (!BackedgeCount) { 13010 SCEVUnionPredicate BackedgePred; 13011 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13012 addPredicate(BackedgePred); 13013 } 13014 return BackedgeCount; 13015 } 13016 13017 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13018 if (Preds.implies(&Pred)) 13019 return; 13020 Preds.add(&Pred); 13021 updateGeneration(); 13022 } 13023 13024 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13025 return Preds; 13026 } 13027 13028 void PredicatedScalarEvolution::updateGeneration() { 13029 // If the generation number wrapped recompute everything. 13030 if (++Generation == 0) { 13031 for (auto &II : RewriteMap) { 13032 const SCEV *Rewritten = II.second.second; 13033 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13034 } 13035 } 13036 } 13037 13038 void PredicatedScalarEvolution::setNoOverflow( 13039 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13040 const SCEV *Expr = getSCEV(V); 13041 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13042 13043 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13044 13045 // Clear the statically implied flags. 13046 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13047 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13048 13049 auto II = FlagsMap.insert({V, Flags}); 13050 if (!II.second) 13051 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13052 } 13053 13054 bool PredicatedScalarEvolution::hasNoOverflow( 13055 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13056 const SCEV *Expr = getSCEV(V); 13057 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13058 13059 Flags = SCEVWrapPredicate::clearFlags( 13060 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13061 13062 auto II = FlagsMap.find(V); 13063 13064 if (II != FlagsMap.end()) 13065 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13066 13067 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13068 } 13069 13070 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13071 const SCEV *Expr = this->getSCEV(V); 13072 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13073 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13074 13075 if (!New) 13076 return nullptr; 13077 13078 for (auto *P : NewPreds) 13079 Preds.add(P); 13080 13081 updateGeneration(); 13082 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13083 return New; 13084 } 13085 13086 PredicatedScalarEvolution::PredicatedScalarEvolution( 13087 const PredicatedScalarEvolution &Init) 13088 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13089 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13090 for (auto I : Init.FlagsMap) 13091 FlagsMap.insert(I); 13092 } 13093 13094 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13095 // For each block. 13096 for (auto *BB : L.getBlocks()) 13097 for (auto &I : *BB) { 13098 if (!SE.isSCEVable(I.getType())) 13099 continue; 13100 13101 auto *Expr = SE.getSCEV(&I); 13102 auto II = RewriteMap.find(Expr); 13103 13104 if (II == RewriteMap.end()) 13105 continue; 13106 13107 // Don't print things that are not interesting. 13108 if (II->second.second == Expr) 13109 continue; 13110 13111 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13112 OS.indent(Depth + 2) << *Expr << "\n"; 13113 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13114 } 13115 } 13116 13117 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13118 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13119 // for URem with constant power-of-2 second operands. 13120 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13121 // 4, A / B becomes X / 8). 13122 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13123 const SCEV *&RHS) { 13124 // Try to match 'zext (trunc A to iB) to iY', which is used 13125 // for URem with constant power-of-2 second operands. Make sure the size of 13126 // the operand A matches the size of the whole expressions. 13127 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13128 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13129 LHS = Trunc->getOperand(); 13130 if (LHS->getType() != Expr->getType()) 13131 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13132 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13133 << getTypeSizeInBits(Trunc->getType())); 13134 return true; 13135 } 13136 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13137 if (Add == nullptr || Add->getNumOperands() != 2) 13138 return false; 13139 13140 const SCEV *A = Add->getOperand(1); 13141 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13142 13143 if (Mul == nullptr) 13144 return false; 13145 13146 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13147 // (SomeExpr + (-(SomeExpr / B) * B)). 13148 if (Expr == getURemExpr(A, B)) { 13149 LHS = A; 13150 RHS = B; 13151 return true; 13152 } 13153 return false; 13154 }; 13155 13156 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13157 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13158 return MatchURemWithDivisor(Mul->getOperand(1)) || 13159 MatchURemWithDivisor(Mul->getOperand(2)); 13160 13161 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13162 if (Mul->getNumOperands() == 2) 13163 return MatchURemWithDivisor(Mul->getOperand(1)) || 13164 MatchURemWithDivisor(Mul->getOperand(0)) || 13165 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13166 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13167 return false; 13168 } 13169 13170 const SCEV * 13171 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13172 SmallVector<BasicBlock*, 16> ExitingBlocks; 13173 L->getExitingBlocks(ExitingBlocks); 13174 13175 // Form an expression for the maximum exit count possible for this loop. We 13176 // merge the max and exact information to approximate a version of 13177 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13178 SmallVector<const SCEV*, 4> ExitCounts; 13179 for (BasicBlock *ExitingBB : ExitingBlocks) { 13180 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13181 if (isa<SCEVCouldNotCompute>(ExitCount)) 13182 ExitCount = getExitCount(L, ExitingBB, 13183 ScalarEvolution::ConstantMaximum); 13184 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13185 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13186 "We should only have known counts for exiting blocks that " 13187 "dominate latch!"); 13188 ExitCounts.push_back(ExitCount); 13189 } 13190 } 13191 if (ExitCounts.empty()) 13192 return getCouldNotCompute(); 13193 return getUMinFromMismatchedTypes(ExitCounts); 13194 } 13195 13196 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13197 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13198 /// we cannot guarantee that the replacement is loop invariant in the loop of 13199 /// the AddRec. 13200 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13201 ValueToSCEVMapTy ⤅ 13202 13203 public: 13204 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13205 : SCEVRewriteVisitor(SE), Map(M) {} 13206 13207 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13208 13209 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13210 auto I = Map.find(Expr->getValue()); 13211 if (I == Map.end()) 13212 return Expr; 13213 return I->second; 13214 } 13215 }; 13216 13217 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13218 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13219 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13220 if (!isa<SCEVUnknown>(LHS)) { 13221 std::swap(LHS, RHS); 13222 Predicate = CmpInst::getSwappedPredicate(Predicate); 13223 } 13224 13225 // For now, limit to conditions that provide information about unknown 13226 // expressions. 13227 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13228 if (!LHSUnknown) 13229 return; 13230 13231 // TODO: use information from more predicates. 13232 switch (Predicate) { 13233 case CmpInst::ICMP_ULT: { 13234 if (!containsAddRecurrence(RHS)) { 13235 const SCEV *Base = LHS; 13236 auto I = RewriteMap.find(LHSUnknown->getValue()); 13237 if (I != RewriteMap.end()) 13238 Base = I->second; 13239 13240 RewriteMap[LHSUnknown->getValue()] = 13241 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 13242 } 13243 break; 13244 } 13245 case CmpInst::ICMP_ULE: { 13246 if (!containsAddRecurrence(RHS)) { 13247 const SCEV *Base = LHS; 13248 auto I = RewriteMap.find(LHSUnknown->getValue()); 13249 if (I != RewriteMap.end()) 13250 Base = I->second; 13251 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 13252 } 13253 break; 13254 } 13255 case CmpInst::ICMP_EQ: 13256 if (isa<SCEVConstant>(RHS)) 13257 RewriteMap[LHSUnknown->getValue()] = RHS; 13258 break; 13259 case CmpInst::ICMP_NE: 13260 if (isa<SCEVConstant>(RHS) && 13261 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13262 RewriteMap[LHSUnknown->getValue()] = 13263 getUMaxExpr(LHS, getOne(RHS->getType())); 13264 break; 13265 default: 13266 break; 13267 } 13268 }; 13269 // Starting at the loop predecessor, climb up the predecessor chain, as long 13270 // as there are predecessors that can be found that have unique successors 13271 // leading to the original header. 13272 // TODO: share this logic with isLoopEntryGuardedByCond. 13273 ValueToSCEVMapTy RewriteMap; 13274 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13275 L->getLoopPredecessor(), L->getHeader()); 13276 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13277 13278 const BranchInst *LoopEntryPredicate = 13279 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13280 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13281 continue; 13282 13283 // TODO: use information from more complex conditions, e.g. AND expressions. 13284 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 13285 if (!Cmp) 13286 continue; 13287 13288 auto Predicate = Cmp->getPredicate(); 13289 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 13290 Predicate = CmpInst::getInversePredicate(Predicate); 13291 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13292 getSCEV(Cmp->getOperand(1)), RewriteMap); 13293 } 13294 13295 // Also collect information from assumptions dominating the loop. 13296 for (auto &AssumeVH : AC.assumptions()) { 13297 if (!AssumeVH) 13298 continue; 13299 auto *AssumeI = cast<CallInst>(AssumeVH); 13300 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13301 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13302 continue; 13303 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13304 getSCEV(Cmp->getOperand(1)), RewriteMap); 13305 } 13306 13307 if (RewriteMap.empty()) 13308 return Expr; 13309 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13310 return Rewriter.visit(Expr); 13311 } 13312