1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/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 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (static_cast<SCEVTypes>(getSCEVType())) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 } 308 OS << "("; 309 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 310 I != E; ++I) { 311 OS << **I; 312 if (std::next(I) != E) 313 OS << OpStr; 314 } 315 OS << ")"; 316 switch (NAry->getSCEVType()) { 317 case scAddExpr: 318 case scMulExpr: 319 if (NAry->hasNoUnsignedWrap()) 320 OS << "<nuw>"; 321 if (NAry->hasNoSignedWrap()) 322 OS << "<nsw>"; 323 } 324 return; 325 } 326 case scUDivExpr: { 327 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 328 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 329 return; 330 } 331 case scUnknown: { 332 const SCEVUnknown *U = cast<SCEVUnknown>(this); 333 Type *AllocTy; 334 if (U->isSizeOf(AllocTy)) { 335 OS << "sizeof(" << *AllocTy << ")"; 336 return; 337 } 338 if (U->isAlignOf(AllocTy)) { 339 OS << "alignof(" << *AllocTy << ")"; 340 return; 341 } 342 343 Type *CTy; 344 Constant *FieldNo; 345 if (U->isOffsetOf(CTy, FieldNo)) { 346 OS << "offsetof(" << *CTy << ", "; 347 FieldNo->printAsOperand(OS, false); 348 OS << ")"; 349 return; 350 } 351 352 // Otherwise just print it normally. 353 U->getValue()->printAsOperand(OS, false); 354 return; 355 } 356 case scCouldNotCompute: 357 OS << "***COULDNOTCOMPUTE***"; 358 return; 359 } 360 llvm_unreachable("Unknown SCEV kind!"); 361 } 362 363 Type *SCEV::getType() const { 364 switch (static_cast<SCEVTypes>(getSCEVType())) { 365 case scConstant: 366 return cast<SCEVConstant>(this)->getType(); 367 case scTruncate: 368 case scZeroExtend: 369 case scSignExtend: 370 return cast<SCEVCastExpr>(this)->getType(); 371 case scAddRecExpr: 372 case scMulExpr: 373 case scUMaxExpr: 374 case scSMaxExpr: 375 case scUMinExpr: 376 case scSMinExpr: 377 return cast<SCEVNAryExpr>(this)->getType(); 378 case scAddExpr: 379 return cast<SCEVAddExpr>(this)->getType(); 380 case scUDivExpr: 381 return cast<SCEVUDivExpr>(this)->getType(); 382 case scUnknown: 383 return cast<SCEVUnknown>(this)->getType(); 384 case scCouldNotCompute: 385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 386 } 387 llvm_unreachable("Unknown SCEV kind!"); 388 } 389 390 bool SCEV::isZero() const { 391 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 392 return SC->getValue()->isZero(); 393 return false; 394 } 395 396 bool SCEV::isOne() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isOne(); 399 return false; 400 } 401 402 bool SCEV::isAllOnesValue() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isMinusOne(); 405 return false; 406 } 407 408 bool SCEV::isNonConstantNegative() const { 409 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 410 if (!Mul) return false; 411 412 // If there is a constant factor, it will be first. 413 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 414 if (!SC) return false; 415 416 // Return true if the value is negative, this matches things like (-42 * V). 417 return SC->getAPInt().isNegative(); 418 } 419 420 SCEVCouldNotCompute::SCEVCouldNotCompute() : 421 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 422 423 bool SCEVCouldNotCompute::classof(const SCEV *S) { 424 return S->getSCEVType() == scCouldNotCompute; 425 } 426 427 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 428 FoldingSetNodeID ID; 429 ID.AddInteger(scConstant); 430 ID.AddPointer(V); 431 void *IP = nullptr; 432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 433 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 434 UniqueSCEVs.InsertNode(S, IP); 435 return S; 436 } 437 438 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 439 return getConstant(ConstantInt::get(getContext(), Val)); 440 } 441 442 const SCEV * 443 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 445 return getConstant(ConstantInt::get(ITy, V, isSigned)); 446 } 447 448 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 449 unsigned SCEVTy, const SCEV *op, Type *ty) 450 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 451 452 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 453 const SCEV *op, Type *ty) 454 : SCEVCastExpr(ID, scTruncate, op, ty) { 455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 456 "Cannot truncate non-integer value!"); 457 } 458 459 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 460 const SCEV *op, Type *ty) 461 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 463 "Cannot zero extend non-integer value!"); 464 } 465 466 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 467 const SCEV *op, Type *ty) 468 : SCEVCastExpr(ID, scSignExtend, op, ty) { 469 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 470 "Cannot sign extend non-integer value!"); 471 } 472 473 void SCEVUnknown::deleted() { 474 // Clear this SCEVUnknown from various maps. 475 SE->forgetMemoizedResults(this); 476 477 // Remove this SCEVUnknown from the uniquing map. 478 SE->UniqueSCEVs.RemoveNode(this); 479 480 // Release the value. 481 setValPtr(nullptr); 482 } 483 484 void SCEVUnknown::allUsesReplacedWith(Value *New) { 485 // Remove this SCEVUnknown from the uniquing map. 486 SE->UniqueSCEVs.RemoveNode(this); 487 488 // Update this SCEVUnknown to point to the new value. This is needed 489 // because there may still be outstanding SCEVs which still point to 490 // this SCEVUnknown. 491 setValPtr(New); 492 } 493 494 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 495 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 496 if (VCE->getOpcode() == Instruction::PtrToInt) 497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 498 if (CE->getOpcode() == Instruction::GetElementPtr && 499 CE->getOperand(0)->isNullValue() && 500 CE->getNumOperands() == 2) 501 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 502 if (CI->isOne()) { 503 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 504 ->getElementType(); 505 return true; 506 } 507 508 return false; 509 } 510 511 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 512 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 513 if (VCE->getOpcode() == Instruction::PtrToInt) 514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 515 if (CE->getOpcode() == Instruction::GetElementPtr && 516 CE->getOperand(0)->isNullValue()) { 517 Type *Ty = 518 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 519 if (StructType *STy = dyn_cast<StructType>(Ty)) 520 if (!STy->isPacked() && 521 CE->getNumOperands() == 3 && 522 CE->getOperand(1)->isNullValue()) { 523 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 524 if (CI->isOne() && 525 STy->getNumElements() == 2 && 526 STy->getElementType(0)->isIntegerTy(1)) { 527 AllocTy = STy->getElementType(1); 528 return true; 529 } 530 } 531 } 532 533 return false; 534 } 535 536 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 537 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 538 if (VCE->getOpcode() == Instruction::PtrToInt) 539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 540 if (CE->getOpcode() == Instruction::GetElementPtr && 541 CE->getNumOperands() == 3 && 542 CE->getOperand(0)->isNullValue() && 543 CE->getOperand(1)->isNullValue()) { 544 Type *Ty = 545 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 546 // Ignore vector types here so that ScalarEvolutionExpander doesn't 547 // emit getelementptrs that index into vectors. 548 if (Ty->isStructTy() || Ty->isArrayTy()) { 549 CTy = Ty; 550 FieldNo = CE->getOperand(2); 551 return true; 552 } 553 } 554 555 return false; 556 } 557 558 //===----------------------------------------------------------------------===// 559 // SCEV Utilities 560 //===----------------------------------------------------------------------===// 561 562 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 563 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 564 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 565 /// have been previously deemed to be "equally complex" by this routine. It is 566 /// intended to avoid exponential time complexity in cases like: 567 /// 568 /// %a = f(%x, %y) 569 /// %b = f(%a, %a) 570 /// %c = f(%b, %b) 571 /// 572 /// %d = f(%x, %y) 573 /// %e = f(%d, %d) 574 /// %f = f(%e, %e) 575 /// 576 /// CompareValueComplexity(%f, %c) 577 /// 578 /// Since we do not continue running this routine on expression trees once we 579 /// have seen unequal values, there is no need to track them in the cache. 580 static int 581 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 582 const LoopInfo *const LI, Value *LV, Value *RV, 583 unsigned Depth) { 584 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 585 return 0; 586 587 // Order pointer values after integer values. This helps SCEVExpander form 588 // GEPs. 589 bool LIsPointer = LV->getType()->isPointerTy(), 590 RIsPointer = RV->getType()->isPointerTy(); 591 if (LIsPointer != RIsPointer) 592 return (int)LIsPointer - (int)RIsPointer; 593 594 // Compare getValueID values. 595 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 596 if (LID != RID) 597 return (int)LID - (int)RID; 598 599 // Sort arguments by their position. 600 if (const auto *LA = dyn_cast<Argument>(LV)) { 601 const auto *RA = cast<Argument>(RV); 602 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 603 return (int)LArgNo - (int)RArgNo; 604 } 605 606 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 607 const auto *RGV = cast<GlobalValue>(RV); 608 609 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 610 auto LT = GV->getLinkage(); 611 return !(GlobalValue::isPrivateLinkage(LT) || 612 GlobalValue::isInternalLinkage(LT)); 613 }; 614 615 // Use the names to distinguish the two values, but only if the 616 // names are semantically important. 617 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 618 return LGV->getName().compare(RGV->getName()); 619 } 620 621 // For instructions, compare their loop depth, and their operand count. This 622 // is pretty loose. 623 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 624 const auto *RInst = cast<Instruction>(RV); 625 626 // Compare loop depths. 627 const BasicBlock *LParent = LInst->getParent(), 628 *RParent = RInst->getParent(); 629 if (LParent != RParent) { 630 unsigned LDepth = LI->getLoopDepth(LParent), 631 RDepth = LI->getLoopDepth(RParent); 632 if (LDepth != RDepth) 633 return (int)LDepth - (int)RDepth; 634 } 635 636 // Compare the number of operands. 637 unsigned LNumOps = LInst->getNumOperands(), 638 RNumOps = RInst->getNumOperands(); 639 if (LNumOps != RNumOps) 640 return (int)LNumOps - (int)RNumOps; 641 642 for (unsigned Idx : seq(0u, LNumOps)) { 643 int Result = 644 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 645 RInst->getOperand(Idx), Depth + 1); 646 if (Result != 0) 647 return Result; 648 } 649 } 650 651 EqCacheValue.unionSets(LV, RV); 652 return 0; 653 } 654 655 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 656 // than RHS, respectively. A three-way result allows recursive comparisons to be 657 // more efficient. 658 static int CompareSCEVComplexity( 659 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 660 EquivalenceClasses<const Value *> &EqCacheValue, 661 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 662 DominatorTree &DT, unsigned Depth = 0) { 663 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 664 if (LHS == RHS) 665 return 0; 666 667 // Primarily, sort the SCEVs by their getSCEVType(). 668 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 669 if (LType != RType) 670 return (int)LType - (int)RType; 671 672 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 673 return 0; 674 // Aside from the getSCEVType() ordering, the particular ordering 675 // isn't very important except that it's beneficial to be consistent, 676 // so that (a + b) and (b + a) don't end up as different expressions. 677 switch (static_cast<SCEVTypes>(LType)) { 678 case scUnknown: { 679 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 680 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 681 682 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 683 RU->getValue(), Depth + 1); 684 if (X == 0) 685 EqCacheSCEV.unionSets(LHS, RHS); 686 return X; 687 } 688 689 case scConstant: { 690 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 691 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 692 693 // Compare constant values. 694 const APInt &LA = LC->getAPInt(); 695 const APInt &RA = RC->getAPInt(); 696 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 697 if (LBitWidth != RBitWidth) 698 return (int)LBitWidth - (int)RBitWidth; 699 return LA.ult(RA) ? -1 : 1; 700 } 701 702 case scAddRecExpr: { 703 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 704 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 705 706 // There is always a dominance between two recs that are used by one SCEV, 707 // so we can safely sort recs by loop header dominance. We require such 708 // order in getAddExpr. 709 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 710 if (LLoop != RLoop) { 711 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 712 assert(LHead != RHead && "Two loops share the same header?"); 713 if (DT.dominates(LHead, RHead)) 714 return 1; 715 else 716 assert(DT.dominates(RHead, LHead) && 717 "No dominance between recurrences used by one SCEV?"); 718 return -1; 719 } 720 721 // Addrec complexity grows with operand count. 722 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 723 if (LNumOps != RNumOps) 724 return (int)LNumOps - (int)RNumOps; 725 726 // Lexicographically compare. 727 for (unsigned i = 0; i != LNumOps; ++i) { 728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 729 LA->getOperand(i), RA->getOperand(i), DT, 730 Depth + 1); 731 if (X != 0) 732 return X; 733 } 734 EqCacheSCEV.unionSets(LHS, RHS); 735 return 0; 736 } 737 738 case scAddExpr: 739 case scMulExpr: 740 case scSMaxExpr: 741 case scUMaxExpr: 742 case scSMinExpr: 743 case scUMinExpr: { 744 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 745 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 746 747 // Lexicographically compare n-ary expressions. 748 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 749 if (LNumOps != RNumOps) 750 return (int)LNumOps - (int)RNumOps; 751 752 for (unsigned i = 0; i != LNumOps; ++i) { 753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 754 LC->getOperand(i), RC->getOperand(i), DT, 755 Depth + 1); 756 if (X != 0) 757 return X; 758 } 759 EqCacheSCEV.unionSets(LHS, RHS); 760 return 0; 761 } 762 763 case scUDivExpr: { 764 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 765 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 766 767 // Lexicographically compare udiv expressions. 768 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 769 RC->getLHS(), DT, Depth + 1); 770 if (X != 0) 771 return X; 772 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 773 RC->getRHS(), DT, Depth + 1); 774 if (X == 0) 775 EqCacheSCEV.unionSets(LHS, RHS); 776 return X; 777 } 778 779 case scTruncate: 780 case scZeroExtend: 781 case scSignExtend: { 782 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 783 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 784 785 // Compare cast expressions by operand. 786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 787 LC->getOperand(), RC->getOperand(), DT, 788 Depth + 1); 789 if (X == 0) 790 EqCacheSCEV.unionSets(LHS, RHS); 791 return X; 792 } 793 794 case scCouldNotCompute: 795 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 796 } 797 llvm_unreachable("Unknown SCEV kind!"); 798 } 799 800 /// Given a list of SCEV objects, order them by their complexity, and group 801 /// objects of the same complexity together by value. When this routine is 802 /// finished, we know that any duplicates in the vector are consecutive and that 803 /// complexity is monotonically increasing. 804 /// 805 /// Note that we go take special precautions to ensure that we get deterministic 806 /// results from this routine. In other words, we don't want the results of 807 /// this to depend on where the addresses of various SCEV objects happened to 808 /// land in memory. 809 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 810 LoopInfo *LI, DominatorTree &DT) { 811 if (Ops.size() < 2) return; // Noop 812 813 EquivalenceClasses<const SCEV *> EqCacheSCEV; 814 EquivalenceClasses<const Value *> EqCacheValue; 815 if (Ops.size() == 2) { 816 // This is the common case, which also happens to be trivially simple. 817 // Special case it. 818 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 819 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 820 std::swap(LHS, RHS); 821 return; 822 } 823 824 // Do the rough sort by complexity. 825 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 826 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 827 0; 828 }); 829 830 // Now that we are sorted by complexity, group elements of the same 831 // complexity. Note that this is, at worst, N^2, but the vector is likely to 832 // be extremely short in practice. Note that we take this approach because we 833 // do not want to depend on the addresses of the objects we are grouping. 834 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 835 const SCEV *S = Ops[i]; 836 unsigned Complexity = S->getSCEVType(); 837 838 // If there are any objects of the same complexity and same value as this 839 // one, group them. 840 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 841 if (Ops[j] == S) { // Found a duplicate. 842 // Move it to immediately after i'th element. 843 std::swap(Ops[i+1], Ops[j]); 844 ++i; // no need to rescan it. 845 if (i == e-2) return; // Done! 846 } 847 } 848 } 849 } 850 851 // Returns the size of the SCEV S. 852 static inline int sizeOfSCEV(const SCEV *S) { 853 struct FindSCEVSize { 854 int Size = 0; 855 856 FindSCEVSize() = default; 857 858 bool follow(const SCEV *S) { 859 ++Size; 860 // Keep looking at all operands of S. 861 return true; 862 } 863 864 bool isDone() const { 865 return false; 866 } 867 }; 868 869 FindSCEVSize F; 870 SCEVTraversal<FindSCEVSize> ST(F); 871 ST.visitAll(S); 872 return F.Size; 873 } 874 875 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 876 /// least HugeExprThreshold nodes). 877 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 878 return any_of(Ops, [](const SCEV *S) { 879 return S->getExpressionSize() >= HugeExprThreshold; 880 }); 881 } 882 883 namespace { 884 885 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 886 public: 887 // Computes the Quotient and Remainder of the division of Numerator by 888 // Denominator. 889 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 890 const SCEV *Denominator, const SCEV **Quotient, 891 const SCEV **Remainder) { 892 assert(Numerator && Denominator && "Uninitialized SCEV"); 893 894 SCEVDivision D(SE, Numerator, Denominator); 895 896 // Check for the trivial case here to avoid having to check for it in the 897 // rest of the code. 898 if (Numerator == Denominator) { 899 *Quotient = D.One; 900 *Remainder = D.Zero; 901 return; 902 } 903 904 if (Numerator->isZero()) { 905 *Quotient = D.Zero; 906 *Remainder = D.Zero; 907 return; 908 } 909 910 // A simple case when N/1. The quotient is N. 911 if (Denominator->isOne()) { 912 *Quotient = Numerator; 913 *Remainder = D.Zero; 914 return; 915 } 916 917 // Split the Denominator when it is a product. 918 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 919 const SCEV *Q, *R; 920 *Quotient = Numerator; 921 for (const SCEV *Op : T->operands()) { 922 divide(SE, *Quotient, Op, &Q, &R); 923 *Quotient = Q; 924 925 // Bail out when the Numerator is not divisible by one of the terms of 926 // the Denominator. 927 if (!R->isZero()) { 928 *Quotient = D.Zero; 929 *Remainder = Numerator; 930 return; 931 } 932 } 933 *Remainder = D.Zero; 934 return; 935 } 936 937 D.visit(Numerator); 938 *Quotient = D.Quotient; 939 *Remainder = D.Remainder; 940 } 941 942 // Except in the trivial case described above, we do not know how to divide 943 // Expr by Denominator for the following functions with empty implementation. 944 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 945 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 946 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 947 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 948 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 949 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 950 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 951 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 952 void visitUnknown(const SCEVUnknown *Numerator) {} 953 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 954 955 void visitConstant(const SCEVConstant *Numerator) { 956 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 957 APInt NumeratorVal = Numerator->getAPInt(); 958 APInt DenominatorVal = D->getAPInt(); 959 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 960 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 961 962 if (NumeratorBW > DenominatorBW) 963 DenominatorVal = DenominatorVal.sext(NumeratorBW); 964 else if (NumeratorBW < DenominatorBW) 965 NumeratorVal = NumeratorVal.sext(DenominatorBW); 966 967 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 968 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 969 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 970 Quotient = SE.getConstant(QuotientVal); 971 Remainder = SE.getConstant(RemainderVal); 972 return; 973 } 974 } 975 976 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 977 const SCEV *StartQ, *StartR, *StepQ, *StepR; 978 if (!Numerator->isAffine()) 979 return cannotDivide(Numerator); 980 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 981 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 982 // Bail out if the types do not match. 983 Type *Ty = Denominator->getType(); 984 if (Ty != StartQ->getType() || Ty != StartR->getType() || 985 Ty != StepQ->getType() || Ty != StepR->getType()) 986 return cannotDivide(Numerator); 987 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 988 Numerator->getNoWrapFlags()); 989 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 990 Numerator->getNoWrapFlags()); 991 } 992 993 void visitAddExpr(const SCEVAddExpr *Numerator) { 994 SmallVector<const SCEV *, 2> Qs, Rs; 995 Type *Ty = Denominator->getType(); 996 997 for (const SCEV *Op : Numerator->operands()) { 998 const SCEV *Q, *R; 999 divide(SE, Op, Denominator, &Q, &R); 1000 1001 // Bail out if types do not match. 1002 if (Ty != Q->getType() || Ty != R->getType()) 1003 return cannotDivide(Numerator); 1004 1005 Qs.push_back(Q); 1006 Rs.push_back(R); 1007 } 1008 1009 if (Qs.size() == 1) { 1010 Quotient = Qs[0]; 1011 Remainder = Rs[0]; 1012 return; 1013 } 1014 1015 Quotient = SE.getAddExpr(Qs); 1016 Remainder = SE.getAddExpr(Rs); 1017 } 1018 1019 void visitMulExpr(const SCEVMulExpr *Numerator) { 1020 SmallVector<const SCEV *, 2> Qs; 1021 Type *Ty = Denominator->getType(); 1022 1023 bool FoundDenominatorTerm = false; 1024 for (const SCEV *Op : Numerator->operands()) { 1025 // Bail out if types do not match. 1026 if (Ty != Op->getType()) 1027 return cannotDivide(Numerator); 1028 1029 if (FoundDenominatorTerm) { 1030 Qs.push_back(Op); 1031 continue; 1032 } 1033 1034 // Check whether Denominator divides one of the product operands. 1035 const SCEV *Q, *R; 1036 divide(SE, Op, Denominator, &Q, &R); 1037 if (!R->isZero()) { 1038 Qs.push_back(Op); 1039 continue; 1040 } 1041 1042 // Bail out if types do not match. 1043 if (Ty != Q->getType()) 1044 return cannotDivide(Numerator); 1045 1046 FoundDenominatorTerm = true; 1047 Qs.push_back(Q); 1048 } 1049 1050 if (FoundDenominatorTerm) { 1051 Remainder = Zero; 1052 if (Qs.size() == 1) 1053 Quotient = Qs[0]; 1054 else 1055 Quotient = SE.getMulExpr(Qs); 1056 return; 1057 } 1058 1059 if (!isa<SCEVUnknown>(Denominator)) 1060 return cannotDivide(Numerator); 1061 1062 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1063 ValueToValueMap RewriteMap; 1064 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1065 cast<SCEVConstant>(Zero)->getValue(); 1066 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1067 1068 if (Remainder->isZero()) { 1069 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1070 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1071 cast<SCEVConstant>(One)->getValue(); 1072 Quotient = 1073 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1074 return; 1075 } 1076 1077 // Quotient is (Numerator - Remainder) divided by Denominator. 1078 const SCEV *Q, *R; 1079 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1080 // This SCEV does not seem to simplify: fail the division here. 1081 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1082 return cannotDivide(Numerator); 1083 divide(SE, Diff, Denominator, &Q, &R); 1084 if (R != Zero) 1085 return cannotDivide(Numerator); 1086 Quotient = Q; 1087 } 1088 1089 private: 1090 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1091 const SCEV *Denominator) 1092 : SE(S), Denominator(Denominator) { 1093 Zero = SE.getZero(Denominator->getType()); 1094 One = SE.getOne(Denominator->getType()); 1095 1096 // We generally do not know how to divide Expr by Denominator. We 1097 // initialize the division to a "cannot divide" state to simplify the rest 1098 // of the code. 1099 cannotDivide(Numerator); 1100 } 1101 1102 // Convenience function for giving up on the division. We set the quotient to 1103 // be equal to zero and the remainder to be equal to the numerator. 1104 void cannotDivide(const SCEV *Numerator) { 1105 Quotient = Zero; 1106 Remainder = Numerator; 1107 } 1108 1109 ScalarEvolution &SE; 1110 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1111 }; 1112 1113 } // end anonymous namespace 1114 1115 //===----------------------------------------------------------------------===// 1116 // Simple SCEV method implementations 1117 //===----------------------------------------------------------------------===// 1118 1119 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1120 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1121 ScalarEvolution &SE, 1122 Type *ResultTy) { 1123 // Handle the simplest case efficiently. 1124 if (K == 1) 1125 return SE.getTruncateOrZeroExtend(It, ResultTy); 1126 1127 // We are using the following formula for BC(It, K): 1128 // 1129 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1130 // 1131 // Suppose, W is the bitwidth of the return value. We must be prepared for 1132 // overflow. Hence, we must assure that the result of our computation is 1133 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1134 // safe in modular arithmetic. 1135 // 1136 // However, this code doesn't use exactly that formula; the formula it uses 1137 // is something like the following, where T is the number of factors of 2 in 1138 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1139 // exponentiation: 1140 // 1141 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1142 // 1143 // This formula is trivially equivalent to the previous formula. However, 1144 // this formula can be implemented much more efficiently. The trick is that 1145 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1146 // arithmetic. To do exact division in modular arithmetic, all we have 1147 // to do is multiply by the inverse. Therefore, this step can be done at 1148 // width W. 1149 // 1150 // The next issue is how to safely do the division by 2^T. The way this 1151 // is done is by doing the multiplication step at a width of at least W + T 1152 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1153 // when we perform the division by 2^T (which is equivalent to a right shift 1154 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1155 // truncated out after the division by 2^T. 1156 // 1157 // In comparison to just directly using the first formula, this technique 1158 // is much more efficient; using the first formula requires W * K bits, 1159 // but this formula less than W + K bits. Also, the first formula requires 1160 // a division step, whereas this formula only requires multiplies and shifts. 1161 // 1162 // It doesn't matter whether the subtraction step is done in the calculation 1163 // width or the input iteration count's width; if the subtraction overflows, 1164 // the result must be zero anyway. We prefer here to do it in the width of 1165 // the induction variable because it helps a lot for certain cases; CodeGen 1166 // isn't smart enough to ignore the overflow, which leads to much less 1167 // efficient code if the width of the subtraction is wider than the native 1168 // register width. 1169 // 1170 // (It's possible to not widen at all by pulling out factors of 2 before 1171 // the multiplication; for example, K=2 can be calculated as 1172 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1173 // extra arithmetic, so it's not an obvious win, and it gets 1174 // much more complicated for K > 3.) 1175 1176 // Protection from insane SCEVs; this bound is conservative, 1177 // but it probably doesn't matter. 1178 if (K > 1000) 1179 return SE.getCouldNotCompute(); 1180 1181 unsigned W = SE.getTypeSizeInBits(ResultTy); 1182 1183 // Calculate K! / 2^T and T; we divide out the factors of two before 1184 // multiplying for calculating K! / 2^T to avoid overflow. 1185 // Other overflow doesn't matter because we only care about the bottom 1186 // W bits of the result. 1187 APInt OddFactorial(W, 1); 1188 unsigned T = 1; 1189 for (unsigned i = 3; i <= K; ++i) { 1190 APInt Mult(W, i); 1191 unsigned TwoFactors = Mult.countTrailingZeros(); 1192 T += TwoFactors; 1193 Mult.lshrInPlace(TwoFactors); 1194 OddFactorial *= Mult; 1195 } 1196 1197 // We need at least W + T bits for the multiplication step 1198 unsigned CalculationBits = W + T; 1199 1200 // Calculate 2^T, at width T+W. 1201 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1202 1203 // Calculate the multiplicative inverse of K! / 2^T; 1204 // this multiplication factor will perform the exact division by 1205 // K! / 2^T. 1206 APInt Mod = APInt::getSignedMinValue(W+1); 1207 APInt MultiplyFactor = OddFactorial.zext(W+1); 1208 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1209 MultiplyFactor = MultiplyFactor.trunc(W); 1210 1211 // Calculate the product, at width T+W 1212 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1213 CalculationBits); 1214 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1215 for (unsigned i = 1; i != K; ++i) { 1216 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1217 Dividend = SE.getMulExpr(Dividend, 1218 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1219 } 1220 1221 // Divide by 2^T 1222 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1223 1224 // Truncate the result, and divide by K! / 2^T. 1225 1226 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1227 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1228 } 1229 1230 /// Return the value of this chain of recurrences at the specified iteration 1231 /// number. We can evaluate this recurrence by multiplying each element in the 1232 /// chain by the binomial coefficient corresponding to it. In other words, we 1233 /// can evaluate {A,+,B,+,C,+,D} as: 1234 /// 1235 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1236 /// 1237 /// where BC(It, k) stands for binomial coefficient. 1238 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1239 ScalarEvolution &SE) const { 1240 const SCEV *Result = getStart(); 1241 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1242 // The computation is correct in the face of overflow provided that the 1243 // multiplication is performed _after_ the evaluation of the binomial 1244 // coefficient. 1245 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1246 if (isa<SCEVCouldNotCompute>(Coeff)) 1247 return Coeff; 1248 1249 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1250 } 1251 return Result; 1252 } 1253 1254 //===----------------------------------------------------------------------===// 1255 // SCEV Expression folder implementations 1256 //===----------------------------------------------------------------------===// 1257 1258 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1259 unsigned Depth) { 1260 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1261 "This is not a truncating conversion!"); 1262 assert(isSCEVable(Ty) && 1263 "This is not a conversion to a SCEVable type!"); 1264 Ty = getEffectiveSCEVType(Ty); 1265 1266 FoldingSetNodeID ID; 1267 ID.AddInteger(scTruncate); 1268 ID.AddPointer(Op); 1269 ID.AddPointer(Ty); 1270 void *IP = nullptr; 1271 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1272 1273 // Fold if the operand is constant. 1274 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1275 return getConstant( 1276 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1277 1278 // trunc(trunc(x)) --> trunc(x) 1279 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1280 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1281 1282 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1283 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1284 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1285 1286 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1287 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1288 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1289 1290 if (Depth > MaxCastDepth) { 1291 SCEV *S = 1292 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1293 UniqueSCEVs.InsertNode(S, IP); 1294 addToLoopUseLists(S); 1295 return S; 1296 } 1297 1298 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1299 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1300 // if after transforming we have at most one truncate, not counting truncates 1301 // that replace other casts. 1302 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1303 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1304 SmallVector<const SCEV *, 4> Operands; 1305 unsigned numTruncs = 0; 1306 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1307 ++i) { 1308 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1309 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1310 numTruncs++; 1311 Operands.push_back(S); 1312 } 1313 if (numTruncs < 2) { 1314 if (isa<SCEVAddExpr>(Op)) 1315 return getAddExpr(Operands); 1316 else if (isa<SCEVMulExpr>(Op)) 1317 return getMulExpr(Operands); 1318 else 1319 llvm_unreachable("Unexpected SCEV type for Op."); 1320 } 1321 // Although we checked in the beginning that ID is not in the cache, it is 1322 // possible that during recursion and different modification ID was inserted 1323 // into the cache. So if we find it, just return it. 1324 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1325 return S; 1326 } 1327 1328 // If the input value is a chrec scev, truncate the chrec's operands. 1329 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1330 SmallVector<const SCEV *, 4> Operands; 1331 for (const SCEV *Op : AddRec->operands()) 1332 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1333 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1334 } 1335 1336 // The cast wasn't folded; create an explicit cast node. We can reuse 1337 // the existing insert position since if we get here, we won't have 1338 // made any changes which would invalidate it. 1339 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1340 Op, Ty); 1341 UniqueSCEVs.InsertNode(S, IP); 1342 addToLoopUseLists(S); 1343 return S; 1344 } 1345 1346 // Get the limit of a recurrence such that incrementing by Step cannot cause 1347 // signed overflow as long as the value of the recurrence within the 1348 // loop does not exceed this limit before incrementing. 1349 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1350 ICmpInst::Predicate *Pred, 1351 ScalarEvolution *SE) { 1352 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1353 if (SE->isKnownPositive(Step)) { 1354 *Pred = ICmpInst::ICMP_SLT; 1355 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1356 SE->getSignedRangeMax(Step)); 1357 } 1358 if (SE->isKnownNegative(Step)) { 1359 *Pred = ICmpInst::ICMP_SGT; 1360 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1361 SE->getSignedRangeMin(Step)); 1362 } 1363 return nullptr; 1364 } 1365 1366 // Get the limit of a recurrence such that incrementing by Step cannot cause 1367 // unsigned overflow as long as the value of the recurrence within the loop does 1368 // not exceed this limit before incrementing. 1369 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1370 ICmpInst::Predicate *Pred, 1371 ScalarEvolution *SE) { 1372 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1373 *Pred = ICmpInst::ICMP_ULT; 1374 1375 return SE->getConstant(APInt::getMinValue(BitWidth) - 1376 SE->getUnsignedRangeMax(Step)); 1377 } 1378 1379 namespace { 1380 1381 struct ExtendOpTraitsBase { 1382 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1383 unsigned); 1384 }; 1385 1386 // Used to make code generic over signed and unsigned overflow. 1387 template <typename ExtendOp> struct ExtendOpTraits { 1388 // Members present: 1389 // 1390 // static const SCEV::NoWrapFlags WrapType; 1391 // 1392 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1393 // 1394 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1395 // ICmpInst::Predicate *Pred, 1396 // ScalarEvolution *SE); 1397 }; 1398 1399 template <> 1400 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1401 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1402 1403 static const GetExtendExprTy GetExtendExpr; 1404 1405 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1406 ICmpInst::Predicate *Pred, 1407 ScalarEvolution *SE) { 1408 return getSignedOverflowLimitForStep(Step, Pred, SE); 1409 } 1410 }; 1411 1412 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1413 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1414 1415 template <> 1416 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1417 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1418 1419 static const GetExtendExprTy GetExtendExpr; 1420 1421 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1422 ICmpInst::Predicate *Pred, 1423 ScalarEvolution *SE) { 1424 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1425 } 1426 }; 1427 1428 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1429 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1430 1431 } // end anonymous namespace 1432 1433 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1434 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1435 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1436 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1437 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1438 // expression "Step + sext/zext(PreIncAR)" is congruent with 1439 // "sext/zext(PostIncAR)" 1440 template <typename ExtendOpTy> 1441 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1442 ScalarEvolution *SE, unsigned Depth) { 1443 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1444 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1445 1446 const Loop *L = AR->getLoop(); 1447 const SCEV *Start = AR->getStart(); 1448 const SCEV *Step = AR->getStepRecurrence(*SE); 1449 1450 // Check for a simple looking step prior to loop entry. 1451 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1452 if (!SA) 1453 return nullptr; 1454 1455 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1456 // subtraction is expensive. For this purpose, perform a quick and dirty 1457 // difference, by checking for Step in the operand list. 1458 SmallVector<const SCEV *, 4> DiffOps; 1459 for (const SCEV *Op : SA->operands()) 1460 if (Op != Step) 1461 DiffOps.push_back(Op); 1462 1463 if (DiffOps.size() == SA->getNumOperands()) 1464 return nullptr; 1465 1466 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1467 // `Step`: 1468 1469 // 1. NSW/NUW flags on the step increment. 1470 auto PreStartFlags = 1471 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1472 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1473 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1474 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1475 1476 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1477 // "S+X does not sign/unsign-overflow". 1478 // 1479 1480 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1481 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1482 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1483 return PreStart; 1484 1485 // 2. Direct overflow check on the step operation's expression. 1486 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1487 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1488 const SCEV *OperandExtendedStart = 1489 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1490 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1491 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1492 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1493 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1494 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1495 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1496 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1497 } 1498 return PreStart; 1499 } 1500 1501 // 3. Loop precondition. 1502 ICmpInst::Predicate Pred; 1503 const SCEV *OverflowLimit = 1504 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1505 1506 if (OverflowLimit && 1507 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1508 return PreStart; 1509 1510 return nullptr; 1511 } 1512 1513 // Get the normalized zero or sign extended expression for this AddRec's Start. 1514 template <typename ExtendOpTy> 1515 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1516 ScalarEvolution *SE, 1517 unsigned Depth) { 1518 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1519 1520 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1521 if (!PreStart) 1522 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1523 1524 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1525 Depth), 1526 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1527 } 1528 1529 // Try to prove away overflow by looking at "nearby" add recurrences. A 1530 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1531 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1532 // 1533 // Formally: 1534 // 1535 // {S,+,X} == {S-T,+,X} + T 1536 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1537 // 1538 // If ({S-T,+,X} + T) does not overflow ... (1) 1539 // 1540 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1541 // 1542 // If {S-T,+,X} does not overflow ... (2) 1543 // 1544 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1545 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1546 // 1547 // If (S-T)+T does not overflow ... (3) 1548 // 1549 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1550 // == {Ext(S),+,Ext(X)} == LHS 1551 // 1552 // Thus, if (1), (2) and (3) are true for some T, then 1553 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1554 // 1555 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1556 // does not overflow" restricted to the 0th iteration. Therefore we only need 1557 // to check for (1) and (2). 1558 // 1559 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1560 // is `Delta` (defined below). 1561 template <typename ExtendOpTy> 1562 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1563 const SCEV *Step, 1564 const Loop *L) { 1565 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1566 1567 // We restrict `Start` to a constant to prevent SCEV from spending too much 1568 // time here. It is correct (but more expensive) to continue with a 1569 // non-constant `Start` and do a general SCEV subtraction to compute 1570 // `PreStart` below. 1571 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1572 if (!StartC) 1573 return false; 1574 1575 APInt StartAI = StartC->getAPInt(); 1576 1577 for (unsigned Delta : {-2, -1, 1, 2}) { 1578 const SCEV *PreStart = getConstant(StartAI - Delta); 1579 1580 FoldingSetNodeID ID; 1581 ID.AddInteger(scAddRecExpr); 1582 ID.AddPointer(PreStart); 1583 ID.AddPointer(Step); 1584 ID.AddPointer(L); 1585 void *IP = nullptr; 1586 const auto *PreAR = 1587 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1588 1589 // Give up if we don't already have the add recurrence we need because 1590 // actually constructing an add recurrence is relatively expensive. 1591 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1592 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1593 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1594 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1595 DeltaS, &Pred, this); 1596 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1597 return true; 1598 } 1599 } 1600 1601 return false; 1602 } 1603 1604 // Finds an integer D for an expression (C + x + y + ...) such that the top 1605 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1606 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1607 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1608 // the (C + x + y + ...) expression is \p WholeAddExpr. 1609 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1610 const SCEVConstant *ConstantTerm, 1611 const SCEVAddExpr *WholeAddExpr) { 1612 const APInt C = ConstantTerm->getAPInt(); 1613 const unsigned BitWidth = C.getBitWidth(); 1614 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1615 uint32_t TZ = BitWidth; 1616 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1617 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1618 if (TZ) { 1619 // Set D to be as many least significant bits of C as possible while still 1620 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1621 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1622 } 1623 return APInt(BitWidth, 0); 1624 } 1625 1626 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1627 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1628 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1629 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1630 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1631 const APInt &ConstantStart, 1632 const SCEV *Step) { 1633 const unsigned BitWidth = ConstantStart.getBitWidth(); 1634 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1635 if (TZ) 1636 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1637 : ConstantStart; 1638 return APInt(BitWidth, 0); 1639 } 1640 1641 const SCEV * 1642 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1643 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1644 "This is not an extending conversion!"); 1645 assert(isSCEVable(Ty) && 1646 "This is not a conversion to a SCEVable type!"); 1647 Ty = getEffectiveSCEVType(Ty); 1648 1649 // Fold if the operand is constant. 1650 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1651 return getConstant( 1652 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1653 1654 // zext(zext(x)) --> zext(x) 1655 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1656 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1657 1658 // Before doing any expensive analysis, check to see if we've already 1659 // computed a SCEV for this Op and Ty. 1660 FoldingSetNodeID ID; 1661 ID.AddInteger(scZeroExtend); 1662 ID.AddPointer(Op); 1663 ID.AddPointer(Ty); 1664 void *IP = nullptr; 1665 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1666 if (Depth > MaxCastDepth) { 1667 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1668 Op, Ty); 1669 UniqueSCEVs.InsertNode(S, IP); 1670 addToLoopUseLists(S); 1671 return S; 1672 } 1673 1674 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1675 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1676 // It's possible the bits taken off by the truncate were all zero bits. If 1677 // so, we should be able to simplify this further. 1678 const SCEV *X = ST->getOperand(); 1679 ConstantRange CR = getUnsignedRange(X); 1680 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1681 unsigned NewBits = getTypeSizeInBits(Ty); 1682 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1683 CR.zextOrTrunc(NewBits))) 1684 return getTruncateOrZeroExtend(X, Ty, Depth); 1685 } 1686 1687 // If the input value is a chrec scev, and we can prove that the value 1688 // did not overflow the old, smaller, value, we can zero extend all of the 1689 // operands (often constants). This allows analysis of something like 1690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1691 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1692 if (AR->isAffine()) { 1693 const SCEV *Start = AR->getStart(); 1694 const SCEV *Step = AR->getStepRecurrence(*this); 1695 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1696 const Loop *L = AR->getLoop(); 1697 1698 if (!AR->hasNoUnsignedWrap()) { 1699 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1700 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1701 } 1702 1703 // If we have special knowledge that this addrec won't overflow, 1704 // we don't need to do any further analysis. 1705 if (AR->hasNoUnsignedWrap()) 1706 return getAddRecExpr( 1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1708 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1709 1710 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1711 // Note that this serves two purposes: It filters out loops that are 1712 // simply not analyzable, and it covers the case where this code is 1713 // being called from within backedge-taken count analysis, such that 1714 // attempting to ask for the backedge-taken count would likely result 1715 // in infinite recursion. In the later case, the analysis code will 1716 // cope with a conservative value, and it will take care to purge 1717 // that value once it has finished. 1718 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1719 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1720 // Manually compute the final value for AR, checking for 1721 // overflow. 1722 1723 // Check whether the backedge-taken count can be losslessly casted to 1724 // the addrec's type. The count is always unsigned. 1725 const SCEV *CastedMaxBECount = 1726 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1727 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1728 CastedMaxBECount, MaxBECount->getType(), Depth); 1729 if (MaxBECount == RecastedMaxBECount) { 1730 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1731 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1732 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1733 SCEV::FlagAnyWrap, Depth + 1); 1734 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1735 SCEV::FlagAnyWrap, 1736 Depth + 1), 1737 WideTy, Depth + 1); 1738 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1739 const SCEV *WideMaxBECount = 1740 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1741 const SCEV *OperandExtendedAdd = 1742 getAddExpr(WideStart, 1743 getMulExpr(WideMaxBECount, 1744 getZeroExtendExpr(Step, WideTy, Depth + 1), 1745 SCEV::FlagAnyWrap, Depth + 1), 1746 SCEV::FlagAnyWrap, Depth + 1); 1747 if (ZAdd == OperandExtendedAdd) { 1748 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1749 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1750 // Return the expression with the addrec on the outside. 1751 return getAddRecExpr( 1752 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1753 Depth + 1), 1754 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1755 AR->getNoWrapFlags()); 1756 } 1757 // Similar to above, only this time treat the step value as signed. 1758 // This covers loops that count down. 1759 OperandExtendedAdd = 1760 getAddExpr(WideStart, 1761 getMulExpr(WideMaxBECount, 1762 getSignExtendExpr(Step, WideTy, Depth + 1), 1763 SCEV::FlagAnyWrap, Depth + 1), 1764 SCEV::FlagAnyWrap, Depth + 1); 1765 if (ZAdd == OperandExtendedAdd) { 1766 // Cache knowledge of AR NW, which is propagated to this AddRec. 1767 // Negative step causes unsigned wrap, but it still can't self-wrap. 1768 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1769 // Return the expression with the addrec on the outside. 1770 return getAddRecExpr( 1771 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1772 Depth + 1), 1773 getSignExtendExpr(Step, Ty, Depth + 1), L, 1774 AR->getNoWrapFlags()); 1775 } 1776 } 1777 } 1778 1779 // Normally, in the cases we can prove no-overflow via a 1780 // backedge guarding condition, we can also compute a backedge 1781 // taken count for the loop. The exceptions are assumptions and 1782 // guards present in the loop -- SCEV is not great at exploiting 1783 // these to compute max backedge taken counts, but can still use 1784 // these to prove lack of overflow. Use this fact to avoid 1785 // doing extra work that may not pay off. 1786 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1787 !AC.assumptions().empty()) { 1788 // If the backedge is guarded by a comparison with the pre-inc 1789 // value the addrec is safe. Also, if the entry is guarded by 1790 // a comparison with the start value and the backedge is 1791 // guarded by a comparison with the post-inc value, the addrec 1792 // is safe. 1793 if (isKnownPositive(Step)) { 1794 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1795 getUnsignedRangeMax(Step)); 1796 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1797 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1798 // Cache knowledge of AR NUW, which is propagated to this 1799 // AddRec. 1800 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1801 // Return the expression with the addrec on the outside. 1802 return getAddRecExpr( 1803 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1804 Depth + 1), 1805 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1806 AR->getNoWrapFlags()); 1807 } 1808 } else if (isKnownNegative(Step)) { 1809 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1810 getSignedRangeMin(Step)); 1811 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1812 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1813 // Cache knowledge of AR NW, which is propagated to this 1814 // AddRec. Negative step causes unsigned wrap, but it 1815 // still can't self-wrap. 1816 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1817 // Return the expression with the addrec on the outside. 1818 return getAddRecExpr( 1819 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1820 Depth + 1), 1821 getSignExtendExpr(Step, Ty, Depth + 1), L, 1822 AR->getNoWrapFlags()); 1823 } 1824 } 1825 } 1826 1827 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1828 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1829 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1830 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1831 const APInt &C = SC->getAPInt(); 1832 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1833 if (D != 0) { 1834 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1835 const SCEV *SResidual = 1836 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1837 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1838 return getAddExpr(SZExtD, SZExtR, 1839 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1840 Depth + 1); 1841 } 1842 } 1843 1844 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1845 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1846 return getAddRecExpr( 1847 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1848 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1849 } 1850 } 1851 1852 // zext(A % B) --> zext(A) % zext(B) 1853 { 1854 const SCEV *LHS; 1855 const SCEV *RHS; 1856 if (matchURem(Op, LHS, RHS)) 1857 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1858 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1859 } 1860 1861 // zext(A / B) --> zext(A) / zext(B). 1862 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1863 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1864 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1865 1866 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1867 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1868 if (SA->hasNoUnsignedWrap()) { 1869 // If the addition does not unsign overflow then we can, by definition, 1870 // commute the zero extension with the addition operation. 1871 SmallVector<const SCEV *, 4> Ops; 1872 for (const auto *Op : SA->operands()) 1873 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1874 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1875 } 1876 1877 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1878 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1879 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1880 // 1881 // Often address arithmetics contain expressions like 1882 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1883 // This transformation is useful while proving that such expressions are 1884 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1885 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1886 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1887 if (D != 0) { 1888 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1889 const SCEV *SResidual = 1890 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1891 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1892 return getAddExpr(SZExtD, SZExtR, 1893 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1894 Depth + 1); 1895 } 1896 } 1897 } 1898 1899 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1900 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1901 if (SM->hasNoUnsignedWrap()) { 1902 // If the multiply does not unsign overflow then we can, by definition, 1903 // commute the zero extension with the multiply operation. 1904 SmallVector<const SCEV *, 4> Ops; 1905 for (const auto *Op : SM->operands()) 1906 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1907 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1908 } 1909 1910 // zext(2^K * (trunc X to iN)) to iM -> 1911 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1912 // 1913 // Proof: 1914 // 1915 // zext(2^K * (trunc X to iN)) to iM 1916 // = zext((trunc X to iN) << K) to iM 1917 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1918 // (because shl removes the top K bits) 1919 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1920 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1921 // 1922 if (SM->getNumOperands() == 2) 1923 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1924 if (MulLHS->getAPInt().isPowerOf2()) 1925 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1926 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1927 MulLHS->getAPInt().logBase2(); 1928 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1929 return getMulExpr( 1930 getZeroExtendExpr(MulLHS, Ty), 1931 getZeroExtendExpr( 1932 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1933 SCEV::FlagNUW, Depth + 1); 1934 } 1935 } 1936 1937 // The cast wasn't folded; create an explicit cast node. 1938 // Recompute the insert position, as it may have been invalidated. 1939 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1940 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1941 Op, Ty); 1942 UniqueSCEVs.InsertNode(S, IP); 1943 addToLoopUseLists(S); 1944 return S; 1945 } 1946 1947 const SCEV * 1948 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1949 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1950 "This is not an extending conversion!"); 1951 assert(isSCEVable(Ty) && 1952 "This is not a conversion to a SCEVable type!"); 1953 Ty = getEffectiveSCEVType(Ty); 1954 1955 // Fold if the operand is constant. 1956 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1957 return getConstant( 1958 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1959 1960 // sext(sext(x)) --> sext(x) 1961 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1962 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1963 1964 // sext(zext(x)) --> zext(x) 1965 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1966 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1967 1968 // Before doing any expensive analysis, check to see if we've already 1969 // computed a SCEV for this Op and Ty. 1970 FoldingSetNodeID ID; 1971 ID.AddInteger(scSignExtend); 1972 ID.AddPointer(Op); 1973 ID.AddPointer(Ty); 1974 void *IP = nullptr; 1975 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1976 // Limit recursion depth. 1977 if (Depth > MaxCastDepth) { 1978 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1979 Op, Ty); 1980 UniqueSCEVs.InsertNode(S, IP); 1981 addToLoopUseLists(S); 1982 return S; 1983 } 1984 1985 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1986 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1987 // It's possible the bits taken off by the truncate were all sign bits. If 1988 // so, we should be able to simplify this further. 1989 const SCEV *X = ST->getOperand(); 1990 ConstantRange CR = getSignedRange(X); 1991 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1992 unsigned NewBits = getTypeSizeInBits(Ty); 1993 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1994 CR.sextOrTrunc(NewBits))) 1995 return getTruncateOrSignExtend(X, Ty, Depth); 1996 } 1997 1998 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1999 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 2000 if (SA->hasNoSignedWrap()) { 2001 // If the addition does not sign overflow then we can, by definition, 2002 // commute the sign extension with the addition operation. 2003 SmallVector<const SCEV *, 4> Ops; 2004 for (const auto *Op : SA->operands()) 2005 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2006 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2007 } 2008 2009 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2010 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2011 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2012 // 2013 // For instance, this will bring two seemingly different expressions: 2014 // 1 + sext(5 + 20 * %x + 24 * %y) and 2015 // sext(6 + 20 * %x + 24 * %y) 2016 // to the same form: 2017 // 2 + sext(4 + 20 * %x + 24 * %y) 2018 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2019 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2020 if (D != 0) { 2021 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2022 const SCEV *SResidual = 2023 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2024 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2025 return getAddExpr(SSExtD, SSExtR, 2026 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2027 Depth + 1); 2028 } 2029 } 2030 } 2031 // If the input value is a chrec scev, and we can prove that the value 2032 // did not overflow the old, smaller, value, we can sign extend all of the 2033 // operands (often constants). This allows analysis of something like 2034 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2035 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2036 if (AR->isAffine()) { 2037 const SCEV *Start = AR->getStart(); 2038 const SCEV *Step = AR->getStepRecurrence(*this); 2039 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2040 const Loop *L = AR->getLoop(); 2041 2042 if (!AR->hasNoSignedWrap()) { 2043 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2044 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2045 } 2046 2047 // If we have special knowledge that this addrec won't overflow, 2048 // we don't need to do any further analysis. 2049 if (AR->hasNoSignedWrap()) 2050 return getAddRecExpr( 2051 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2052 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2053 2054 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2055 // Note that this serves two purposes: It filters out loops that are 2056 // simply not analyzable, and it covers the case where this code is 2057 // being called from within backedge-taken count analysis, such that 2058 // attempting to ask for the backedge-taken count would likely result 2059 // in infinite recursion. In the later case, the analysis code will 2060 // cope with a conservative value, and it will take care to purge 2061 // that value once it has finished. 2062 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2063 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2064 // Manually compute the final value for AR, checking for 2065 // overflow. 2066 2067 // Check whether the backedge-taken count can be losslessly casted to 2068 // the addrec's type. The count is always unsigned. 2069 const SCEV *CastedMaxBECount = 2070 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2071 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2072 CastedMaxBECount, MaxBECount->getType(), Depth); 2073 if (MaxBECount == RecastedMaxBECount) { 2074 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2075 // Check whether Start+Step*MaxBECount has no signed overflow. 2076 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2077 SCEV::FlagAnyWrap, Depth + 1); 2078 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2079 SCEV::FlagAnyWrap, 2080 Depth + 1), 2081 WideTy, Depth + 1); 2082 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2083 const SCEV *WideMaxBECount = 2084 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2085 const SCEV *OperandExtendedAdd = 2086 getAddExpr(WideStart, 2087 getMulExpr(WideMaxBECount, 2088 getSignExtendExpr(Step, WideTy, Depth + 1), 2089 SCEV::FlagAnyWrap, Depth + 1), 2090 SCEV::FlagAnyWrap, Depth + 1); 2091 if (SAdd == OperandExtendedAdd) { 2092 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2093 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2094 // Return the expression with the addrec on the outside. 2095 return getAddRecExpr( 2096 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2097 Depth + 1), 2098 getSignExtendExpr(Step, Ty, Depth + 1), L, 2099 AR->getNoWrapFlags()); 2100 } 2101 // Similar to above, only this time treat the step value as unsigned. 2102 // This covers loops that count up with an unsigned step. 2103 OperandExtendedAdd = 2104 getAddExpr(WideStart, 2105 getMulExpr(WideMaxBECount, 2106 getZeroExtendExpr(Step, WideTy, Depth + 1), 2107 SCEV::FlagAnyWrap, Depth + 1), 2108 SCEV::FlagAnyWrap, Depth + 1); 2109 if (SAdd == OperandExtendedAdd) { 2110 // If AR wraps around then 2111 // 2112 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2113 // => SAdd != OperandExtendedAdd 2114 // 2115 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2116 // (SAdd == OperandExtendedAdd => AR is NW) 2117 2118 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2119 2120 // Return the expression with the addrec on the outside. 2121 return getAddRecExpr( 2122 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2123 Depth + 1), 2124 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2125 AR->getNoWrapFlags()); 2126 } 2127 } 2128 } 2129 2130 // Normally, in the cases we can prove no-overflow via a 2131 // backedge guarding condition, we can also compute a backedge 2132 // taken count for the loop. The exceptions are assumptions and 2133 // guards present in the loop -- SCEV is not great at exploiting 2134 // these to compute max backedge taken counts, but can still use 2135 // these to prove lack of overflow. Use this fact to avoid 2136 // doing extra work that may not pay off. 2137 2138 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2139 !AC.assumptions().empty()) { 2140 // If the backedge is guarded by a comparison with the pre-inc 2141 // value the addrec is safe. Also, if the entry is guarded by 2142 // a comparison with the start value and the backedge is 2143 // guarded by a comparison with the post-inc value, the addrec 2144 // is safe. 2145 ICmpInst::Predicate Pred; 2146 const SCEV *OverflowLimit = 2147 getSignedOverflowLimitForStep(Step, &Pred, this); 2148 if (OverflowLimit && 2149 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2150 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2151 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2152 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2153 return getAddRecExpr( 2154 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2155 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2156 } 2157 } 2158 2159 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2160 // if D + (C - D + Step * n) could be proven to not signed wrap 2161 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2162 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2163 const APInt &C = SC->getAPInt(); 2164 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2165 if (D != 0) { 2166 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2167 const SCEV *SResidual = 2168 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2169 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2170 return getAddExpr(SSExtD, SSExtR, 2171 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2172 Depth + 1); 2173 } 2174 } 2175 2176 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2177 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2178 return getAddRecExpr( 2179 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2180 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2181 } 2182 } 2183 2184 // If the input value is provably positive and we could not simplify 2185 // away the sext build a zext instead. 2186 if (isKnownNonNegative(Op)) 2187 return getZeroExtendExpr(Op, Ty, Depth + 1); 2188 2189 // The cast wasn't folded; create an explicit cast node. 2190 // Recompute the insert position, as it may have been invalidated. 2191 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2192 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2193 Op, Ty); 2194 UniqueSCEVs.InsertNode(S, IP); 2195 addToLoopUseLists(S); 2196 return S; 2197 } 2198 2199 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2200 /// unspecified bits out to the given type. 2201 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2202 Type *Ty) { 2203 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2204 "This is not an extending conversion!"); 2205 assert(isSCEVable(Ty) && 2206 "This is not a conversion to a SCEVable type!"); 2207 Ty = getEffectiveSCEVType(Ty); 2208 2209 // Sign-extend negative constants. 2210 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2211 if (SC->getAPInt().isNegative()) 2212 return getSignExtendExpr(Op, Ty); 2213 2214 // Peel off a truncate cast. 2215 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2216 const SCEV *NewOp = T->getOperand(); 2217 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2218 return getAnyExtendExpr(NewOp, Ty); 2219 return getTruncateOrNoop(NewOp, Ty); 2220 } 2221 2222 // Next try a zext cast. If the cast is folded, use it. 2223 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2224 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2225 return ZExt; 2226 2227 // Next try a sext cast. If the cast is folded, use it. 2228 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2229 if (!isa<SCEVSignExtendExpr>(SExt)) 2230 return SExt; 2231 2232 // Force the cast to be folded into the operands of an addrec. 2233 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2234 SmallVector<const SCEV *, 4> Ops; 2235 for (const SCEV *Op : AR->operands()) 2236 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2237 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2238 } 2239 2240 // If the expression is obviously signed, use the sext cast value. 2241 if (isa<SCEVSMaxExpr>(Op)) 2242 return SExt; 2243 2244 // Absent any other information, use the zext cast value. 2245 return ZExt; 2246 } 2247 2248 /// Process the given Ops list, which is a list of operands to be added under 2249 /// the given scale, update the given map. This is a helper function for 2250 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2251 /// that would form an add expression like this: 2252 /// 2253 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2254 /// 2255 /// where A and B are constants, update the map with these values: 2256 /// 2257 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2258 /// 2259 /// and add 13 + A*B*29 to AccumulatedConstant. 2260 /// This will allow getAddRecExpr to produce this: 2261 /// 2262 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2263 /// 2264 /// This form often exposes folding opportunities that are hidden in 2265 /// the original operand list. 2266 /// 2267 /// Return true iff it appears that any interesting folding opportunities 2268 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2269 /// the common case where no interesting opportunities are present, and 2270 /// is also used as a check to avoid infinite recursion. 2271 static bool 2272 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2273 SmallVectorImpl<const SCEV *> &NewOps, 2274 APInt &AccumulatedConstant, 2275 const SCEV *const *Ops, size_t NumOperands, 2276 const APInt &Scale, 2277 ScalarEvolution &SE) { 2278 bool Interesting = false; 2279 2280 // Iterate over the add operands. They are sorted, with constants first. 2281 unsigned i = 0; 2282 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2283 ++i; 2284 // Pull a buried constant out to the outside. 2285 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2286 Interesting = true; 2287 AccumulatedConstant += Scale * C->getAPInt(); 2288 } 2289 2290 // Next comes everything else. We're especially interested in multiplies 2291 // here, but they're in the middle, so just visit the rest with one loop. 2292 for (; i != NumOperands; ++i) { 2293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2294 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2295 APInt NewScale = 2296 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2297 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2298 // A multiplication of a constant with another add; recurse. 2299 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2300 Interesting |= 2301 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2302 Add->op_begin(), Add->getNumOperands(), 2303 NewScale, SE); 2304 } else { 2305 // A multiplication of a constant with some other value. Update 2306 // the map. 2307 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2308 const SCEV *Key = SE.getMulExpr(MulOps); 2309 auto Pair = M.insert({Key, NewScale}); 2310 if (Pair.second) { 2311 NewOps.push_back(Pair.first->first); 2312 } else { 2313 Pair.first->second += NewScale; 2314 // The map already had an entry for this value, which may indicate 2315 // a folding opportunity. 2316 Interesting = true; 2317 } 2318 } 2319 } else { 2320 // An ordinary operand. Update the map. 2321 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2322 M.insert({Ops[i], Scale}); 2323 if (Pair.second) { 2324 NewOps.push_back(Pair.first->first); 2325 } else { 2326 Pair.first->second += Scale; 2327 // The map already had an entry for this value, which may indicate 2328 // a folding opportunity. 2329 Interesting = true; 2330 } 2331 } 2332 } 2333 2334 return Interesting; 2335 } 2336 2337 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2338 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2339 // can't-overflow flags for the operation if possible. 2340 static SCEV::NoWrapFlags 2341 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2342 const ArrayRef<const SCEV *> Ops, 2343 SCEV::NoWrapFlags Flags) { 2344 using namespace std::placeholders; 2345 2346 using OBO = OverflowingBinaryOperator; 2347 2348 bool CanAnalyze = 2349 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2350 (void)CanAnalyze; 2351 assert(CanAnalyze && "don't call from other places!"); 2352 2353 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2354 SCEV::NoWrapFlags SignOrUnsignWrap = 2355 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2356 2357 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2358 auto IsKnownNonNegative = [&](const SCEV *S) { 2359 return SE->isKnownNonNegative(S); 2360 }; 2361 2362 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2363 Flags = 2364 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2365 2366 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2367 2368 if (SignOrUnsignWrap != SignOrUnsignMask && 2369 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2370 isa<SCEVConstant>(Ops[0])) { 2371 2372 auto Opcode = [&] { 2373 switch (Type) { 2374 case scAddExpr: 2375 return Instruction::Add; 2376 case scMulExpr: 2377 return Instruction::Mul; 2378 default: 2379 llvm_unreachable("Unexpected SCEV op."); 2380 } 2381 }(); 2382 2383 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2384 2385 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2386 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2387 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2388 Opcode, C, OBO::NoSignedWrap); 2389 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2390 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2391 } 2392 2393 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2394 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2395 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2396 Opcode, C, OBO::NoUnsignedWrap); 2397 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2398 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2399 } 2400 } 2401 2402 return Flags; 2403 } 2404 2405 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2406 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2407 } 2408 2409 /// Get a canonical add expression, or something simpler if possible. 2410 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2411 SCEV::NoWrapFlags Flags, 2412 unsigned Depth) { 2413 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2414 "only nuw or nsw allowed"); 2415 assert(!Ops.empty() && "Cannot get empty add!"); 2416 if (Ops.size() == 1) return Ops[0]; 2417 #ifndef NDEBUG 2418 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2419 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2420 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2421 "SCEVAddExpr operand types don't match!"); 2422 #endif 2423 2424 // Sort by complexity, this groups all similar expression types together. 2425 GroupByComplexity(Ops, &LI, DT); 2426 2427 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2428 2429 // If there are any constants, fold them together. 2430 unsigned Idx = 0; 2431 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2432 ++Idx; 2433 assert(Idx < Ops.size()); 2434 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2435 // We found two constants, fold them together! 2436 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2437 if (Ops.size() == 2) return Ops[0]; 2438 Ops.erase(Ops.begin()+1); // Erase the folded element 2439 LHSC = cast<SCEVConstant>(Ops[0]); 2440 } 2441 2442 // If we are left with a constant zero being added, strip it off. 2443 if (LHSC->getValue()->isZero()) { 2444 Ops.erase(Ops.begin()); 2445 --Idx; 2446 } 2447 2448 if (Ops.size() == 1) return Ops[0]; 2449 } 2450 2451 // Limit recursion calls depth. 2452 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2453 return getOrCreateAddExpr(Ops, Flags); 2454 2455 // Okay, check to see if the same value occurs in the operand list more than 2456 // once. If so, merge them together into an multiply expression. Since we 2457 // sorted the list, these values are required to be adjacent. 2458 Type *Ty = Ops[0]->getType(); 2459 bool FoundMatch = false; 2460 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2461 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2462 // Scan ahead to count how many equal operands there are. 2463 unsigned Count = 2; 2464 while (i+Count != e && Ops[i+Count] == Ops[i]) 2465 ++Count; 2466 // Merge the values into a multiply. 2467 const SCEV *Scale = getConstant(Ty, Count); 2468 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2469 if (Ops.size() == Count) 2470 return Mul; 2471 Ops[i] = Mul; 2472 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2473 --i; e -= Count - 1; 2474 FoundMatch = true; 2475 } 2476 if (FoundMatch) 2477 return getAddExpr(Ops, Flags, Depth + 1); 2478 2479 // Check for truncates. If all the operands are truncated from the same 2480 // type, see if factoring out the truncate would permit the result to be 2481 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2482 // if the contents of the resulting outer trunc fold to something simple. 2483 auto FindTruncSrcType = [&]() -> Type * { 2484 // We're ultimately looking to fold an addrec of truncs and muls of only 2485 // constants and truncs, so if we find any other types of SCEV 2486 // as operands of the addrec then we bail and return nullptr here. 2487 // Otherwise, we return the type of the operand of a trunc that we find. 2488 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2489 return T->getOperand()->getType(); 2490 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2491 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2492 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2493 return T->getOperand()->getType(); 2494 } 2495 return nullptr; 2496 }; 2497 if (auto *SrcType = FindTruncSrcType()) { 2498 SmallVector<const SCEV *, 8> LargeOps; 2499 bool Ok = true; 2500 // Check all the operands to see if they can be represented in the 2501 // source type of the truncate. 2502 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2503 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2504 if (T->getOperand()->getType() != SrcType) { 2505 Ok = false; 2506 break; 2507 } 2508 LargeOps.push_back(T->getOperand()); 2509 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2510 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2511 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2512 SmallVector<const SCEV *, 8> LargeMulOps; 2513 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2514 if (const SCEVTruncateExpr *T = 2515 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2516 if (T->getOperand()->getType() != SrcType) { 2517 Ok = false; 2518 break; 2519 } 2520 LargeMulOps.push_back(T->getOperand()); 2521 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2522 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2523 } else { 2524 Ok = false; 2525 break; 2526 } 2527 } 2528 if (Ok) 2529 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2530 } else { 2531 Ok = false; 2532 break; 2533 } 2534 } 2535 if (Ok) { 2536 // Evaluate the expression in the larger type. 2537 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2538 // If it folds to something simple, use it. Otherwise, don't. 2539 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2540 return getTruncateExpr(Fold, Ty); 2541 } 2542 } 2543 2544 // Skip past any other cast SCEVs. 2545 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2546 ++Idx; 2547 2548 // If there are add operands they would be next. 2549 if (Idx < Ops.size()) { 2550 bool DeletedAdd = false; 2551 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2552 if (Ops.size() > AddOpsInlineThreshold || 2553 Add->getNumOperands() > AddOpsInlineThreshold) 2554 break; 2555 // If we have an add, expand the add operands onto the end of the operands 2556 // list. 2557 Ops.erase(Ops.begin()+Idx); 2558 Ops.append(Add->op_begin(), Add->op_end()); 2559 DeletedAdd = true; 2560 } 2561 2562 // If we deleted at least one add, we added operands to the end of the list, 2563 // and they are not necessarily sorted. Recurse to resort and resimplify 2564 // any operands we just acquired. 2565 if (DeletedAdd) 2566 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2567 } 2568 2569 // Skip over the add expression until we get to a multiply. 2570 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2571 ++Idx; 2572 2573 // Check to see if there are any folding opportunities present with 2574 // operands multiplied by constant values. 2575 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2576 uint64_t BitWidth = getTypeSizeInBits(Ty); 2577 DenseMap<const SCEV *, APInt> M; 2578 SmallVector<const SCEV *, 8> NewOps; 2579 APInt AccumulatedConstant(BitWidth, 0); 2580 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2581 Ops.data(), Ops.size(), 2582 APInt(BitWidth, 1), *this)) { 2583 struct APIntCompare { 2584 bool operator()(const APInt &LHS, const APInt &RHS) const { 2585 return LHS.ult(RHS); 2586 } 2587 }; 2588 2589 // Some interesting folding opportunity is present, so its worthwhile to 2590 // re-generate the operands list. Group the operands by constant scale, 2591 // to avoid multiplying by the same constant scale multiple times. 2592 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2593 for (const SCEV *NewOp : NewOps) 2594 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2595 // Re-generate the operands list. 2596 Ops.clear(); 2597 if (AccumulatedConstant != 0) 2598 Ops.push_back(getConstant(AccumulatedConstant)); 2599 for (auto &MulOp : MulOpLists) 2600 if (MulOp.first != 0) 2601 Ops.push_back(getMulExpr( 2602 getConstant(MulOp.first), 2603 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2604 SCEV::FlagAnyWrap, Depth + 1)); 2605 if (Ops.empty()) 2606 return getZero(Ty); 2607 if (Ops.size() == 1) 2608 return Ops[0]; 2609 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2610 } 2611 } 2612 2613 // If we are adding something to a multiply expression, make sure the 2614 // something is not already an operand of the multiply. If so, merge it into 2615 // the multiply. 2616 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2617 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2618 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2619 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2620 if (isa<SCEVConstant>(MulOpSCEV)) 2621 continue; 2622 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2623 if (MulOpSCEV == Ops[AddOp]) { 2624 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2625 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2626 if (Mul->getNumOperands() != 2) { 2627 // If the multiply has more than two operands, we must get the 2628 // Y*Z term. 2629 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2630 Mul->op_begin()+MulOp); 2631 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2632 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2633 } 2634 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2635 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2636 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2637 SCEV::FlagAnyWrap, Depth + 1); 2638 if (Ops.size() == 2) return OuterMul; 2639 if (AddOp < Idx) { 2640 Ops.erase(Ops.begin()+AddOp); 2641 Ops.erase(Ops.begin()+Idx-1); 2642 } else { 2643 Ops.erase(Ops.begin()+Idx); 2644 Ops.erase(Ops.begin()+AddOp-1); 2645 } 2646 Ops.push_back(OuterMul); 2647 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2648 } 2649 2650 // Check this multiply against other multiplies being added together. 2651 for (unsigned OtherMulIdx = Idx+1; 2652 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2653 ++OtherMulIdx) { 2654 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2655 // If MulOp occurs in OtherMul, we can fold the two multiplies 2656 // together. 2657 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2658 OMulOp != e; ++OMulOp) 2659 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2660 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2661 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2662 if (Mul->getNumOperands() != 2) { 2663 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2664 Mul->op_begin()+MulOp); 2665 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2666 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2667 } 2668 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2669 if (OtherMul->getNumOperands() != 2) { 2670 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2671 OtherMul->op_begin()+OMulOp); 2672 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2673 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2674 } 2675 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2676 const SCEV *InnerMulSum = 2677 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2678 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2679 SCEV::FlagAnyWrap, Depth + 1); 2680 if (Ops.size() == 2) return OuterMul; 2681 Ops.erase(Ops.begin()+Idx); 2682 Ops.erase(Ops.begin()+OtherMulIdx-1); 2683 Ops.push_back(OuterMul); 2684 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2685 } 2686 } 2687 } 2688 } 2689 2690 // If there are any add recurrences in the operands list, see if any other 2691 // added values are loop invariant. If so, we can fold them into the 2692 // recurrence. 2693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2694 ++Idx; 2695 2696 // Scan over all recurrences, trying to fold loop invariants into them. 2697 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2698 // Scan all of the other operands to this add and add them to the vector if 2699 // they are loop invariant w.r.t. the recurrence. 2700 SmallVector<const SCEV *, 8> LIOps; 2701 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2702 const Loop *AddRecLoop = AddRec->getLoop(); 2703 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2704 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2705 LIOps.push_back(Ops[i]); 2706 Ops.erase(Ops.begin()+i); 2707 --i; --e; 2708 } 2709 2710 // If we found some loop invariants, fold them into the recurrence. 2711 if (!LIOps.empty()) { 2712 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2713 LIOps.push_back(AddRec->getStart()); 2714 2715 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2716 AddRec->op_end()); 2717 // This follows from the fact that the no-wrap flags on the outer add 2718 // expression are applicable on the 0th iteration, when the add recurrence 2719 // will be equal to its start value. 2720 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2721 2722 // Build the new addrec. Propagate the NUW and NSW flags if both the 2723 // outer add and the inner addrec are guaranteed to have no overflow. 2724 // Always propagate NW. 2725 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2726 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2727 2728 // If all of the other operands were loop invariant, we are done. 2729 if (Ops.size() == 1) return NewRec; 2730 2731 // Otherwise, add the folded AddRec by the non-invariant parts. 2732 for (unsigned i = 0;; ++i) 2733 if (Ops[i] == AddRec) { 2734 Ops[i] = NewRec; 2735 break; 2736 } 2737 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2738 } 2739 2740 // Okay, if there weren't any loop invariants to be folded, check to see if 2741 // there are multiple AddRec's with the same loop induction variable being 2742 // added together. If so, we can fold them. 2743 for (unsigned OtherIdx = Idx+1; 2744 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2745 ++OtherIdx) { 2746 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2747 // so that the 1st found AddRecExpr is dominated by all others. 2748 assert(DT.dominates( 2749 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2750 AddRec->getLoop()->getHeader()) && 2751 "AddRecExprs are not sorted in reverse dominance order?"); 2752 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2753 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2754 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2755 AddRec->op_end()); 2756 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2757 ++OtherIdx) { 2758 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2759 if (OtherAddRec->getLoop() == AddRecLoop) { 2760 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2761 i != e; ++i) { 2762 if (i >= AddRecOps.size()) { 2763 AddRecOps.append(OtherAddRec->op_begin()+i, 2764 OtherAddRec->op_end()); 2765 break; 2766 } 2767 SmallVector<const SCEV *, 2> TwoOps = { 2768 AddRecOps[i], OtherAddRec->getOperand(i)}; 2769 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2770 } 2771 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2772 } 2773 } 2774 // Step size has changed, so we cannot guarantee no self-wraparound. 2775 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2776 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2777 } 2778 } 2779 2780 // Otherwise couldn't fold anything into this recurrence. Move onto the 2781 // next one. 2782 } 2783 2784 // Okay, it looks like we really DO need an add expr. Check to see if we 2785 // already have one, otherwise create a new one. 2786 return getOrCreateAddExpr(Ops, Flags); 2787 } 2788 2789 const SCEV * 2790 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2791 SCEV::NoWrapFlags Flags) { 2792 FoldingSetNodeID ID; 2793 ID.AddInteger(scAddExpr); 2794 for (const SCEV *Op : Ops) 2795 ID.AddPointer(Op); 2796 void *IP = nullptr; 2797 SCEVAddExpr *S = 2798 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2799 if (!S) { 2800 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2801 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2802 S = new (SCEVAllocator) 2803 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2804 UniqueSCEVs.InsertNode(S, IP); 2805 addToLoopUseLists(S); 2806 } 2807 S->setNoWrapFlags(Flags); 2808 return S; 2809 } 2810 2811 const SCEV * 2812 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2813 const Loop *L, SCEV::NoWrapFlags Flags) { 2814 FoldingSetNodeID ID; 2815 ID.AddInteger(scAddRecExpr); 2816 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2817 ID.AddPointer(Ops[i]); 2818 ID.AddPointer(L); 2819 void *IP = nullptr; 2820 SCEVAddRecExpr *S = 2821 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2822 if (!S) { 2823 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2824 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2825 S = new (SCEVAllocator) 2826 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2827 UniqueSCEVs.InsertNode(S, IP); 2828 addToLoopUseLists(S); 2829 } 2830 S->setNoWrapFlags(Flags); 2831 return S; 2832 } 2833 2834 const SCEV * 2835 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2836 SCEV::NoWrapFlags Flags) { 2837 FoldingSetNodeID ID; 2838 ID.AddInteger(scMulExpr); 2839 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2840 ID.AddPointer(Ops[i]); 2841 void *IP = nullptr; 2842 SCEVMulExpr *S = 2843 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2844 if (!S) { 2845 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2846 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2847 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2848 O, Ops.size()); 2849 UniqueSCEVs.InsertNode(S, IP); 2850 addToLoopUseLists(S); 2851 } 2852 S->setNoWrapFlags(Flags); 2853 return S; 2854 } 2855 2856 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2857 uint64_t k = i*j; 2858 if (j > 1 && k / j != i) Overflow = true; 2859 return k; 2860 } 2861 2862 /// Compute the result of "n choose k", the binomial coefficient. If an 2863 /// intermediate computation overflows, Overflow will be set and the return will 2864 /// be garbage. Overflow is not cleared on absence of overflow. 2865 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2866 // We use the multiplicative formula: 2867 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2868 // At each iteration, we take the n-th term of the numeral and divide by the 2869 // (k-n)th term of the denominator. This division will always produce an 2870 // integral result, and helps reduce the chance of overflow in the 2871 // intermediate computations. However, we can still overflow even when the 2872 // final result would fit. 2873 2874 if (n == 0 || n == k) return 1; 2875 if (k > n) return 0; 2876 2877 if (k > n/2) 2878 k = n-k; 2879 2880 uint64_t r = 1; 2881 for (uint64_t i = 1; i <= k; ++i) { 2882 r = umul_ov(r, n-(i-1), Overflow); 2883 r /= i; 2884 } 2885 return r; 2886 } 2887 2888 /// Determine if any of the operands in this SCEV are a constant or if 2889 /// any of the add or multiply expressions in this SCEV contain a constant. 2890 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2891 struct FindConstantInAddMulChain { 2892 bool FoundConstant = false; 2893 2894 bool follow(const SCEV *S) { 2895 FoundConstant |= isa<SCEVConstant>(S); 2896 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2897 } 2898 2899 bool isDone() const { 2900 return FoundConstant; 2901 } 2902 }; 2903 2904 FindConstantInAddMulChain F; 2905 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2906 ST.visitAll(StartExpr); 2907 return F.FoundConstant; 2908 } 2909 2910 /// Get a canonical multiply expression, or something simpler if possible. 2911 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2912 SCEV::NoWrapFlags Flags, 2913 unsigned Depth) { 2914 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2915 "only nuw or nsw allowed"); 2916 assert(!Ops.empty() && "Cannot get empty mul!"); 2917 if (Ops.size() == 1) return Ops[0]; 2918 #ifndef NDEBUG 2919 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2920 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2921 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2922 "SCEVMulExpr operand types don't match!"); 2923 #endif 2924 2925 // Sort by complexity, this groups all similar expression types together. 2926 GroupByComplexity(Ops, &LI, DT); 2927 2928 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2929 2930 // Limit recursion calls depth. 2931 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2932 return getOrCreateMulExpr(Ops, Flags); 2933 2934 // If there are any constants, fold them together. 2935 unsigned Idx = 0; 2936 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2937 2938 if (Ops.size() == 2) 2939 // C1*(C2+V) -> C1*C2 + C1*V 2940 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2941 // If any of Add's ops are Adds or Muls with a constant, apply this 2942 // transformation as well. 2943 // 2944 // TODO: There are some cases where this transformation is not 2945 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2946 // this transformation should be narrowed down. 2947 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2948 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2949 SCEV::FlagAnyWrap, Depth + 1), 2950 getMulExpr(LHSC, Add->getOperand(1), 2951 SCEV::FlagAnyWrap, Depth + 1), 2952 SCEV::FlagAnyWrap, Depth + 1); 2953 2954 ++Idx; 2955 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2956 // We found two constants, fold them together! 2957 ConstantInt *Fold = 2958 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2959 Ops[0] = getConstant(Fold); 2960 Ops.erase(Ops.begin()+1); // Erase the folded element 2961 if (Ops.size() == 1) return Ops[0]; 2962 LHSC = cast<SCEVConstant>(Ops[0]); 2963 } 2964 2965 // If we are left with a constant one being multiplied, strip it off. 2966 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2967 Ops.erase(Ops.begin()); 2968 --Idx; 2969 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2970 // If we have a multiply of zero, it will always be zero. 2971 return Ops[0]; 2972 } else if (Ops[0]->isAllOnesValue()) { 2973 // If we have a mul by -1 of an add, try distributing the -1 among the 2974 // add operands. 2975 if (Ops.size() == 2) { 2976 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2977 SmallVector<const SCEV *, 4> NewOps; 2978 bool AnyFolded = false; 2979 for (const SCEV *AddOp : Add->operands()) { 2980 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2981 Depth + 1); 2982 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2983 NewOps.push_back(Mul); 2984 } 2985 if (AnyFolded) 2986 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2987 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2988 // Negation preserves a recurrence's no self-wrap property. 2989 SmallVector<const SCEV *, 4> Operands; 2990 for (const SCEV *AddRecOp : AddRec->operands()) 2991 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2992 Depth + 1)); 2993 2994 return getAddRecExpr(Operands, AddRec->getLoop(), 2995 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2996 } 2997 } 2998 } 2999 3000 if (Ops.size() == 1) 3001 return Ops[0]; 3002 } 3003 3004 // Skip over the add expression until we get to a multiply. 3005 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3006 ++Idx; 3007 3008 // If there are mul operands inline them all into this expression. 3009 if (Idx < Ops.size()) { 3010 bool DeletedMul = false; 3011 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3012 if (Ops.size() > MulOpsInlineThreshold) 3013 break; 3014 // If we have an mul, expand the mul operands onto the end of the 3015 // operands list. 3016 Ops.erase(Ops.begin()+Idx); 3017 Ops.append(Mul->op_begin(), Mul->op_end()); 3018 DeletedMul = true; 3019 } 3020 3021 // If we deleted at least one mul, we added operands to the end of the 3022 // list, and they are not necessarily sorted. Recurse to resort and 3023 // resimplify any operands we just acquired. 3024 if (DeletedMul) 3025 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3026 } 3027 3028 // If there are any add recurrences in the operands list, see if any other 3029 // added values are loop invariant. If so, we can fold them into the 3030 // recurrence. 3031 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3032 ++Idx; 3033 3034 // Scan over all recurrences, trying to fold loop invariants into them. 3035 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3036 // Scan all of the other operands to this mul and add them to the vector 3037 // if they are loop invariant w.r.t. the recurrence. 3038 SmallVector<const SCEV *, 8> LIOps; 3039 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3040 const Loop *AddRecLoop = AddRec->getLoop(); 3041 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3042 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3043 LIOps.push_back(Ops[i]); 3044 Ops.erase(Ops.begin()+i); 3045 --i; --e; 3046 } 3047 3048 // If we found some loop invariants, fold them into the recurrence. 3049 if (!LIOps.empty()) { 3050 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3051 SmallVector<const SCEV *, 4> NewOps; 3052 NewOps.reserve(AddRec->getNumOperands()); 3053 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3054 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3055 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3056 SCEV::FlagAnyWrap, Depth + 1)); 3057 3058 // Build the new addrec. Propagate the NUW and NSW flags if both the 3059 // outer mul and the inner addrec are guaranteed to have no overflow. 3060 // 3061 // No self-wrap cannot be guaranteed after changing the step size, but 3062 // will be inferred if either NUW or NSW is true. 3063 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3064 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3065 3066 // If all of the other operands were loop invariant, we are done. 3067 if (Ops.size() == 1) return NewRec; 3068 3069 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3070 for (unsigned i = 0;; ++i) 3071 if (Ops[i] == AddRec) { 3072 Ops[i] = NewRec; 3073 break; 3074 } 3075 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3076 } 3077 3078 // Okay, if there weren't any loop invariants to be folded, check to see 3079 // if there are multiple AddRec's with the same loop induction variable 3080 // being multiplied together. If so, we can fold them. 3081 3082 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3083 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3084 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3085 // ]]],+,...up to x=2n}. 3086 // Note that the arguments to choose() are always integers with values 3087 // known at compile time, never SCEV objects. 3088 // 3089 // The implementation avoids pointless extra computations when the two 3090 // addrec's are of different length (mathematically, it's equivalent to 3091 // an infinite stream of zeros on the right). 3092 bool OpsModified = false; 3093 for (unsigned OtherIdx = Idx+1; 3094 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3095 ++OtherIdx) { 3096 const SCEVAddRecExpr *OtherAddRec = 3097 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3098 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3099 continue; 3100 3101 // Limit max number of arguments to avoid creation of unreasonably big 3102 // SCEVAddRecs with very complex operands. 3103 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3104 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3105 continue; 3106 3107 bool Overflow = false; 3108 Type *Ty = AddRec->getType(); 3109 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3110 SmallVector<const SCEV*, 7> AddRecOps; 3111 for (int x = 0, xe = AddRec->getNumOperands() + 3112 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3113 SmallVector <const SCEV *, 7> SumOps; 3114 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3115 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3116 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3117 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3118 z < ze && !Overflow; ++z) { 3119 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3120 uint64_t Coeff; 3121 if (LargerThan64Bits) 3122 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3123 else 3124 Coeff = Coeff1*Coeff2; 3125 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3126 const SCEV *Term1 = AddRec->getOperand(y-z); 3127 const SCEV *Term2 = OtherAddRec->getOperand(z); 3128 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3129 SCEV::FlagAnyWrap, Depth + 1)); 3130 } 3131 } 3132 if (SumOps.empty()) 3133 SumOps.push_back(getZero(Ty)); 3134 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3135 } 3136 if (!Overflow) { 3137 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3138 SCEV::FlagAnyWrap); 3139 if (Ops.size() == 2) return NewAddRec; 3140 Ops[Idx] = NewAddRec; 3141 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3142 OpsModified = true; 3143 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3144 if (!AddRec) 3145 break; 3146 } 3147 } 3148 if (OpsModified) 3149 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3150 3151 // Otherwise couldn't fold anything into this recurrence. Move onto the 3152 // next one. 3153 } 3154 3155 // Okay, it looks like we really DO need an mul expr. Check to see if we 3156 // already have one, otherwise create a new one. 3157 return getOrCreateMulExpr(Ops, Flags); 3158 } 3159 3160 /// Represents an unsigned remainder expression based on unsigned division. 3161 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3162 const SCEV *RHS) { 3163 assert(getEffectiveSCEVType(LHS->getType()) == 3164 getEffectiveSCEVType(RHS->getType()) && 3165 "SCEVURemExpr operand types don't match!"); 3166 3167 // Short-circuit easy cases 3168 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3169 // If constant is one, the result is trivial 3170 if (RHSC->getValue()->isOne()) 3171 return getZero(LHS->getType()); // X urem 1 --> 0 3172 3173 // If constant is a power of two, fold into a zext(trunc(LHS)). 3174 if (RHSC->getAPInt().isPowerOf2()) { 3175 Type *FullTy = LHS->getType(); 3176 Type *TruncTy = 3177 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3178 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3179 } 3180 } 3181 3182 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3183 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3184 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3185 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3186 } 3187 3188 /// Get a canonical unsigned division expression, or something simpler if 3189 /// possible. 3190 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3191 const SCEV *RHS) { 3192 assert(getEffectiveSCEVType(LHS->getType()) == 3193 getEffectiveSCEVType(RHS->getType()) && 3194 "SCEVUDivExpr operand types don't match!"); 3195 3196 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3197 if (RHSC->getValue()->isOne()) 3198 return LHS; // X udiv 1 --> x 3199 // If the denominator is zero, the result of the udiv is undefined. Don't 3200 // try to analyze it, because the resolution chosen here may differ from 3201 // the resolution chosen in other parts of the compiler. 3202 if (!RHSC->getValue()->isZero()) { 3203 // Determine if the division can be folded into the operands of 3204 // its operands. 3205 // TODO: Generalize this to non-constants by using known-bits information. 3206 Type *Ty = LHS->getType(); 3207 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3208 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3209 // For non-power-of-two values, effectively round the value up to the 3210 // nearest power of two. 3211 if (!RHSC->getAPInt().isPowerOf2()) 3212 ++MaxShiftAmt; 3213 IntegerType *ExtTy = 3214 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3215 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3216 if (const SCEVConstant *Step = 3217 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3218 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3219 const APInt &StepInt = Step->getAPInt(); 3220 const APInt &DivInt = RHSC->getAPInt(); 3221 if (!StepInt.urem(DivInt) && 3222 getZeroExtendExpr(AR, ExtTy) == 3223 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3224 getZeroExtendExpr(Step, ExtTy), 3225 AR->getLoop(), SCEV::FlagAnyWrap)) { 3226 SmallVector<const SCEV *, 4> Operands; 3227 for (const SCEV *Op : AR->operands()) 3228 Operands.push_back(getUDivExpr(Op, RHS)); 3229 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3230 } 3231 /// Get a canonical UDivExpr for a recurrence. 3232 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3233 // We can currently only fold X%N if X is constant. 3234 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3235 if (StartC && !DivInt.urem(StepInt) && 3236 getZeroExtendExpr(AR, ExtTy) == 3237 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3238 getZeroExtendExpr(Step, ExtTy), 3239 AR->getLoop(), SCEV::FlagAnyWrap)) { 3240 const APInt &StartInt = StartC->getAPInt(); 3241 const APInt &StartRem = StartInt.urem(StepInt); 3242 if (StartRem != 0) 3243 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3244 AR->getLoop(), SCEV::FlagNW); 3245 } 3246 } 3247 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3248 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3249 SmallVector<const SCEV *, 4> Operands; 3250 for (const SCEV *Op : M->operands()) 3251 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3252 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3253 // Find an operand that's safely divisible. 3254 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3255 const SCEV *Op = M->getOperand(i); 3256 const SCEV *Div = getUDivExpr(Op, RHSC); 3257 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3258 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3259 M->op_end()); 3260 Operands[i] = Div; 3261 return getMulExpr(Operands); 3262 } 3263 } 3264 } 3265 3266 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3267 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3268 if (auto *DivisorConstant = 3269 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3270 bool Overflow = false; 3271 APInt NewRHS = 3272 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3273 if (Overflow) { 3274 return getConstant(RHSC->getType(), 0, false); 3275 } 3276 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3277 } 3278 } 3279 3280 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3281 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3282 SmallVector<const SCEV *, 4> Operands; 3283 for (const SCEV *Op : A->operands()) 3284 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3285 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3286 Operands.clear(); 3287 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3288 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3289 if (isa<SCEVUDivExpr>(Op) || 3290 getMulExpr(Op, RHS) != A->getOperand(i)) 3291 break; 3292 Operands.push_back(Op); 3293 } 3294 if (Operands.size() == A->getNumOperands()) 3295 return getAddExpr(Operands); 3296 } 3297 } 3298 3299 // Fold if both operands are constant. 3300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3301 Constant *LHSCV = LHSC->getValue(); 3302 Constant *RHSCV = RHSC->getValue(); 3303 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3304 RHSCV))); 3305 } 3306 } 3307 } 3308 3309 FoldingSetNodeID ID; 3310 ID.AddInteger(scUDivExpr); 3311 ID.AddPointer(LHS); 3312 ID.AddPointer(RHS); 3313 void *IP = nullptr; 3314 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3315 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3316 LHS, RHS); 3317 UniqueSCEVs.InsertNode(S, IP); 3318 addToLoopUseLists(S); 3319 return S; 3320 } 3321 3322 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3323 APInt A = C1->getAPInt().abs(); 3324 APInt B = C2->getAPInt().abs(); 3325 uint32_t ABW = A.getBitWidth(); 3326 uint32_t BBW = B.getBitWidth(); 3327 3328 if (ABW > BBW) 3329 B = B.zext(ABW); 3330 else if (ABW < BBW) 3331 A = A.zext(BBW); 3332 3333 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3334 } 3335 3336 /// Get a canonical unsigned division expression, or something simpler if 3337 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3338 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3339 /// it's not exact because the udiv may be clearing bits. 3340 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3341 const SCEV *RHS) { 3342 // TODO: we could try to find factors in all sorts of things, but for now we 3343 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3344 // end of this file for inspiration. 3345 3346 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3347 if (!Mul || !Mul->hasNoUnsignedWrap()) 3348 return getUDivExpr(LHS, RHS); 3349 3350 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3351 // If the mulexpr multiplies by a constant, then that constant must be the 3352 // first element of the mulexpr. 3353 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3354 if (LHSCst == RHSCst) { 3355 SmallVector<const SCEV *, 2> Operands; 3356 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3357 return getMulExpr(Operands); 3358 } 3359 3360 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3361 // that there's a factor provided by one of the other terms. We need to 3362 // check. 3363 APInt Factor = gcd(LHSCst, RHSCst); 3364 if (!Factor.isIntN(1)) { 3365 LHSCst = 3366 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3367 RHSCst = 3368 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3369 SmallVector<const SCEV *, 2> Operands; 3370 Operands.push_back(LHSCst); 3371 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3372 LHS = getMulExpr(Operands); 3373 RHS = RHSCst; 3374 Mul = dyn_cast<SCEVMulExpr>(LHS); 3375 if (!Mul) 3376 return getUDivExactExpr(LHS, RHS); 3377 } 3378 } 3379 } 3380 3381 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3382 if (Mul->getOperand(i) == RHS) { 3383 SmallVector<const SCEV *, 2> Operands; 3384 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3385 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3386 return getMulExpr(Operands); 3387 } 3388 } 3389 3390 return getUDivExpr(LHS, RHS); 3391 } 3392 3393 /// Get an add recurrence expression for the specified loop. Simplify the 3394 /// expression as much as possible. 3395 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3396 const Loop *L, 3397 SCEV::NoWrapFlags Flags) { 3398 SmallVector<const SCEV *, 4> Operands; 3399 Operands.push_back(Start); 3400 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3401 if (StepChrec->getLoop() == L) { 3402 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3403 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3404 } 3405 3406 Operands.push_back(Step); 3407 return getAddRecExpr(Operands, L, Flags); 3408 } 3409 3410 /// Get an add recurrence expression for the specified loop. Simplify the 3411 /// expression as much as possible. 3412 const SCEV * 3413 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3414 const Loop *L, SCEV::NoWrapFlags Flags) { 3415 if (Operands.size() == 1) return Operands[0]; 3416 #ifndef NDEBUG 3417 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3418 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3419 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3420 "SCEVAddRecExpr operand types don't match!"); 3421 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3422 assert(isLoopInvariant(Operands[i], L) && 3423 "SCEVAddRecExpr operand is not loop-invariant!"); 3424 #endif 3425 3426 if (Operands.back()->isZero()) { 3427 Operands.pop_back(); 3428 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3429 } 3430 3431 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3432 // use that information to infer NUW and NSW flags. However, computing a 3433 // BE count requires calling getAddRecExpr, so we may not yet have a 3434 // meaningful BE count at this point (and if we don't, we'd be stuck 3435 // with a SCEVCouldNotCompute as the cached BE count). 3436 3437 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3438 3439 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3440 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3441 const Loop *NestedLoop = NestedAR->getLoop(); 3442 if (L->contains(NestedLoop) 3443 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3444 : (!NestedLoop->contains(L) && 3445 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3446 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3447 NestedAR->op_end()); 3448 Operands[0] = NestedAR->getStart(); 3449 // AddRecs require their operands be loop-invariant with respect to their 3450 // loops. Don't perform this transformation if it would break this 3451 // requirement. 3452 bool AllInvariant = all_of( 3453 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3454 3455 if (AllInvariant) { 3456 // Create a recurrence for the outer loop with the same step size. 3457 // 3458 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3459 // inner recurrence has the same property. 3460 SCEV::NoWrapFlags OuterFlags = 3461 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3462 3463 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3464 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3465 return isLoopInvariant(Op, NestedLoop); 3466 }); 3467 3468 if (AllInvariant) { 3469 // Ok, both add recurrences are valid after the transformation. 3470 // 3471 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3472 // the outer recurrence has the same property. 3473 SCEV::NoWrapFlags InnerFlags = 3474 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3475 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3476 } 3477 } 3478 // Reset Operands to its original state. 3479 Operands[0] = NestedAR; 3480 } 3481 } 3482 3483 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3484 // already have one, otherwise create a new one. 3485 return getOrCreateAddRecExpr(Operands, L, Flags); 3486 } 3487 3488 const SCEV * 3489 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3490 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3491 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3492 // getSCEV(Base)->getType() has the same address space as Base->getType() 3493 // because SCEV::getType() preserves the address space. 3494 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3495 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3496 // instruction to its SCEV, because the Instruction may be guarded by control 3497 // flow and the no-overflow bits may not be valid for the expression in any 3498 // context. This can be fixed similarly to how these flags are handled for 3499 // adds. 3500 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3501 : SCEV::FlagAnyWrap; 3502 3503 const SCEV *TotalOffset = getZero(IntIdxTy); 3504 // The array size is unimportant. The first thing we do on CurTy is getting 3505 // its element type. 3506 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3507 for (const SCEV *IndexExpr : IndexExprs) { 3508 // Compute the (potentially symbolic) offset in bytes for this index. 3509 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3510 // For a struct, add the member offset. 3511 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3512 unsigned FieldNo = Index->getZExtValue(); 3513 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3514 3515 // Add the field offset to the running total offset. 3516 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3517 3518 // Update CurTy to the type of the field at Index. 3519 CurTy = STy->getTypeAtIndex(Index); 3520 } else { 3521 // Update CurTy to its element type. 3522 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3523 // For an array, add the element offset, explicitly scaled. 3524 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3525 // Getelementptr indices are signed. 3526 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3527 3528 // Multiply the index by the element size to compute the element offset. 3529 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3530 3531 // Add the element offset to the running total offset. 3532 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3533 } 3534 } 3535 3536 // Add the total offset from all the GEP indices to the base. 3537 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3538 } 3539 3540 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3541 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3542 ArrayRef<const SCEV *> Ops) { 3543 FoldingSetNodeID ID; 3544 void *IP = nullptr; 3545 ID.AddInteger(SCEVType); 3546 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3547 ID.AddPointer(Ops[i]); 3548 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3549 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3550 } 3551 3552 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3553 SmallVectorImpl<const SCEV *> &Ops) { 3554 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3555 if (Ops.size() == 1) return Ops[0]; 3556 #ifndef NDEBUG 3557 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3558 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3559 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3560 "Operand types don't match!"); 3561 #endif 3562 3563 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3564 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3565 3566 // Sort by complexity, this groups all similar expression types together. 3567 GroupByComplexity(Ops, &LI, DT); 3568 3569 // Check if we have created the same expression before. 3570 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3571 return S; 3572 } 3573 3574 // If there are any constants, fold them together. 3575 unsigned Idx = 0; 3576 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3577 ++Idx; 3578 assert(Idx < Ops.size()); 3579 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3580 if (Kind == scSMaxExpr) 3581 return APIntOps::smax(LHS, RHS); 3582 else if (Kind == scSMinExpr) 3583 return APIntOps::smin(LHS, RHS); 3584 else if (Kind == scUMaxExpr) 3585 return APIntOps::umax(LHS, RHS); 3586 else if (Kind == scUMinExpr) 3587 return APIntOps::umin(LHS, RHS); 3588 llvm_unreachable("Unknown SCEV min/max opcode"); 3589 }; 3590 3591 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3592 // We found two constants, fold them together! 3593 ConstantInt *Fold = ConstantInt::get( 3594 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3595 Ops[0] = getConstant(Fold); 3596 Ops.erase(Ops.begin()+1); // Erase the folded element 3597 if (Ops.size() == 1) return Ops[0]; 3598 LHSC = cast<SCEVConstant>(Ops[0]); 3599 } 3600 3601 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3602 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3603 3604 if (IsMax ? IsMinV : IsMaxV) { 3605 // If we are left with a constant minimum(/maximum)-int, strip it off. 3606 Ops.erase(Ops.begin()); 3607 --Idx; 3608 } else if (IsMax ? IsMaxV : IsMinV) { 3609 // If we have a max(/min) with a constant maximum(/minimum)-int, 3610 // it will always be the extremum. 3611 return LHSC; 3612 } 3613 3614 if (Ops.size() == 1) return Ops[0]; 3615 } 3616 3617 // Find the first operation of the same kind 3618 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3619 ++Idx; 3620 3621 // Check to see if one of the operands is of the same kind. If so, expand its 3622 // operands onto our operand list, and recurse to simplify. 3623 if (Idx < Ops.size()) { 3624 bool DeletedAny = false; 3625 while (Ops[Idx]->getSCEVType() == Kind) { 3626 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3627 Ops.erase(Ops.begin()+Idx); 3628 Ops.append(SMME->op_begin(), SMME->op_end()); 3629 DeletedAny = true; 3630 } 3631 3632 if (DeletedAny) 3633 return getMinMaxExpr(Kind, Ops); 3634 } 3635 3636 // Okay, check to see if the same value occurs in the operand list twice. If 3637 // so, delete one. Since we sorted the list, these values are required to 3638 // be adjacent. 3639 llvm::CmpInst::Predicate GEPred = 3640 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3641 llvm::CmpInst::Predicate LEPred = 3642 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3643 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3644 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3645 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3646 if (Ops[i] == Ops[i + 1] || 3647 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3648 // X op Y op Y --> X op Y 3649 // X op Y --> X, if we know X, Y are ordered appropriately 3650 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3651 --i; 3652 --e; 3653 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3654 Ops[i + 1])) { 3655 // X op Y --> Y, if we know X, Y are ordered appropriately 3656 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3657 --i; 3658 --e; 3659 } 3660 } 3661 3662 if (Ops.size() == 1) return Ops[0]; 3663 3664 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3665 3666 // Okay, it looks like we really DO need an expr. Check to see if we 3667 // already have one, otherwise create a new one. 3668 const SCEV *ExistingSCEV; 3669 FoldingSetNodeID ID; 3670 void *IP; 3671 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3672 if (ExistingSCEV) 3673 return ExistingSCEV; 3674 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3675 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3676 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3677 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3678 3679 UniqueSCEVs.InsertNode(S, IP); 3680 addToLoopUseLists(S); 3681 return S; 3682 } 3683 3684 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3685 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3686 return getSMaxExpr(Ops); 3687 } 3688 3689 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3690 return getMinMaxExpr(scSMaxExpr, Ops); 3691 } 3692 3693 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3694 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3695 return getUMaxExpr(Ops); 3696 } 3697 3698 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3699 return getMinMaxExpr(scUMaxExpr, Ops); 3700 } 3701 3702 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3703 const SCEV *RHS) { 3704 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3705 return getSMinExpr(Ops); 3706 } 3707 3708 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3709 return getMinMaxExpr(scSMinExpr, Ops); 3710 } 3711 3712 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3713 const SCEV *RHS) { 3714 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3715 return getUMinExpr(Ops); 3716 } 3717 3718 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3719 return getMinMaxExpr(scUMinExpr, Ops); 3720 } 3721 3722 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3723 // We can bypass creating a target-independent 3724 // constant expression and then folding it back into a ConstantInt. 3725 // This is just a compile-time optimization. 3726 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3727 } 3728 3729 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3730 StructType *STy, 3731 unsigned FieldNo) { 3732 // We can bypass creating a target-independent 3733 // constant expression and then folding it back into a ConstantInt. 3734 // This is just a compile-time optimization. 3735 return getConstant( 3736 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3737 } 3738 3739 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3740 // Don't attempt to do anything other than create a SCEVUnknown object 3741 // here. createSCEV only calls getUnknown after checking for all other 3742 // interesting possibilities, and any other code that calls getUnknown 3743 // is doing so in order to hide a value from SCEV canonicalization. 3744 3745 FoldingSetNodeID ID; 3746 ID.AddInteger(scUnknown); 3747 ID.AddPointer(V); 3748 void *IP = nullptr; 3749 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3750 assert(cast<SCEVUnknown>(S)->getValue() == V && 3751 "Stale SCEVUnknown in uniquing map!"); 3752 return S; 3753 } 3754 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3755 FirstUnknown); 3756 FirstUnknown = cast<SCEVUnknown>(S); 3757 UniqueSCEVs.InsertNode(S, IP); 3758 return S; 3759 } 3760 3761 //===----------------------------------------------------------------------===// 3762 // Basic SCEV Analysis and PHI Idiom Recognition Code 3763 // 3764 3765 /// Test if values of the given type are analyzable within the SCEV 3766 /// framework. This primarily includes integer types, and it can optionally 3767 /// include pointer types if the ScalarEvolution class has access to 3768 /// target-specific information. 3769 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3770 // Integers and pointers are always SCEVable. 3771 return Ty->isIntOrPtrTy(); 3772 } 3773 3774 /// Return the size in bits of the specified type, for which isSCEVable must 3775 /// return true. 3776 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3777 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3778 if (Ty->isPointerTy()) 3779 return getDataLayout().getIndexTypeSizeInBits(Ty); 3780 return getDataLayout().getTypeSizeInBits(Ty); 3781 } 3782 3783 /// Return a type with the same bitwidth as the given type and which represents 3784 /// how SCEV will treat the given type, for which isSCEVable must return 3785 /// true. For pointer types, this is the pointer index sized integer type. 3786 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3787 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3788 3789 if (Ty->isIntegerTy()) 3790 return Ty; 3791 3792 // The only other support type is pointer. 3793 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3794 return getDataLayout().getIndexType(Ty); 3795 } 3796 3797 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3798 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3799 } 3800 3801 const SCEV *ScalarEvolution::getCouldNotCompute() { 3802 return CouldNotCompute.get(); 3803 } 3804 3805 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3806 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3807 auto *SU = dyn_cast<SCEVUnknown>(S); 3808 return SU && SU->getValue() == nullptr; 3809 }); 3810 3811 return !ContainsNulls; 3812 } 3813 3814 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3815 HasRecMapType::iterator I = HasRecMap.find(S); 3816 if (I != HasRecMap.end()) 3817 return I->second; 3818 3819 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3820 HasRecMap.insert({S, FoundAddRec}); 3821 return FoundAddRec; 3822 } 3823 3824 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3825 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3826 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3827 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3828 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3829 if (!Add) 3830 return {S, nullptr}; 3831 3832 if (Add->getNumOperands() != 2) 3833 return {S, nullptr}; 3834 3835 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3836 if (!ConstOp) 3837 return {S, nullptr}; 3838 3839 return {Add->getOperand(1), ConstOp->getValue()}; 3840 } 3841 3842 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3843 /// by the value and offset from any ValueOffsetPair in the set. 3844 SetVector<ScalarEvolution::ValueOffsetPair> * 3845 ScalarEvolution::getSCEVValues(const SCEV *S) { 3846 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3847 if (SI == ExprValueMap.end()) 3848 return nullptr; 3849 #ifndef NDEBUG 3850 if (VerifySCEVMap) { 3851 // Check there is no dangling Value in the set returned. 3852 for (const auto &VE : SI->second) 3853 assert(ValueExprMap.count(VE.first)); 3854 } 3855 #endif 3856 return &SI->second; 3857 } 3858 3859 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3860 /// cannot be used separately. eraseValueFromMap should be used to remove 3861 /// V from ValueExprMap and ExprValueMap at the same time. 3862 void ScalarEvolution::eraseValueFromMap(Value *V) { 3863 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3864 if (I != ValueExprMap.end()) { 3865 const SCEV *S = I->second; 3866 // Remove {V, 0} from the set of ExprValueMap[S] 3867 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3868 SV->remove({V, nullptr}); 3869 3870 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3871 const SCEV *Stripped; 3872 ConstantInt *Offset; 3873 std::tie(Stripped, Offset) = splitAddExpr(S); 3874 if (Offset != nullptr) { 3875 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3876 SV->remove({V, Offset}); 3877 } 3878 ValueExprMap.erase(V); 3879 } 3880 } 3881 3882 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3883 /// TODO: In reality it is better to check the poison recursively 3884 /// but this is better than nothing. 3885 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3886 if (auto *I = dyn_cast<Instruction>(V)) { 3887 if (isa<OverflowingBinaryOperator>(I)) { 3888 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3889 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3890 return true; 3891 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3892 return true; 3893 } 3894 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3895 return true; 3896 } 3897 return false; 3898 } 3899 3900 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3901 /// create a new one. 3902 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3903 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3904 3905 const SCEV *S = getExistingSCEV(V); 3906 if (S == nullptr) { 3907 S = createSCEV(V); 3908 // During PHI resolution, it is possible to create two SCEVs for the same 3909 // V, so it is needed to double check whether V->S is inserted into 3910 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3911 std::pair<ValueExprMapType::iterator, bool> Pair = 3912 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3913 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3914 ExprValueMap[S].insert({V, nullptr}); 3915 3916 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3917 // ExprValueMap. 3918 const SCEV *Stripped = S; 3919 ConstantInt *Offset = nullptr; 3920 std::tie(Stripped, Offset) = splitAddExpr(S); 3921 // If stripped is SCEVUnknown, don't bother to save 3922 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3923 // increase the complexity of the expansion code. 3924 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3925 // because it may generate add/sub instead of GEP in SCEV expansion. 3926 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3927 !isa<GetElementPtrInst>(V)) 3928 ExprValueMap[Stripped].insert({V, Offset}); 3929 } 3930 } 3931 return S; 3932 } 3933 3934 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3935 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3936 3937 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3938 if (I != ValueExprMap.end()) { 3939 const SCEV *S = I->second; 3940 if (checkValidity(S)) 3941 return S; 3942 eraseValueFromMap(V); 3943 forgetMemoizedResults(S); 3944 } 3945 return nullptr; 3946 } 3947 3948 /// Return a SCEV corresponding to -V = -1*V 3949 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3950 SCEV::NoWrapFlags Flags) { 3951 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3952 return getConstant( 3953 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3954 3955 Type *Ty = V->getType(); 3956 Ty = getEffectiveSCEVType(Ty); 3957 return getMulExpr( 3958 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3959 } 3960 3961 /// If Expr computes ~A, return A else return nullptr 3962 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3963 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3964 if (!Add || Add->getNumOperands() != 2 || 3965 !Add->getOperand(0)->isAllOnesValue()) 3966 return nullptr; 3967 3968 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3969 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3970 !AddRHS->getOperand(0)->isAllOnesValue()) 3971 return nullptr; 3972 3973 return AddRHS->getOperand(1); 3974 } 3975 3976 /// Return a SCEV corresponding to ~V = -1-V 3977 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3978 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3979 return getConstant( 3980 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3981 3982 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3983 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3984 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3985 SmallVector<const SCEV *, 2> MatchedOperands; 3986 for (const SCEV *Operand : MME->operands()) { 3987 const SCEV *Matched = MatchNotExpr(Operand); 3988 if (!Matched) 3989 return (const SCEV *)nullptr; 3990 MatchedOperands.push_back(Matched); 3991 } 3992 return getMinMaxExpr( 3993 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3994 MatchedOperands); 3995 }; 3996 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3997 return Replaced; 3998 } 3999 4000 Type *Ty = V->getType(); 4001 Ty = getEffectiveSCEVType(Ty); 4002 const SCEV *AllOnes = 4003 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4004 return getMinusSCEV(AllOnes, V); 4005 } 4006 4007 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4008 SCEV::NoWrapFlags Flags, 4009 unsigned Depth) { 4010 // Fast path: X - X --> 0. 4011 if (LHS == RHS) 4012 return getZero(LHS->getType()); 4013 4014 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4015 // makes it so that we cannot make much use of NUW. 4016 auto AddFlags = SCEV::FlagAnyWrap; 4017 const bool RHSIsNotMinSigned = 4018 !getSignedRangeMin(RHS).isMinSignedValue(); 4019 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4020 // Let M be the minimum representable signed value. Then (-1)*RHS 4021 // signed-wraps if and only if RHS is M. That can happen even for 4022 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4023 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4024 // (-1)*RHS, we need to prove that RHS != M. 4025 // 4026 // If LHS is non-negative and we know that LHS - RHS does not 4027 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4028 // either by proving that RHS > M or that LHS >= 0. 4029 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4030 AddFlags = SCEV::FlagNSW; 4031 } 4032 } 4033 4034 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4035 // RHS is NSW and LHS >= 0. 4036 // 4037 // The difficulty here is that the NSW flag may have been proven 4038 // relative to a loop that is to be found in a recurrence in LHS and 4039 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4040 // larger scope than intended. 4041 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4042 4043 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4044 } 4045 4046 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4047 unsigned Depth) { 4048 Type *SrcTy = V->getType(); 4049 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4050 "Cannot truncate or zero extend with non-integer arguments!"); 4051 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4052 return V; // No conversion 4053 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4054 return getTruncateExpr(V, Ty, Depth); 4055 return getZeroExtendExpr(V, Ty, Depth); 4056 } 4057 4058 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4059 unsigned Depth) { 4060 Type *SrcTy = V->getType(); 4061 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4062 "Cannot truncate or zero extend with non-integer arguments!"); 4063 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4064 return V; // No conversion 4065 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4066 return getTruncateExpr(V, Ty, Depth); 4067 return getSignExtendExpr(V, Ty, Depth); 4068 } 4069 4070 const SCEV * 4071 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4072 Type *SrcTy = V->getType(); 4073 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4074 "Cannot noop or zero extend with non-integer arguments!"); 4075 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4076 "getNoopOrZeroExtend cannot truncate!"); 4077 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4078 return V; // No conversion 4079 return getZeroExtendExpr(V, Ty); 4080 } 4081 4082 const SCEV * 4083 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4084 Type *SrcTy = V->getType(); 4085 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4086 "Cannot noop or sign extend with non-integer arguments!"); 4087 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4088 "getNoopOrSignExtend cannot truncate!"); 4089 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4090 return V; // No conversion 4091 return getSignExtendExpr(V, Ty); 4092 } 4093 4094 const SCEV * 4095 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4096 Type *SrcTy = V->getType(); 4097 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4098 "Cannot noop or any extend with non-integer arguments!"); 4099 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4100 "getNoopOrAnyExtend cannot truncate!"); 4101 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4102 return V; // No conversion 4103 return getAnyExtendExpr(V, Ty); 4104 } 4105 4106 const SCEV * 4107 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4108 Type *SrcTy = V->getType(); 4109 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4110 "Cannot truncate or noop with non-integer arguments!"); 4111 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4112 "getTruncateOrNoop cannot extend!"); 4113 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4114 return V; // No conversion 4115 return getTruncateExpr(V, Ty); 4116 } 4117 4118 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4119 const SCEV *RHS) { 4120 const SCEV *PromotedLHS = LHS; 4121 const SCEV *PromotedRHS = RHS; 4122 4123 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4124 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4125 else 4126 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4127 4128 return getUMaxExpr(PromotedLHS, PromotedRHS); 4129 } 4130 4131 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4132 const SCEV *RHS) { 4133 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4134 return getUMinFromMismatchedTypes(Ops); 4135 } 4136 4137 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4138 SmallVectorImpl<const SCEV *> &Ops) { 4139 assert(!Ops.empty() && "At least one operand must be!"); 4140 // Trivial case. 4141 if (Ops.size() == 1) 4142 return Ops[0]; 4143 4144 // Find the max type first. 4145 Type *MaxType = nullptr; 4146 for (auto *S : Ops) 4147 if (MaxType) 4148 MaxType = getWiderType(MaxType, S->getType()); 4149 else 4150 MaxType = S->getType(); 4151 4152 // Extend all ops to max type. 4153 SmallVector<const SCEV *, 2> PromotedOps; 4154 for (auto *S : Ops) 4155 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4156 4157 // Generate umin. 4158 return getUMinExpr(PromotedOps); 4159 } 4160 4161 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4162 // A pointer operand may evaluate to a nonpointer expression, such as null. 4163 if (!V->getType()->isPointerTy()) 4164 return V; 4165 4166 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4167 return getPointerBase(Cast->getOperand()); 4168 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4169 const SCEV *PtrOp = nullptr; 4170 for (const SCEV *NAryOp : NAry->operands()) { 4171 if (NAryOp->getType()->isPointerTy()) { 4172 // Cannot find the base of an expression with multiple pointer operands. 4173 if (PtrOp) 4174 return V; 4175 PtrOp = NAryOp; 4176 } 4177 } 4178 if (!PtrOp) 4179 return V; 4180 return getPointerBase(PtrOp); 4181 } 4182 return V; 4183 } 4184 4185 /// Push users of the given Instruction onto the given Worklist. 4186 static void 4187 PushDefUseChildren(Instruction *I, 4188 SmallVectorImpl<Instruction *> &Worklist) { 4189 // Push the def-use children onto the Worklist stack. 4190 for (User *U : I->users()) 4191 Worklist.push_back(cast<Instruction>(U)); 4192 } 4193 4194 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4195 SmallVector<Instruction *, 16> Worklist; 4196 PushDefUseChildren(PN, Worklist); 4197 4198 SmallPtrSet<Instruction *, 8> Visited; 4199 Visited.insert(PN); 4200 while (!Worklist.empty()) { 4201 Instruction *I = Worklist.pop_back_val(); 4202 if (!Visited.insert(I).second) 4203 continue; 4204 4205 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4206 if (It != ValueExprMap.end()) { 4207 const SCEV *Old = It->second; 4208 4209 // Short-circuit the def-use traversal if the symbolic name 4210 // ceases to appear in expressions. 4211 if (Old != SymName && !hasOperand(Old, SymName)) 4212 continue; 4213 4214 // SCEVUnknown for a PHI either means that it has an unrecognized 4215 // structure, it's a PHI that's in the progress of being computed 4216 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4217 // additional loop trip count information isn't going to change anything. 4218 // In the second case, createNodeForPHI will perform the necessary 4219 // updates on its own when it gets to that point. In the third, we do 4220 // want to forget the SCEVUnknown. 4221 if (!isa<PHINode>(I) || 4222 !isa<SCEVUnknown>(Old) || 4223 (I != PN && Old == SymName)) { 4224 eraseValueFromMap(It->first); 4225 forgetMemoizedResults(Old); 4226 } 4227 } 4228 4229 PushDefUseChildren(I, Worklist); 4230 } 4231 } 4232 4233 namespace { 4234 4235 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4236 /// expression in case its Loop is L. If it is not L then 4237 /// if IgnoreOtherLoops is true then use AddRec itself 4238 /// otherwise rewrite cannot be done. 4239 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4240 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4241 public: 4242 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4243 bool IgnoreOtherLoops = true) { 4244 SCEVInitRewriter Rewriter(L, SE); 4245 const SCEV *Result = Rewriter.visit(S); 4246 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4247 return SE.getCouldNotCompute(); 4248 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4249 ? SE.getCouldNotCompute() 4250 : Result; 4251 } 4252 4253 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4254 if (!SE.isLoopInvariant(Expr, L)) 4255 SeenLoopVariantSCEVUnknown = true; 4256 return Expr; 4257 } 4258 4259 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4260 // Only re-write AddRecExprs for this loop. 4261 if (Expr->getLoop() == L) 4262 return Expr->getStart(); 4263 SeenOtherLoops = true; 4264 return Expr; 4265 } 4266 4267 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4268 4269 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4270 4271 private: 4272 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4273 : SCEVRewriteVisitor(SE), L(L) {} 4274 4275 const Loop *L; 4276 bool SeenLoopVariantSCEVUnknown = false; 4277 bool SeenOtherLoops = false; 4278 }; 4279 4280 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4281 /// increment expression in case its Loop is L. If it is not L then 4282 /// use AddRec itself. 4283 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4284 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4285 public: 4286 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4287 SCEVPostIncRewriter Rewriter(L, SE); 4288 const SCEV *Result = Rewriter.visit(S); 4289 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4290 ? SE.getCouldNotCompute() 4291 : Result; 4292 } 4293 4294 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4295 if (!SE.isLoopInvariant(Expr, L)) 4296 SeenLoopVariantSCEVUnknown = true; 4297 return Expr; 4298 } 4299 4300 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4301 // Only re-write AddRecExprs for this loop. 4302 if (Expr->getLoop() == L) 4303 return Expr->getPostIncExpr(SE); 4304 SeenOtherLoops = true; 4305 return Expr; 4306 } 4307 4308 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4309 4310 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4311 4312 private: 4313 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4314 : SCEVRewriteVisitor(SE), L(L) {} 4315 4316 const Loop *L; 4317 bool SeenLoopVariantSCEVUnknown = false; 4318 bool SeenOtherLoops = false; 4319 }; 4320 4321 /// This class evaluates the compare condition by matching it against the 4322 /// condition of loop latch. If there is a match we assume a true value 4323 /// for the condition while building SCEV nodes. 4324 class SCEVBackedgeConditionFolder 4325 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4326 public: 4327 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4328 ScalarEvolution &SE) { 4329 bool IsPosBECond = false; 4330 Value *BECond = nullptr; 4331 if (BasicBlock *Latch = L->getLoopLatch()) { 4332 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4333 if (BI && BI->isConditional()) { 4334 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4335 "Both outgoing branches should not target same header!"); 4336 BECond = BI->getCondition(); 4337 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4338 } else { 4339 return S; 4340 } 4341 } 4342 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4343 return Rewriter.visit(S); 4344 } 4345 4346 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4347 const SCEV *Result = Expr; 4348 bool InvariantF = SE.isLoopInvariant(Expr, L); 4349 4350 if (!InvariantF) { 4351 Instruction *I = cast<Instruction>(Expr->getValue()); 4352 switch (I->getOpcode()) { 4353 case Instruction::Select: { 4354 SelectInst *SI = cast<SelectInst>(I); 4355 Optional<const SCEV *> Res = 4356 compareWithBackedgeCondition(SI->getCondition()); 4357 if (Res.hasValue()) { 4358 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4359 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4360 } 4361 break; 4362 } 4363 default: { 4364 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4365 if (Res.hasValue()) 4366 Result = Res.getValue(); 4367 break; 4368 } 4369 } 4370 } 4371 return Result; 4372 } 4373 4374 private: 4375 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4376 bool IsPosBECond, ScalarEvolution &SE) 4377 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4378 IsPositiveBECond(IsPosBECond) {} 4379 4380 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4381 4382 const Loop *L; 4383 /// Loop back condition. 4384 Value *BackedgeCond = nullptr; 4385 /// Set to true if loop back is on positive branch condition. 4386 bool IsPositiveBECond; 4387 }; 4388 4389 Optional<const SCEV *> 4390 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4391 4392 // If value matches the backedge condition for loop latch, 4393 // then return a constant evolution node based on loopback 4394 // branch taken. 4395 if (BackedgeCond == IC) 4396 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4397 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4398 return None; 4399 } 4400 4401 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4402 public: 4403 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4404 ScalarEvolution &SE) { 4405 SCEVShiftRewriter Rewriter(L, SE); 4406 const SCEV *Result = Rewriter.visit(S); 4407 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4408 } 4409 4410 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4411 // Only allow AddRecExprs for this loop. 4412 if (!SE.isLoopInvariant(Expr, L)) 4413 Valid = false; 4414 return Expr; 4415 } 4416 4417 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4418 if (Expr->getLoop() == L && Expr->isAffine()) 4419 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4420 Valid = false; 4421 return Expr; 4422 } 4423 4424 bool isValid() { return Valid; } 4425 4426 private: 4427 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4428 : SCEVRewriteVisitor(SE), L(L) {} 4429 4430 const Loop *L; 4431 bool Valid = true; 4432 }; 4433 4434 } // end anonymous namespace 4435 4436 SCEV::NoWrapFlags 4437 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4438 if (!AR->isAffine()) 4439 return SCEV::FlagAnyWrap; 4440 4441 using OBO = OverflowingBinaryOperator; 4442 4443 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4444 4445 if (!AR->hasNoSignedWrap()) { 4446 ConstantRange AddRecRange = getSignedRange(AR); 4447 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4448 4449 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4450 Instruction::Add, IncRange, OBO::NoSignedWrap); 4451 if (NSWRegion.contains(AddRecRange)) 4452 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4453 } 4454 4455 if (!AR->hasNoUnsignedWrap()) { 4456 ConstantRange AddRecRange = getUnsignedRange(AR); 4457 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4458 4459 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4460 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4461 if (NUWRegion.contains(AddRecRange)) 4462 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4463 } 4464 4465 return Result; 4466 } 4467 4468 namespace { 4469 4470 /// Represents an abstract binary operation. This may exist as a 4471 /// normal instruction or constant expression, or may have been 4472 /// derived from an expression tree. 4473 struct BinaryOp { 4474 unsigned Opcode; 4475 Value *LHS; 4476 Value *RHS; 4477 bool IsNSW = false; 4478 bool IsNUW = false; 4479 4480 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4481 /// constant expression. 4482 Operator *Op = nullptr; 4483 4484 explicit BinaryOp(Operator *Op) 4485 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4486 Op(Op) { 4487 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4488 IsNSW = OBO->hasNoSignedWrap(); 4489 IsNUW = OBO->hasNoUnsignedWrap(); 4490 } 4491 } 4492 4493 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4494 bool IsNUW = false) 4495 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4496 }; 4497 4498 } // end anonymous namespace 4499 4500 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4501 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4502 auto *Op = dyn_cast<Operator>(V); 4503 if (!Op) 4504 return None; 4505 4506 // Implementation detail: all the cleverness here should happen without 4507 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4508 // SCEV expressions when possible, and we should not break that. 4509 4510 switch (Op->getOpcode()) { 4511 case Instruction::Add: 4512 case Instruction::Sub: 4513 case Instruction::Mul: 4514 case Instruction::UDiv: 4515 case Instruction::URem: 4516 case Instruction::And: 4517 case Instruction::Or: 4518 case Instruction::AShr: 4519 case Instruction::Shl: 4520 return BinaryOp(Op); 4521 4522 case Instruction::Xor: 4523 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4524 // If the RHS of the xor is a signmask, then this is just an add. 4525 // Instcombine turns add of signmask into xor as a strength reduction step. 4526 if (RHSC->getValue().isSignMask()) 4527 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4528 return BinaryOp(Op); 4529 4530 case Instruction::LShr: 4531 // Turn logical shift right of a constant into a unsigned divide. 4532 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4533 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4534 4535 // If the shift count is not less than the bitwidth, the result of 4536 // the shift is undefined. Don't try to analyze it, because the 4537 // resolution chosen here may differ from the resolution chosen in 4538 // other parts of the compiler. 4539 if (SA->getValue().ult(BitWidth)) { 4540 Constant *X = 4541 ConstantInt::get(SA->getContext(), 4542 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4543 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4544 } 4545 } 4546 return BinaryOp(Op); 4547 4548 case Instruction::ExtractValue: { 4549 auto *EVI = cast<ExtractValueInst>(Op); 4550 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4551 break; 4552 4553 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4554 if (!WO) 4555 break; 4556 4557 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4558 bool Signed = WO->isSigned(); 4559 // TODO: Should add nuw/nsw flags for mul as well. 4560 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4561 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4562 4563 // Now that we know that all uses of the arithmetic-result component of 4564 // CI are guarded by the overflow check, we can go ahead and pretend 4565 // that the arithmetic is non-overflowing. 4566 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4567 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4568 } 4569 4570 default: 4571 break; 4572 } 4573 4574 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4575 // semantics as a Sub, return a binary sub expression. 4576 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4577 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4578 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4579 4580 return None; 4581 } 4582 4583 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4584 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4585 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4586 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4587 /// follows one of the following patterns: 4588 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4589 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4590 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4591 /// we return the type of the truncation operation, and indicate whether the 4592 /// truncated type should be treated as signed/unsigned by setting 4593 /// \p Signed to true/false, respectively. 4594 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4595 bool &Signed, ScalarEvolution &SE) { 4596 // The case where Op == SymbolicPHI (that is, with no type conversions on 4597 // the way) is handled by the regular add recurrence creating logic and 4598 // would have already been triggered in createAddRecForPHI. Reaching it here 4599 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4600 // because one of the other operands of the SCEVAddExpr updating this PHI is 4601 // not invariant). 4602 // 4603 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4604 // this case predicates that allow us to prove that Op == SymbolicPHI will 4605 // be added. 4606 if (Op == SymbolicPHI) 4607 return nullptr; 4608 4609 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4610 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4611 if (SourceBits != NewBits) 4612 return nullptr; 4613 4614 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4615 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4616 if (!SExt && !ZExt) 4617 return nullptr; 4618 const SCEVTruncateExpr *Trunc = 4619 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4620 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4621 if (!Trunc) 4622 return nullptr; 4623 const SCEV *X = Trunc->getOperand(); 4624 if (X != SymbolicPHI) 4625 return nullptr; 4626 Signed = SExt != nullptr; 4627 return Trunc->getType(); 4628 } 4629 4630 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4631 if (!PN->getType()->isIntegerTy()) 4632 return nullptr; 4633 const Loop *L = LI.getLoopFor(PN->getParent()); 4634 if (!L || L->getHeader() != PN->getParent()) 4635 return nullptr; 4636 return L; 4637 } 4638 4639 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4640 // computation that updates the phi follows the following pattern: 4641 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4642 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4643 // If so, try to see if it can be rewritten as an AddRecExpr under some 4644 // Predicates. If successful, return them as a pair. Also cache the results 4645 // of the analysis. 4646 // 4647 // Example usage scenario: 4648 // Say the Rewriter is called for the following SCEV: 4649 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4650 // where: 4651 // %X = phi i64 (%Start, %BEValue) 4652 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4653 // and call this function with %SymbolicPHI = %X. 4654 // 4655 // The analysis will find that the value coming around the backedge has 4656 // the following SCEV: 4657 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4658 // Upon concluding that this matches the desired pattern, the function 4659 // will return the pair {NewAddRec, SmallPredsVec} where: 4660 // NewAddRec = {%Start,+,%Step} 4661 // SmallPredsVec = {P1, P2, P3} as follows: 4662 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4663 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4664 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4665 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4666 // under the predicates {P1,P2,P3}. 4667 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4668 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4669 // 4670 // TODO's: 4671 // 4672 // 1) Extend the Induction descriptor to also support inductions that involve 4673 // casts: When needed (namely, when we are called in the context of the 4674 // vectorizer induction analysis), a Set of cast instructions will be 4675 // populated by this method, and provided back to isInductionPHI. This is 4676 // needed to allow the vectorizer to properly record them to be ignored by 4677 // the cost model and to avoid vectorizing them (otherwise these casts, 4678 // which are redundant under the runtime overflow checks, will be 4679 // vectorized, which can be costly). 4680 // 4681 // 2) Support additional induction/PHISCEV patterns: We also want to support 4682 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4683 // after the induction update operation (the induction increment): 4684 // 4685 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4686 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4687 // 4688 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4689 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4690 // 4691 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4692 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4693 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4694 SmallVector<const SCEVPredicate *, 3> Predicates; 4695 4696 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4697 // return an AddRec expression under some predicate. 4698 4699 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4700 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4701 assert(L && "Expecting an integer loop header phi"); 4702 4703 // The loop may have multiple entrances or multiple exits; we can analyze 4704 // this phi as an addrec if it has a unique entry value and a unique 4705 // backedge value. 4706 Value *BEValueV = nullptr, *StartValueV = nullptr; 4707 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4708 Value *V = PN->getIncomingValue(i); 4709 if (L->contains(PN->getIncomingBlock(i))) { 4710 if (!BEValueV) { 4711 BEValueV = V; 4712 } else if (BEValueV != V) { 4713 BEValueV = nullptr; 4714 break; 4715 } 4716 } else if (!StartValueV) { 4717 StartValueV = V; 4718 } else if (StartValueV != V) { 4719 StartValueV = nullptr; 4720 break; 4721 } 4722 } 4723 if (!BEValueV || !StartValueV) 4724 return None; 4725 4726 const SCEV *BEValue = getSCEV(BEValueV); 4727 4728 // If the value coming around the backedge is an add with the symbolic 4729 // value we just inserted, possibly with casts that we can ignore under 4730 // an appropriate runtime guard, then we found a simple induction variable! 4731 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4732 if (!Add) 4733 return None; 4734 4735 // If there is a single occurrence of the symbolic value, possibly 4736 // casted, replace it with a recurrence. 4737 unsigned FoundIndex = Add->getNumOperands(); 4738 Type *TruncTy = nullptr; 4739 bool Signed; 4740 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4741 if ((TruncTy = 4742 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4743 if (FoundIndex == e) { 4744 FoundIndex = i; 4745 break; 4746 } 4747 4748 if (FoundIndex == Add->getNumOperands()) 4749 return None; 4750 4751 // Create an add with everything but the specified operand. 4752 SmallVector<const SCEV *, 8> Ops; 4753 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4754 if (i != FoundIndex) 4755 Ops.push_back(Add->getOperand(i)); 4756 const SCEV *Accum = getAddExpr(Ops); 4757 4758 // The runtime checks will not be valid if the step amount is 4759 // varying inside the loop. 4760 if (!isLoopInvariant(Accum, L)) 4761 return None; 4762 4763 // *** Part2: Create the predicates 4764 4765 // Analysis was successful: we have a phi-with-cast pattern for which we 4766 // can return an AddRec expression under the following predicates: 4767 // 4768 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4769 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4770 // P2: An Equal predicate that guarantees that 4771 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4772 // P3: An Equal predicate that guarantees that 4773 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4774 // 4775 // As we next prove, the above predicates guarantee that: 4776 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4777 // 4778 // 4779 // More formally, we want to prove that: 4780 // Expr(i+1) = Start + (i+1) * Accum 4781 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4782 // 4783 // Given that: 4784 // 1) Expr(0) = Start 4785 // 2) Expr(1) = Start + Accum 4786 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4787 // 3) Induction hypothesis (step i): 4788 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4789 // 4790 // Proof: 4791 // Expr(i+1) = 4792 // = Start + (i+1)*Accum 4793 // = (Start + i*Accum) + Accum 4794 // = Expr(i) + Accum 4795 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4796 // :: from step i 4797 // 4798 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4799 // 4800 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4801 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4802 // + Accum :: from P3 4803 // 4804 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4805 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4806 // 4807 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4808 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4809 // 4810 // By induction, the same applies to all iterations 1<=i<n: 4811 // 4812 4813 // Create a truncated addrec for which we will add a no overflow check (P1). 4814 const SCEV *StartVal = getSCEV(StartValueV); 4815 const SCEV *PHISCEV = 4816 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4817 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4818 4819 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4820 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4821 // will be constant. 4822 // 4823 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4824 // add P1. 4825 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4826 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4827 Signed ? SCEVWrapPredicate::IncrementNSSW 4828 : SCEVWrapPredicate::IncrementNUSW; 4829 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4830 Predicates.push_back(AddRecPred); 4831 } 4832 4833 // Create the Equal Predicates P2,P3: 4834 4835 // It is possible that the predicates P2 and/or P3 are computable at 4836 // compile time due to StartVal and/or Accum being constants. 4837 // If either one is, then we can check that now and escape if either P2 4838 // or P3 is false. 4839 4840 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4841 // for each of StartVal and Accum 4842 auto getExtendedExpr = [&](const SCEV *Expr, 4843 bool CreateSignExtend) -> const SCEV * { 4844 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4845 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4846 const SCEV *ExtendedExpr = 4847 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4848 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4849 return ExtendedExpr; 4850 }; 4851 4852 // Given: 4853 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4854 // = getExtendedExpr(Expr) 4855 // Determine whether the predicate P: Expr == ExtendedExpr 4856 // is known to be false at compile time 4857 auto PredIsKnownFalse = [&](const SCEV *Expr, 4858 const SCEV *ExtendedExpr) -> bool { 4859 return Expr != ExtendedExpr && 4860 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4861 }; 4862 4863 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4864 if (PredIsKnownFalse(StartVal, StartExtended)) { 4865 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4866 return None; 4867 } 4868 4869 // The Step is always Signed (because the overflow checks are either 4870 // NSSW or NUSW) 4871 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4872 if (PredIsKnownFalse(Accum, AccumExtended)) { 4873 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4874 return None; 4875 } 4876 4877 auto AppendPredicate = [&](const SCEV *Expr, 4878 const SCEV *ExtendedExpr) -> void { 4879 if (Expr != ExtendedExpr && 4880 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4881 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4882 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4883 Predicates.push_back(Pred); 4884 } 4885 }; 4886 4887 AppendPredicate(StartVal, StartExtended); 4888 AppendPredicate(Accum, AccumExtended); 4889 4890 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4891 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4892 // into NewAR if it will also add the runtime overflow checks specified in 4893 // Predicates. 4894 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4895 4896 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4897 std::make_pair(NewAR, Predicates); 4898 // Remember the result of the analysis for this SCEV at this locayyytion. 4899 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4900 return PredRewrite; 4901 } 4902 4903 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4904 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4905 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4906 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4907 if (!L) 4908 return None; 4909 4910 // Check to see if we already analyzed this PHI. 4911 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4912 if (I != PredicatedSCEVRewrites.end()) { 4913 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4914 I->second; 4915 // Analysis was done before and failed to create an AddRec: 4916 if (Rewrite.first == SymbolicPHI) 4917 return None; 4918 // Analysis was done before and succeeded to create an AddRec under 4919 // a predicate: 4920 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4921 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4922 return Rewrite; 4923 } 4924 4925 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4926 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4927 4928 // Record in the cache that the analysis failed 4929 if (!Rewrite) { 4930 SmallVector<const SCEVPredicate *, 3> Predicates; 4931 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4932 return None; 4933 } 4934 4935 return Rewrite; 4936 } 4937 4938 // FIXME: This utility is currently required because the Rewriter currently 4939 // does not rewrite this expression: 4940 // {0, +, (sext ix (trunc iy to ix) to iy)} 4941 // into {0, +, %step}, 4942 // even when the following Equal predicate exists: 4943 // "%step == (sext ix (trunc iy to ix) to iy)". 4944 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4945 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4946 if (AR1 == AR2) 4947 return true; 4948 4949 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4950 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4951 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4952 return false; 4953 return true; 4954 }; 4955 4956 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4957 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4958 return false; 4959 return true; 4960 } 4961 4962 /// A helper function for createAddRecFromPHI to handle simple cases. 4963 /// 4964 /// This function tries to find an AddRec expression for the simplest (yet most 4965 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4966 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4967 /// technique for finding the AddRec expression. 4968 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4969 Value *BEValueV, 4970 Value *StartValueV) { 4971 const Loop *L = LI.getLoopFor(PN->getParent()); 4972 assert(L && L->getHeader() == PN->getParent()); 4973 assert(BEValueV && StartValueV); 4974 4975 auto BO = MatchBinaryOp(BEValueV, DT); 4976 if (!BO) 4977 return nullptr; 4978 4979 if (BO->Opcode != Instruction::Add) 4980 return nullptr; 4981 4982 const SCEV *Accum = nullptr; 4983 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4984 Accum = getSCEV(BO->RHS); 4985 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4986 Accum = getSCEV(BO->LHS); 4987 4988 if (!Accum) 4989 return nullptr; 4990 4991 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4992 if (BO->IsNUW) 4993 Flags = setFlags(Flags, SCEV::FlagNUW); 4994 if (BO->IsNSW) 4995 Flags = setFlags(Flags, SCEV::FlagNSW); 4996 4997 const SCEV *StartVal = getSCEV(StartValueV); 4998 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4999 5000 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5001 5002 // We can add Flags to the post-inc expression only if we 5003 // know that it is *undefined behavior* for BEValueV to 5004 // overflow. 5005 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5006 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5007 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5008 5009 return PHISCEV; 5010 } 5011 5012 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5013 const Loop *L = LI.getLoopFor(PN->getParent()); 5014 if (!L || L->getHeader() != PN->getParent()) 5015 return nullptr; 5016 5017 // The loop may have multiple entrances or multiple exits; we can analyze 5018 // this phi as an addrec if it has a unique entry value and a unique 5019 // backedge value. 5020 Value *BEValueV = nullptr, *StartValueV = nullptr; 5021 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5022 Value *V = PN->getIncomingValue(i); 5023 if (L->contains(PN->getIncomingBlock(i))) { 5024 if (!BEValueV) { 5025 BEValueV = V; 5026 } else if (BEValueV != V) { 5027 BEValueV = nullptr; 5028 break; 5029 } 5030 } else if (!StartValueV) { 5031 StartValueV = V; 5032 } else if (StartValueV != V) { 5033 StartValueV = nullptr; 5034 break; 5035 } 5036 } 5037 if (!BEValueV || !StartValueV) 5038 return nullptr; 5039 5040 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5041 "PHI node already processed?"); 5042 5043 // First, try to find AddRec expression without creating a fictituos symbolic 5044 // value for PN. 5045 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5046 return S; 5047 5048 // Handle PHI node value symbolically. 5049 const SCEV *SymbolicName = getUnknown(PN); 5050 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5051 5052 // Using this symbolic name for the PHI, analyze the value coming around 5053 // the back-edge. 5054 const SCEV *BEValue = getSCEV(BEValueV); 5055 5056 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5057 // has a special value for the first iteration of the loop. 5058 5059 // If the value coming around the backedge is an add with the symbolic 5060 // value we just inserted, then we found a simple induction variable! 5061 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5062 // If there is a single occurrence of the symbolic value, replace it 5063 // with a recurrence. 5064 unsigned FoundIndex = Add->getNumOperands(); 5065 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5066 if (Add->getOperand(i) == SymbolicName) 5067 if (FoundIndex == e) { 5068 FoundIndex = i; 5069 break; 5070 } 5071 5072 if (FoundIndex != Add->getNumOperands()) { 5073 // Create an add with everything but the specified operand. 5074 SmallVector<const SCEV *, 8> Ops; 5075 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5076 if (i != FoundIndex) 5077 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5078 L, *this)); 5079 const SCEV *Accum = getAddExpr(Ops); 5080 5081 // This is not a valid addrec if the step amount is varying each 5082 // loop iteration, but is not itself an addrec in this loop. 5083 if (isLoopInvariant(Accum, L) || 5084 (isa<SCEVAddRecExpr>(Accum) && 5085 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5086 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5087 5088 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5089 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5090 if (BO->IsNUW) 5091 Flags = setFlags(Flags, SCEV::FlagNUW); 5092 if (BO->IsNSW) 5093 Flags = setFlags(Flags, SCEV::FlagNSW); 5094 } 5095 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5096 // If the increment is an inbounds GEP, then we know the address 5097 // space cannot be wrapped around. We cannot make any guarantee 5098 // about signed or unsigned overflow because pointers are 5099 // unsigned but we may have a negative index from the base 5100 // pointer. We can guarantee that no unsigned wrap occurs if the 5101 // indices form a positive value. 5102 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5103 Flags = setFlags(Flags, SCEV::FlagNW); 5104 5105 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5106 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5107 Flags = setFlags(Flags, SCEV::FlagNUW); 5108 } 5109 5110 // We cannot transfer nuw and nsw flags from subtraction 5111 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5112 // for instance. 5113 } 5114 5115 const SCEV *StartVal = getSCEV(StartValueV); 5116 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5117 5118 // Okay, for the entire analysis of this edge we assumed the PHI 5119 // to be symbolic. We now need to go back and purge all of the 5120 // entries for the scalars that use the symbolic expression. 5121 forgetSymbolicName(PN, SymbolicName); 5122 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5123 5124 // We can add Flags to the post-inc expression only if we 5125 // know that it is *undefined behavior* for BEValueV to 5126 // overflow. 5127 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5128 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5129 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5130 5131 return PHISCEV; 5132 } 5133 } 5134 } else { 5135 // Otherwise, this could be a loop like this: 5136 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5137 // In this case, j = {1,+,1} and BEValue is j. 5138 // Because the other in-value of i (0) fits the evolution of BEValue 5139 // i really is an addrec evolution. 5140 // 5141 // We can generalize this saying that i is the shifted value of BEValue 5142 // by one iteration: 5143 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5144 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5145 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5146 if (Shifted != getCouldNotCompute() && 5147 Start != getCouldNotCompute()) { 5148 const SCEV *StartVal = getSCEV(StartValueV); 5149 if (Start == StartVal) { 5150 // Okay, for the entire analysis of this edge we assumed the PHI 5151 // to be symbolic. We now need to go back and purge all of the 5152 // entries for the scalars that use the symbolic expression. 5153 forgetSymbolicName(PN, SymbolicName); 5154 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5155 return Shifted; 5156 } 5157 } 5158 } 5159 5160 // Remove the temporary PHI node SCEV that has been inserted while intending 5161 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5162 // as it will prevent later (possibly simpler) SCEV expressions to be added 5163 // to the ValueExprMap. 5164 eraseValueFromMap(PN); 5165 5166 return nullptr; 5167 } 5168 5169 // Checks if the SCEV S is available at BB. S is considered available at BB 5170 // if S can be materialized at BB without introducing a fault. 5171 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5172 BasicBlock *BB) { 5173 struct CheckAvailable { 5174 bool TraversalDone = false; 5175 bool Available = true; 5176 5177 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5178 BasicBlock *BB = nullptr; 5179 DominatorTree &DT; 5180 5181 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5182 : L(L), BB(BB), DT(DT) {} 5183 5184 bool setUnavailable() { 5185 TraversalDone = true; 5186 Available = false; 5187 return false; 5188 } 5189 5190 bool follow(const SCEV *S) { 5191 switch (S->getSCEVType()) { 5192 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5193 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5194 case scUMinExpr: 5195 case scSMinExpr: 5196 // These expressions are available if their operand(s) is/are. 5197 return true; 5198 5199 case scAddRecExpr: { 5200 // We allow add recurrences that are on the loop BB is in, or some 5201 // outer loop. This guarantees availability because the value of the 5202 // add recurrence at BB is simply the "current" value of the induction 5203 // variable. We can relax this in the future; for instance an add 5204 // recurrence on a sibling dominating loop is also available at BB. 5205 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5206 if (L && (ARLoop == L || ARLoop->contains(L))) 5207 return true; 5208 5209 return setUnavailable(); 5210 } 5211 5212 case scUnknown: { 5213 // For SCEVUnknown, we check for simple dominance. 5214 const auto *SU = cast<SCEVUnknown>(S); 5215 Value *V = SU->getValue(); 5216 5217 if (isa<Argument>(V)) 5218 return false; 5219 5220 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5221 return false; 5222 5223 return setUnavailable(); 5224 } 5225 5226 case scUDivExpr: 5227 case scCouldNotCompute: 5228 // We do not try to smart about these at all. 5229 return setUnavailable(); 5230 } 5231 llvm_unreachable("switch should be fully covered!"); 5232 } 5233 5234 bool isDone() { return TraversalDone; } 5235 }; 5236 5237 CheckAvailable CA(L, BB, DT); 5238 SCEVTraversal<CheckAvailable> ST(CA); 5239 5240 ST.visitAll(S); 5241 return CA.Available; 5242 } 5243 5244 // Try to match a control flow sequence that branches out at BI and merges back 5245 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5246 // match. 5247 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5248 Value *&C, Value *&LHS, Value *&RHS) { 5249 C = BI->getCondition(); 5250 5251 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5252 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5253 5254 if (!LeftEdge.isSingleEdge()) 5255 return false; 5256 5257 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5258 5259 Use &LeftUse = Merge->getOperandUse(0); 5260 Use &RightUse = Merge->getOperandUse(1); 5261 5262 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5263 LHS = LeftUse; 5264 RHS = RightUse; 5265 return true; 5266 } 5267 5268 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5269 LHS = RightUse; 5270 RHS = LeftUse; 5271 return true; 5272 } 5273 5274 return false; 5275 } 5276 5277 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5278 auto IsReachable = 5279 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5280 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5281 const Loop *L = LI.getLoopFor(PN->getParent()); 5282 5283 // We don't want to break LCSSA, even in a SCEV expression tree. 5284 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5285 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5286 return nullptr; 5287 5288 // Try to match 5289 // 5290 // br %cond, label %left, label %right 5291 // left: 5292 // br label %merge 5293 // right: 5294 // br label %merge 5295 // merge: 5296 // V = phi [ %x, %left ], [ %y, %right ] 5297 // 5298 // as "select %cond, %x, %y" 5299 5300 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5301 assert(IDom && "At least the entry block should dominate PN"); 5302 5303 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5304 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5305 5306 if (BI && BI->isConditional() && 5307 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5308 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5309 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5310 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5311 } 5312 5313 return nullptr; 5314 } 5315 5316 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5317 if (const SCEV *S = createAddRecFromPHI(PN)) 5318 return S; 5319 5320 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5321 return S; 5322 5323 // If the PHI has a single incoming value, follow that value, unless the 5324 // PHI's incoming blocks are in a different loop, in which case doing so 5325 // risks breaking LCSSA form. Instcombine would normally zap these, but 5326 // it doesn't have DominatorTree information, so it may miss cases. 5327 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5328 if (LI.replacementPreservesLCSSAForm(PN, V)) 5329 return getSCEV(V); 5330 5331 // If it's not a loop phi, we can't handle it yet. 5332 return getUnknown(PN); 5333 } 5334 5335 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5336 Value *Cond, 5337 Value *TrueVal, 5338 Value *FalseVal) { 5339 // Handle "constant" branch or select. This can occur for instance when a 5340 // loop pass transforms an inner loop and moves on to process the outer loop. 5341 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5342 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5343 5344 // Try to match some simple smax or umax patterns. 5345 auto *ICI = dyn_cast<ICmpInst>(Cond); 5346 if (!ICI) 5347 return getUnknown(I); 5348 5349 Value *LHS = ICI->getOperand(0); 5350 Value *RHS = ICI->getOperand(1); 5351 5352 switch (ICI->getPredicate()) { 5353 case ICmpInst::ICMP_SLT: 5354 case ICmpInst::ICMP_SLE: 5355 std::swap(LHS, RHS); 5356 LLVM_FALLTHROUGH; 5357 case ICmpInst::ICMP_SGT: 5358 case ICmpInst::ICMP_SGE: 5359 // a >s b ? a+x : b+x -> smax(a, b)+x 5360 // a >s b ? b+x : a+x -> smin(a, b)+x 5361 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5362 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5363 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5364 const SCEV *LA = getSCEV(TrueVal); 5365 const SCEV *RA = getSCEV(FalseVal); 5366 const SCEV *LDiff = getMinusSCEV(LA, LS); 5367 const SCEV *RDiff = getMinusSCEV(RA, RS); 5368 if (LDiff == RDiff) 5369 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5370 LDiff = getMinusSCEV(LA, RS); 5371 RDiff = getMinusSCEV(RA, LS); 5372 if (LDiff == RDiff) 5373 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5374 } 5375 break; 5376 case ICmpInst::ICMP_ULT: 5377 case ICmpInst::ICMP_ULE: 5378 std::swap(LHS, RHS); 5379 LLVM_FALLTHROUGH; 5380 case ICmpInst::ICMP_UGT: 5381 case ICmpInst::ICMP_UGE: 5382 // a >u b ? a+x : b+x -> umax(a, b)+x 5383 // a >u b ? b+x : a+x -> umin(a, b)+x 5384 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5385 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5386 const SCEV *RS = getNoopOrZeroExtend(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(getUMaxExpr(LS, RS), LDiff); 5393 LDiff = getMinusSCEV(LA, RS); 5394 RDiff = getMinusSCEV(RA, LS); 5395 if (LDiff == RDiff) 5396 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5397 } 5398 break; 5399 case ICmpInst::ICMP_NE: 5400 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5401 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5402 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5403 const SCEV *One = getOne(I->getType()); 5404 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5405 const SCEV *LA = getSCEV(TrueVal); 5406 const SCEV *RA = getSCEV(FalseVal); 5407 const SCEV *LDiff = getMinusSCEV(LA, LS); 5408 const SCEV *RDiff = getMinusSCEV(RA, One); 5409 if (LDiff == RDiff) 5410 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5411 } 5412 break; 5413 case ICmpInst::ICMP_EQ: 5414 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5415 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5416 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5417 const SCEV *One = getOne(I->getType()); 5418 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5419 const SCEV *LA = getSCEV(TrueVal); 5420 const SCEV *RA = getSCEV(FalseVal); 5421 const SCEV *LDiff = getMinusSCEV(LA, One); 5422 const SCEV *RDiff = getMinusSCEV(RA, LS); 5423 if (LDiff == RDiff) 5424 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5425 } 5426 break; 5427 default: 5428 break; 5429 } 5430 5431 return getUnknown(I); 5432 } 5433 5434 /// Expand GEP instructions into add and multiply operations. This allows them 5435 /// to be analyzed by regular SCEV code. 5436 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5437 // Don't attempt to analyze GEPs over unsized objects. 5438 if (!GEP->getSourceElementType()->isSized()) 5439 return getUnknown(GEP); 5440 5441 SmallVector<const SCEV *, 4> IndexExprs; 5442 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5443 IndexExprs.push_back(getSCEV(*Index)); 5444 return getGEPExpr(GEP, IndexExprs); 5445 } 5446 5447 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5448 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5449 return C->getAPInt().countTrailingZeros(); 5450 5451 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5452 return std::min(GetMinTrailingZeros(T->getOperand()), 5453 (uint32_t)getTypeSizeInBits(T->getType())); 5454 5455 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5456 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5457 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5458 ? getTypeSizeInBits(E->getType()) 5459 : OpRes; 5460 } 5461 5462 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5463 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5464 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5465 ? getTypeSizeInBits(E->getType()) 5466 : OpRes; 5467 } 5468 5469 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5470 // The result is the min of all operands results. 5471 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5472 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5473 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5474 return MinOpRes; 5475 } 5476 5477 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5478 // The result is the sum of all operands results. 5479 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5480 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5481 for (unsigned i = 1, e = M->getNumOperands(); 5482 SumOpRes != BitWidth && i != e; ++i) 5483 SumOpRes = 5484 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5485 return SumOpRes; 5486 } 5487 5488 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5489 // The result is the min of all operands results. 5490 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5491 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5492 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5493 return MinOpRes; 5494 } 5495 5496 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5497 // The result is the min of all operands results. 5498 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5499 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5500 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5501 return MinOpRes; 5502 } 5503 5504 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5505 // The result is the min of all operands results. 5506 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5507 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5508 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5509 return MinOpRes; 5510 } 5511 5512 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5513 // For a SCEVUnknown, ask ValueTracking. 5514 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5515 return Known.countMinTrailingZeros(); 5516 } 5517 5518 // SCEVUDivExpr 5519 return 0; 5520 } 5521 5522 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5523 auto I = MinTrailingZerosCache.find(S); 5524 if (I != MinTrailingZerosCache.end()) 5525 return I->second; 5526 5527 uint32_t Result = GetMinTrailingZerosImpl(S); 5528 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5529 assert(InsertPair.second && "Should insert a new key"); 5530 return InsertPair.first->second; 5531 } 5532 5533 /// Helper method to assign a range to V from metadata present in the IR. 5534 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5535 if (Instruction *I = dyn_cast<Instruction>(V)) 5536 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5537 return getConstantRangeFromMetadata(*MD); 5538 5539 return None; 5540 } 5541 5542 /// Determine the range for a particular SCEV. If SignHint is 5543 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5544 /// with a "cleaner" unsigned (resp. signed) representation. 5545 const ConstantRange & 5546 ScalarEvolution::getRangeRef(const SCEV *S, 5547 ScalarEvolution::RangeSignHint SignHint) { 5548 DenseMap<const SCEV *, ConstantRange> &Cache = 5549 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5550 : SignedRanges; 5551 ConstantRange::PreferredRangeType RangeType = 5552 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5553 ? ConstantRange::Unsigned : ConstantRange::Signed; 5554 5555 // See if we've computed this range already. 5556 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5557 if (I != Cache.end()) 5558 return I->second; 5559 5560 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5561 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5562 5563 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5564 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5565 using OBO = OverflowingBinaryOperator; 5566 5567 // If the value has known zeros, the maximum value will have those known zeros 5568 // as well. 5569 uint32_t TZ = GetMinTrailingZeros(S); 5570 if (TZ != 0) { 5571 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5572 ConservativeResult = 5573 ConstantRange(APInt::getMinValue(BitWidth), 5574 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5575 else 5576 ConservativeResult = ConstantRange( 5577 APInt::getSignedMinValue(BitWidth), 5578 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5579 } 5580 5581 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5582 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5583 unsigned WrapType = OBO::AnyWrap; 5584 if (Add->hasNoSignedWrap()) 5585 WrapType |= OBO::NoSignedWrap; 5586 if (Add->hasNoUnsignedWrap()) 5587 WrapType |= OBO::NoUnsignedWrap; 5588 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5589 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5590 WrapType, RangeType); 5591 return setRange(Add, SignHint, 5592 ConservativeResult.intersectWith(X, RangeType)); 5593 } 5594 5595 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5596 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5597 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5598 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5599 return setRange(Mul, SignHint, 5600 ConservativeResult.intersectWith(X, RangeType)); 5601 } 5602 5603 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5604 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5605 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5606 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5607 return setRange(SMax, SignHint, 5608 ConservativeResult.intersectWith(X, RangeType)); 5609 } 5610 5611 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5612 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5613 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5614 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5615 return setRange(UMax, SignHint, 5616 ConservativeResult.intersectWith(X, RangeType)); 5617 } 5618 5619 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5620 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5621 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5622 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5623 return setRange(SMin, SignHint, 5624 ConservativeResult.intersectWith(X, RangeType)); 5625 } 5626 5627 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5628 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5629 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5630 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5631 return setRange(UMin, SignHint, 5632 ConservativeResult.intersectWith(X, RangeType)); 5633 } 5634 5635 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5636 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5637 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5638 return setRange(UDiv, SignHint, 5639 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5640 } 5641 5642 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5643 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5644 return setRange(ZExt, SignHint, 5645 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5646 RangeType)); 5647 } 5648 5649 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5650 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5651 return setRange(SExt, SignHint, 5652 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5653 RangeType)); 5654 } 5655 5656 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5657 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5658 return setRange(Trunc, SignHint, 5659 ConservativeResult.intersectWith(X.truncate(BitWidth), 5660 RangeType)); 5661 } 5662 5663 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5664 // If there's no unsigned wrap, the value will never be less than its 5665 // initial value. 5666 if (AddRec->hasNoUnsignedWrap()) { 5667 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5668 if (!UnsignedMinValue.isNullValue()) 5669 ConservativeResult = ConservativeResult.intersectWith( 5670 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5671 } 5672 5673 // If there's no signed wrap, and all the operands except initial value have 5674 // the same sign or zero, the value won't ever be: 5675 // 1: smaller than initial value if operands are non negative, 5676 // 2: bigger than initial value if operands are non positive. 5677 // For both cases, value can not cross signed min/max boundary. 5678 if (AddRec->hasNoSignedWrap()) { 5679 bool AllNonNeg = true; 5680 bool AllNonPos = true; 5681 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5682 if (!isKnownNonNegative(AddRec->getOperand(i))) 5683 AllNonNeg = false; 5684 if (!isKnownNonPositive(AddRec->getOperand(i))) 5685 AllNonPos = false; 5686 } 5687 if (AllNonNeg) 5688 ConservativeResult = ConservativeResult.intersectWith( 5689 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5690 APInt::getSignedMinValue(BitWidth)), 5691 RangeType); 5692 else if (AllNonPos) 5693 ConservativeResult = ConservativeResult.intersectWith( 5694 ConstantRange::getNonEmpty( 5695 APInt::getSignedMinValue(BitWidth), 5696 getSignedRangeMax(AddRec->getStart()) + 1), 5697 RangeType); 5698 } 5699 5700 // TODO: non-affine addrec 5701 if (AddRec->isAffine()) { 5702 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5703 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5704 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5705 auto RangeFromAffine = getRangeForAffineAR( 5706 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5707 BitWidth); 5708 if (!RangeFromAffine.isFullSet()) 5709 ConservativeResult = 5710 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5711 5712 auto RangeFromFactoring = getRangeViaFactoring( 5713 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5714 BitWidth); 5715 if (!RangeFromFactoring.isFullSet()) 5716 ConservativeResult = 5717 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5718 } 5719 } 5720 5721 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5722 } 5723 5724 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5725 // Check if the IR explicitly contains !range metadata. 5726 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5727 if (MDRange.hasValue()) 5728 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5729 RangeType); 5730 5731 // Split here to avoid paying the compile-time cost of calling both 5732 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5733 // if needed. 5734 const DataLayout &DL = getDataLayout(); 5735 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5736 // For a SCEVUnknown, ask ValueTracking. 5737 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5738 if (Known.getBitWidth() != BitWidth) 5739 Known = Known.zextOrTrunc(BitWidth); 5740 // If Known does not result in full-set, intersect with it. 5741 if (Known.getMinValue() != Known.getMaxValue() + 1) 5742 ConservativeResult = ConservativeResult.intersectWith( 5743 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5744 RangeType); 5745 } else { 5746 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5747 "generalize as needed!"); 5748 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5749 // If the pointer size is larger than the index size type, this can cause 5750 // NS to be larger than BitWidth. So compensate for this. 5751 if (U->getType()->isPointerTy()) { 5752 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5753 int ptrIdxDiff = ptrSize - BitWidth; 5754 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5755 NS -= ptrIdxDiff; 5756 } 5757 5758 if (NS > 1) 5759 ConservativeResult = ConservativeResult.intersectWith( 5760 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5761 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5762 RangeType); 5763 } 5764 5765 // A range of Phi is a subset of union of all ranges of its input. 5766 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5767 // Make sure that we do not run over cycled Phis. 5768 if (PendingPhiRanges.insert(Phi).second) { 5769 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5770 for (auto &Op : Phi->operands()) { 5771 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5772 RangeFromOps = RangeFromOps.unionWith(OpRange); 5773 // No point to continue if we already have a full set. 5774 if (RangeFromOps.isFullSet()) 5775 break; 5776 } 5777 ConservativeResult = 5778 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5779 bool Erased = PendingPhiRanges.erase(Phi); 5780 assert(Erased && "Failed to erase Phi properly?"); 5781 (void) Erased; 5782 } 5783 } 5784 5785 return setRange(U, SignHint, std::move(ConservativeResult)); 5786 } 5787 5788 return setRange(S, SignHint, std::move(ConservativeResult)); 5789 } 5790 5791 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5792 // values that the expression can take. Initially, the expression has a value 5793 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5794 // argument defines if we treat Step as signed or unsigned. 5795 static ConstantRange getRangeForAffineARHelper(APInt Step, 5796 const ConstantRange &StartRange, 5797 const APInt &MaxBECount, 5798 unsigned BitWidth, bool Signed) { 5799 // If either Step or MaxBECount is 0, then the expression won't change, and we 5800 // just need to return the initial range. 5801 if (Step == 0 || MaxBECount == 0) 5802 return StartRange; 5803 5804 // If we don't know anything about the initial value (i.e. StartRange is 5805 // FullRange), then we don't know anything about the final range either. 5806 // Return FullRange. 5807 if (StartRange.isFullSet()) 5808 return ConstantRange::getFull(BitWidth); 5809 5810 // If Step is signed and negative, then we use its absolute value, but we also 5811 // note that we're moving in the opposite direction. 5812 bool Descending = Signed && Step.isNegative(); 5813 5814 if (Signed) 5815 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5816 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5817 // This equations hold true due to the well-defined wrap-around behavior of 5818 // APInt. 5819 Step = Step.abs(); 5820 5821 // Check if Offset is more than full span of BitWidth. If it is, the 5822 // expression is guaranteed to overflow. 5823 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5824 return ConstantRange::getFull(BitWidth); 5825 5826 // Offset is by how much the expression can change. Checks above guarantee no 5827 // overflow here. 5828 APInt Offset = Step * MaxBECount; 5829 5830 // Minimum value of the final range will match the minimal value of StartRange 5831 // if the expression is increasing and will be decreased by Offset otherwise. 5832 // Maximum value of the final range will match the maximal value of StartRange 5833 // if the expression is decreasing and will be increased by Offset otherwise. 5834 APInt StartLower = StartRange.getLower(); 5835 APInt StartUpper = StartRange.getUpper() - 1; 5836 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5837 : (StartUpper + std::move(Offset)); 5838 5839 // It's possible that the new minimum/maximum value will fall into the initial 5840 // range (due to wrap around). This means that the expression can take any 5841 // value in this bitwidth, and we have to return full range. 5842 if (StartRange.contains(MovedBoundary)) 5843 return ConstantRange::getFull(BitWidth); 5844 5845 APInt NewLower = 5846 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5847 APInt NewUpper = 5848 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5849 NewUpper += 1; 5850 5851 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5852 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5853 } 5854 5855 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5856 const SCEV *Step, 5857 const SCEV *MaxBECount, 5858 unsigned BitWidth) { 5859 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5860 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5861 "Precondition!"); 5862 5863 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5864 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5865 5866 // First, consider step signed. 5867 ConstantRange StartSRange = getSignedRange(Start); 5868 ConstantRange StepSRange = getSignedRange(Step); 5869 5870 // If Step can be both positive and negative, we need to find ranges for the 5871 // maximum absolute step values in both directions and union them. 5872 ConstantRange SR = 5873 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5874 MaxBECountValue, BitWidth, /* Signed = */ true); 5875 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5876 StartSRange, MaxBECountValue, 5877 BitWidth, /* Signed = */ true)); 5878 5879 // Next, consider step unsigned. 5880 ConstantRange UR = getRangeForAffineARHelper( 5881 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5882 MaxBECountValue, BitWidth, /* Signed = */ false); 5883 5884 // Finally, intersect signed and unsigned ranges. 5885 return SR.intersectWith(UR, ConstantRange::Smallest); 5886 } 5887 5888 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5889 const SCEV *Step, 5890 const SCEV *MaxBECount, 5891 unsigned BitWidth) { 5892 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5893 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5894 5895 struct SelectPattern { 5896 Value *Condition = nullptr; 5897 APInt TrueValue; 5898 APInt FalseValue; 5899 5900 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5901 const SCEV *S) { 5902 Optional<unsigned> CastOp; 5903 APInt Offset(BitWidth, 0); 5904 5905 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5906 "Should be!"); 5907 5908 // Peel off a constant offset: 5909 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5910 // In the future we could consider being smarter here and handle 5911 // {Start+Step,+,Step} too. 5912 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5913 return; 5914 5915 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5916 S = SA->getOperand(1); 5917 } 5918 5919 // Peel off a cast operation 5920 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5921 CastOp = SCast->getSCEVType(); 5922 S = SCast->getOperand(); 5923 } 5924 5925 using namespace llvm::PatternMatch; 5926 5927 auto *SU = dyn_cast<SCEVUnknown>(S); 5928 const APInt *TrueVal, *FalseVal; 5929 if (!SU || 5930 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5931 m_APInt(FalseVal)))) { 5932 Condition = nullptr; 5933 return; 5934 } 5935 5936 TrueValue = *TrueVal; 5937 FalseValue = *FalseVal; 5938 5939 // Re-apply the cast we peeled off earlier 5940 if (CastOp.hasValue()) 5941 switch (*CastOp) { 5942 default: 5943 llvm_unreachable("Unknown SCEV cast type!"); 5944 5945 case scTruncate: 5946 TrueValue = TrueValue.trunc(BitWidth); 5947 FalseValue = FalseValue.trunc(BitWidth); 5948 break; 5949 case scZeroExtend: 5950 TrueValue = TrueValue.zext(BitWidth); 5951 FalseValue = FalseValue.zext(BitWidth); 5952 break; 5953 case scSignExtend: 5954 TrueValue = TrueValue.sext(BitWidth); 5955 FalseValue = FalseValue.sext(BitWidth); 5956 break; 5957 } 5958 5959 // Re-apply the constant offset we peeled off earlier 5960 TrueValue += Offset; 5961 FalseValue += Offset; 5962 } 5963 5964 bool isRecognized() { return Condition != nullptr; } 5965 }; 5966 5967 SelectPattern StartPattern(*this, BitWidth, Start); 5968 if (!StartPattern.isRecognized()) 5969 return ConstantRange::getFull(BitWidth); 5970 5971 SelectPattern StepPattern(*this, BitWidth, Step); 5972 if (!StepPattern.isRecognized()) 5973 return ConstantRange::getFull(BitWidth); 5974 5975 if (StartPattern.Condition != StepPattern.Condition) { 5976 // We don't handle this case today; but we could, by considering four 5977 // possibilities below instead of two. I'm not sure if there are cases where 5978 // that will help over what getRange already does, though. 5979 return ConstantRange::getFull(BitWidth); 5980 } 5981 5982 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5983 // construct arbitrary general SCEV expressions here. This function is called 5984 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5985 // say) can end up caching a suboptimal value. 5986 5987 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5988 // C2352 and C2512 (otherwise it isn't needed). 5989 5990 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5991 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5992 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5993 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5994 5995 ConstantRange TrueRange = 5996 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5997 ConstantRange FalseRange = 5998 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5999 6000 return TrueRange.unionWith(FalseRange); 6001 } 6002 6003 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6004 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6005 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6006 6007 // Return early if there are no flags to propagate to the SCEV. 6008 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6009 if (BinOp->hasNoUnsignedWrap()) 6010 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6011 if (BinOp->hasNoSignedWrap()) 6012 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6013 if (Flags == SCEV::FlagAnyWrap) 6014 return SCEV::FlagAnyWrap; 6015 6016 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6017 } 6018 6019 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6020 // Here we check that I is in the header of the innermost loop containing I, 6021 // since we only deal with instructions in the loop header. The actual loop we 6022 // need to check later will come from an add recurrence, but getting that 6023 // requires computing the SCEV of the operands, which can be expensive. This 6024 // check we can do cheaply to rule out some cases early. 6025 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6026 if (InnermostContainingLoop == nullptr || 6027 InnermostContainingLoop->getHeader() != I->getParent()) 6028 return false; 6029 6030 // Only proceed if we can prove that I does not yield poison. 6031 if (!programUndefinedIfFullPoison(I)) 6032 return false; 6033 6034 // At this point we know that if I is executed, then it does not wrap 6035 // according to at least one of NSW or NUW. If I is not executed, then we do 6036 // not know if the calculation that I represents would wrap. Multiple 6037 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6038 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6039 // derived from other instructions that map to the same SCEV. We cannot make 6040 // that guarantee for cases where I is not executed. So we need to find the 6041 // loop that I is considered in relation to and prove that I is executed for 6042 // every iteration of that loop. That implies that the value that I 6043 // calculates does not wrap anywhere in the loop, so then we can apply the 6044 // flags to the SCEV. 6045 // 6046 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6047 // from different loops, so that we know which loop to prove that I is 6048 // executed in. 6049 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6050 // I could be an extractvalue from a call to an overflow intrinsic. 6051 // TODO: We can do better here in some cases. 6052 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6053 return false; 6054 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6055 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6056 bool AllOtherOpsLoopInvariant = true; 6057 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6058 ++OtherOpIndex) { 6059 if (OtherOpIndex != OpIndex) { 6060 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6061 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6062 AllOtherOpsLoopInvariant = false; 6063 break; 6064 } 6065 } 6066 } 6067 if (AllOtherOpsLoopInvariant && 6068 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6069 return true; 6070 } 6071 } 6072 return false; 6073 } 6074 6075 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6076 // If we know that \c I can never be poison period, then that's enough. 6077 if (isSCEVExprNeverPoison(I)) 6078 return true; 6079 6080 // For an add recurrence specifically, we assume that infinite loops without 6081 // side effects are undefined behavior, and then reason as follows: 6082 // 6083 // If the add recurrence is poison in any iteration, it is poison on all 6084 // future iterations (since incrementing poison yields poison). If the result 6085 // of the add recurrence is fed into the loop latch condition and the loop 6086 // does not contain any throws or exiting blocks other than the latch, we now 6087 // have the ability to "choose" whether the backedge is taken or not (by 6088 // choosing a sufficiently evil value for the poison feeding into the branch) 6089 // for every iteration including and after the one in which \p I first became 6090 // poison. There are two possibilities (let's call the iteration in which \p 6091 // I first became poison as K): 6092 // 6093 // 1. In the set of iterations including and after K, the loop body executes 6094 // no side effects. In this case executing the backege an infinte number 6095 // of times will yield undefined behavior. 6096 // 6097 // 2. In the set of iterations including and after K, the loop body executes 6098 // at least one side effect. In this case, that specific instance of side 6099 // effect is control dependent on poison, which also yields undefined 6100 // behavior. 6101 6102 auto *ExitingBB = L->getExitingBlock(); 6103 auto *LatchBB = L->getLoopLatch(); 6104 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6105 return false; 6106 6107 SmallPtrSet<const Instruction *, 16> Pushed; 6108 SmallVector<const Instruction *, 8> PoisonStack; 6109 6110 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6111 // things that are known to be fully poison under that assumption go on the 6112 // PoisonStack. 6113 Pushed.insert(I); 6114 PoisonStack.push_back(I); 6115 6116 bool LatchControlDependentOnPoison = false; 6117 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6118 const Instruction *Poison = PoisonStack.pop_back_val(); 6119 6120 for (auto *PoisonUser : Poison->users()) { 6121 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6122 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6123 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6124 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6125 assert(BI->isConditional() && "Only possibility!"); 6126 if (BI->getParent() == LatchBB) { 6127 LatchControlDependentOnPoison = true; 6128 break; 6129 } 6130 } 6131 } 6132 } 6133 6134 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6135 } 6136 6137 ScalarEvolution::LoopProperties 6138 ScalarEvolution::getLoopProperties(const Loop *L) { 6139 using LoopProperties = ScalarEvolution::LoopProperties; 6140 6141 auto Itr = LoopPropertiesCache.find(L); 6142 if (Itr == LoopPropertiesCache.end()) { 6143 auto HasSideEffects = [](Instruction *I) { 6144 if (auto *SI = dyn_cast<StoreInst>(I)) 6145 return !SI->isSimple(); 6146 6147 return I->mayHaveSideEffects(); 6148 }; 6149 6150 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6151 /*HasNoSideEffects*/ true}; 6152 6153 for (auto *BB : L->getBlocks()) 6154 for (auto &I : *BB) { 6155 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6156 LP.HasNoAbnormalExits = false; 6157 if (HasSideEffects(&I)) 6158 LP.HasNoSideEffects = false; 6159 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6160 break; // We're already as pessimistic as we can get. 6161 } 6162 6163 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6164 assert(InsertPair.second && "We just checked!"); 6165 Itr = InsertPair.first; 6166 } 6167 6168 return Itr->second; 6169 } 6170 6171 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6172 if (!isSCEVable(V->getType())) 6173 return getUnknown(V); 6174 6175 if (Instruction *I = dyn_cast<Instruction>(V)) { 6176 // Don't attempt to analyze instructions in blocks that aren't 6177 // reachable. Such instructions don't matter, and they aren't required 6178 // to obey basic rules for definitions dominating uses which this 6179 // analysis depends on. 6180 if (!DT.isReachableFromEntry(I->getParent())) 6181 return getUnknown(UndefValue::get(V->getType())); 6182 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6183 return getConstant(CI); 6184 else if (isa<ConstantPointerNull>(V)) 6185 return getZero(V->getType()); 6186 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6187 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6188 else if (!isa<ConstantExpr>(V)) 6189 return getUnknown(V); 6190 6191 Operator *U = cast<Operator>(V); 6192 if (auto BO = MatchBinaryOp(U, DT)) { 6193 switch (BO->Opcode) { 6194 case Instruction::Add: { 6195 // The simple thing to do would be to just call getSCEV on both operands 6196 // and call getAddExpr with the result. However if we're looking at a 6197 // bunch of things all added together, this can be quite inefficient, 6198 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6199 // Instead, gather up all the operands and make a single getAddExpr call. 6200 // LLVM IR canonical form means we need only traverse the left operands. 6201 SmallVector<const SCEV *, 4> AddOps; 6202 do { 6203 if (BO->Op) { 6204 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6205 AddOps.push_back(OpSCEV); 6206 break; 6207 } 6208 6209 // If a NUW or NSW flag can be applied to the SCEV for this 6210 // addition, then compute the SCEV for this addition by itself 6211 // with a separate call to getAddExpr. We need to do that 6212 // instead of pushing the operands of the addition onto AddOps, 6213 // since the flags are only known to apply to this particular 6214 // addition - they may not apply to other additions that can be 6215 // formed with operands from AddOps. 6216 const SCEV *RHS = getSCEV(BO->RHS); 6217 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6218 if (Flags != SCEV::FlagAnyWrap) { 6219 const SCEV *LHS = getSCEV(BO->LHS); 6220 if (BO->Opcode == Instruction::Sub) 6221 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6222 else 6223 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6224 break; 6225 } 6226 } 6227 6228 if (BO->Opcode == Instruction::Sub) 6229 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6230 else 6231 AddOps.push_back(getSCEV(BO->RHS)); 6232 6233 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6234 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6235 NewBO->Opcode != Instruction::Sub)) { 6236 AddOps.push_back(getSCEV(BO->LHS)); 6237 break; 6238 } 6239 BO = NewBO; 6240 } while (true); 6241 6242 return getAddExpr(AddOps); 6243 } 6244 6245 case Instruction::Mul: { 6246 SmallVector<const SCEV *, 4> MulOps; 6247 do { 6248 if (BO->Op) { 6249 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6250 MulOps.push_back(OpSCEV); 6251 break; 6252 } 6253 6254 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6255 if (Flags != SCEV::FlagAnyWrap) { 6256 MulOps.push_back( 6257 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6258 break; 6259 } 6260 } 6261 6262 MulOps.push_back(getSCEV(BO->RHS)); 6263 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6264 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6265 MulOps.push_back(getSCEV(BO->LHS)); 6266 break; 6267 } 6268 BO = NewBO; 6269 } while (true); 6270 6271 return getMulExpr(MulOps); 6272 } 6273 case Instruction::UDiv: 6274 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6275 case Instruction::URem: 6276 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6277 case Instruction::Sub: { 6278 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6279 if (BO->Op) 6280 Flags = getNoWrapFlagsFromUB(BO->Op); 6281 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6282 } 6283 case Instruction::And: 6284 // For an expression like x&255 that merely masks off the high bits, 6285 // use zext(trunc(x)) as the SCEV expression. 6286 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6287 if (CI->isZero()) 6288 return getSCEV(BO->RHS); 6289 if (CI->isMinusOne()) 6290 return getSCEV(BO->LHS); 6291 const APInt &A = CI->getValue(); 6292 6293 // Instcombine's ShrinkDemandedConstant may strip bits out of 6294 // constants, obscuring what would otherwise be a low-bits mask. 6295 // Use computeKnownBits to compute what ShrinkDemandedConstant 6296 // knew about to reconstruct a low-bits mask value. 6297 unsigned LZ = A.countLeadingZeros(); 6298 unsigned TZ = A.countTrailingZeros(); 6299 unsigned BitWidth = A.getBitWidth(); 6300 KnownBits Known(BitWidth); 6301 computeKnownBits(BO->LHS, Known, getDataLayout(), 6302 0, &AC, nullptr, &DT); 6303 6304 APInt EffectiveMask = 6305 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6306 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6307 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6308 const SCEV *LHS = getSCEV(BO->LHS); 6309 const SCEV *ShiftedLHS = nullptr; 6310 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6311 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6312 // For an expression like (x * 8) & 8, simplify the multiply. 6313 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6314 unsigned GCD = std::min(MulZeros, TZ); 6315 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6316 SmallVector<const SCEV*, 4> MulOps; 6317 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6318 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6319 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6320 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6321 } 6322 } 6323 if (!ShiftedLHS) 6324 ShiftedLHS = getUDivExpr(LHS, MulCount); 6325 return getMulExpr( 6326 getZeroExtendExpr( 6327 getTruncateExpr(ShiftedLHS, 6328 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6329 BO->LHS->getType()), 6330 MulCount); 6331 } 6332 } 6333 break; 6334 6335 case Instruction::Or: 6336 // If the RHS of the Or is a constant, we may have something like: 6337 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6338 // optimizations will transparently handle this case. 6339 // 6340 // In order for this transformation to be safe, the LHS must be of the 6341 // form X*(2^n) and the Or constant must be less than 2^n. 6342 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6343 const SCEV *LHS = getSCEV(BO->LHS); 6344 const APInt &CIVal = CI->getValue(); 6345 if (GetMinTrailingZeros(LHS) >= 6346 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6347 // Build a plain add SCEV. 6348 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6349 // If the LHS of the add was an addrec and it has no-wrap flags, 6350 // transfer the no-wrap flags, since an or won't introduce a wrap. 6351 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6352 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6353 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6354 OldAR->getNoWrapFlags()); 6355 } 6356 return S; 6357 } 6358 } 6359 break; 6360 6361 case Instruction::Xor: 6362 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6363 // If the RHS of xor is -1, then this is a not operation. 6364 if (CI->isMinusOne()) 6365 return getNotSCEV(getSCEV(BO->LHS)); 6366 6367 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6368 // This is a variant of the check for xor with -1, and it handles 6369 // the case where instcombine has trimmed non-demanded bits out 6370 // of an xor with -1. 6371 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6372 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6373 if (LBO->getOpcode() == Instruction::And && 6374 LCI->getValue() == CI->getValue()) 6375 if (const SCEVZeroExtendExpr *Z = 6376 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6377 Type *UTy = BO->LHS->getType(); 6378 const SCEV *Z0 = Z->getOperand(); 6379 Type *Z0Ty = Z0->getType(); 6380 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6381 6382 // If C is a low-bits mask, the zero extend is serving to 6383 // mask off the high bits. Complement the operand and 6384 // re-apply the zext. 6385 if (CI->getValue().isMask(Z0TySize)) 6386 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6387 6388 // If C is a single bit, it may be in the sign-bit position 6389 // before the zero-extend. In this case, represent the xor 6390 // using an add, which is equivalent, and re-apply the zext. 6391 APInt Trunc = CI->getValue().trunc(Z0TySize); 6392 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6393 Trunc.isSignMask()) 6394 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6395 UTy); 6396 } 6397 } 6398 break; 6399 6400 case Instruction::Shl: 6401 // Turn shift left of a constant amount into a multiply. 6402 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6403 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6404 6405 // If the shift count is not less than the bitwidth, the result of 6406 // the shift is undefined. Don't try to analyze it, because the 6407 // resolution chosen here may differ from the resolution chosen in 6408 // other parts of the compiler. 6409 if (SA->getValue().uge(BitWidth)) 6410 break; 6411 6412 // It is currently not resolved how to interpret NSW for left 6413 // shift by BitWidth - 1, so we avoid applying flags in that 6414 // case. Remove this check (or this comment) once the situation 6415 // is resolved. See 6416 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6417 // and http://reviews.llvm.org/D8890 . 6418 auto Flags = SCEV::FlagAnyWrap; 6419 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6420 Flags = getNoWrapFlagsFromUB(BO->Op); 6421 6422 Constant *X = ConstantInt::get( 6423 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6424 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6425 } 6426 break; 6427 6428 case Instruction::AShr: { 6429 // AShr X, C, where C is a constant. 6430 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6431 if (!CI) 6432 break; 6433 6434 Type *OuterTy = BO->LHS->getType(); 6435 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6436 // If the shift count is not less than the bitwidth, the result of 6437 // the shift is undefined. Don't try to analyze it, because the 6438 // resolution chosen here may differ from the resolution chosen in 6439 // other parts of the compiler. 6440 if (CI->getValue().uge(BitWidth)) 6441 break; 6442 6443 if (CI->isZero()) 6444 return getSCEV(BO->LHS); // shift by zero --> noop 6445 6446 uint64_t AShrAmt = CI->getZExtValue(); 6447 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6448 6449 Operator *L = dyn_cast<Operator>(BO->LHS); 6450 if (L && L->getOpcode() == Instruction::Shl) { 6451 // X = Shl A, n 6452 // Y = AShr X, m 6453 // Both n and m are constant. 6454 6455 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6456 if (L->getOperand(1) == BO->RHS) 6457 // For a two-shift sext-inreg, i.e. n = m, 6458 // use sext(trunc(x)) as the SCEV expression. 6459 return getSignExtendExpr( 6460 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6461 6462 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6463 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6464 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6465 if (ShlAmt > AShrAmt) { 6466 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6467 // expression. We already checked that ShlAmt < BitWidth, so 6468 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6469 // ShlAmt - AShrAmt < Amt. 6470 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6471 ShlAmt - AShrAmt); 6472 return getSignExtendExpr( 6473 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6474 getConstant(Mul)), OuterTy); 6475 } 6476 } 6477 } 6478 break; 6479 } 6480 } 6481 } 6482 6483 switch (U->getOpcode()) { 6484 case Instruction::Trunc: 6485 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6486 6487 case Instruction::ZExt: 6488 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6489 6490 case Instruction::SExt: 6491 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6492 // The NSW flag of a subtract does not always survive the conversion to 6493 // A + (-1)*B. By pushing sign extension onto its operands we are much 6494 // more likely to preserve NSW and allow later AddRec optimisations. 6495 // 6496 // NOTE: This is effectively duplicating this logic from getSignExtend: 6497 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6498 // but by that point the NSW information has potentially been lost. 6499 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6500 Type *Ty = U->getType(); 6501 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6502 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6503 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6504 } 6505 } 6506 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6507 6508 case Instruction::BitCast: 6509 // BitCasts are no-op casts so we just eliminate the cast. 6510 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6511 return getSCEV(U->getOperand(0)); 6512 break; 6513 6514 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6515 // lead to pointer expressions which cannot safely be expanded to GEPs, 6516 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6517 // simplifying integer expressions. 6518 6519 case Instruction::GetElementPtr: 6520 return createNodeForGEP(cast<GEPOperator>(U)); 6521 6522 case Instruction::PHI: 6523 return createNodeForPHI(cast<PHINode>(U)); 6524 6525 case Instruction::Select: 6526 // U can also be a select constant expr, which let fall through. Since 6527 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6528 // constant expressions cannot have instructions as operands, we'd have 6529 // returned getUnknown for a select constant expressions anyway. 6530 if (isa<Instruction>(U)) 6531 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6532 U->getOperand(1), U->getOperand(2)); 6533 break; 6534 6535 case Instruction::Call: 6536 case Instruction::Invoke: 6537 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6538 return getSCEV(RV); 6539 break; 6540 } 6541 6542 return getUnknown(V); 6543 } 6544 6545 //===----------------------------------------------------------------------===// 6546 // Iteration Count Computation Code 6547 // 6548 6549 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6550 if (!ExitCount) 6551 return 0; 6552 6553 ConstantInt *ExitConst = ExitCount->getValue(); 6554 6555 // Guard against huge trip counts. 6556 if (ExitConst->getValue().getActiveBits() > 32) 6557 return 0; 6558 6559 // In case of integer overflow, this returns 0, which is correct. 6560 return ((unsigned)ExitConst->getZExtValue()) + 1; 6561 } 6562 6563 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6564 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6565 return getSmallConstantTripCount(L, ExitingBB); 6566 6567 // No trip count information for multiple exits. 6568 return 0; 6569 } 6570 6571 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6572 BasicBlock *ExitingBlock) { 6573 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6574 assert(L->isLoopExiting(ExitingBlock) && 6575 "Exiting block must actually branch out of the loop!"); 6576 const SCEVConstant *ExitCount = 6577 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6578 return getConstantTripCount(ExitCount); 6579 } 6580 6581 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6582 const auto *MaxExitCount = 6583 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6584 return getConstantTripCount(MaxExitCount); 6585 } 6586 6587 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6588 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6589 return getSmallConstantTripMultiple(L, ExitingBB); 6590 6591 // No trip multiple information for multiple exits. 6592 return 0; 6593 } 6594 6595 /// Returns the largest constant divisor of the trip count of this loop as a 6596 /// normal unsigned value, if possible. This means that the actual trip count is 6597 /// always a multiple of the returned value (don't forget the trip count could 6598 /// very well be zero as well!). 6599 /// 6600 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6601 /// multiple of a constant (which is also the case if the trip count is simply 6602 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6603 /// if the trip count is very large (>= 2^32). 6604 /// 6605 /// As explained in the comments for getSmallConstantTripCount, this assumes 6606 /// that control exits the loop via ExitingBlock. 6607 unsigned 6608 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6609 BasicBlock *ExitingBlock) { 6610 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6611 assert(L->isLoopExiting(ExitingBlock) && 6612 "Exiting block must actually branch out of the loop!"); 6613 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6614 if (ExitCount == getCouldNotCompute()) 6615 return 1; 6616 6617 // Get the trip count from the BE count by adding 1. 6618 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6619 6620 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6621 if (!TC) 6622 // Attempt to factor more general cases. Returns the greatest power of 6623 // two divisor. If overflow happens, the trip count expression is still 6624 // divisible by the greatest power of 2 divisor returned. 6625 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6626 6627 ConstantInt *Result = TC->getValue(); 6628 6629 // Guard against huge trip counts (this requires checking 6630 // for zero to handle the case where the trip count == -1 and the 6631 // addition wraps). 6632 if (!Result || Result->getValue().getActiveBits() > 32 || 6633 Result->getValue().getActiveBits() == 0) 6634 return 1; 6635 6636 return (unsigned)Result->getZExtValue(); 6637 } 6638 6639 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6640 BasicBlock *ExitingBlock, 6641 ExitCountKind Kind) { 6642 switch (Kind) { 6643 case Exact: 6644 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6645 case ConstantMaximum: 6646 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6647 }; 6648 llvm_unreachable("Invalid ExitCountKind!"); 6649 } 6650 6651 const SCEV * 6652 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6653 SCEVUnionPredicate &Preds) { 6654 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6655 } 6656 6657 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6658 ExitCountKind Kind) { 6659 switch (Kind) { 6660 case Exact: 6661 return getBackedgeTakenInfo(L).getExact(L, this); 6662 case ConstantMaximum: 6663 return getBackedgeTakenInfo(L).getMax(this); 6664 }; 6665 llvm_unreachable("Invalid ExitCountKind!"); 6666 } 6667 6668 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6669 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6670 } 6671 6672 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6673 static void 6674 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6675 BasicBlock *Header = L->getHeader(); 6676 6677 // Push all Loop-header PHIs onto the Worklist stack. 6678 for (PHINode &PN : Header->phis()) 6679 Worklist.push_back(&PN); 6680 } 6681 6682 const ScalarEvolution::BackedgeTakenInfo & 6683 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6684 auto &BTI = getBackedgeTakenInfo(L); 6685 if (BTI.hasFullInfo()) 6686 return BTI; 6687 6688 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6689 6690 if (!Pair.second) 6691 return Pair.first->second; 6692 6693 BackedgeTakenInfo Result = 6694 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6695 6696 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6697 } 6698 6699 const ScalarEvolution::BackedgeTakenInfo & 6700 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6701 // Initially insert an invalid entry for this loop. If the insertion 6702 // succeeds, proceed to actually compute a backedge-taken count and 6703 // update the value. The temporary CouldNotCompute value tells SCEV 6704 // code elsewhere that it shouldn't attempt to request a new 6705 // backedge-taken count, which could result in infinite recursion. 6706 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6707 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6708 if (!Pair.second) 6709 return Pair.first->second; 6710 6711 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6712 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6713 // must be cleared in this scope. 6714 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6715 6716 // In product build, there are no usage of statistic. 6717 (void)NumTripCountsComputed; 6718 (void)NumTripCountsNotComputed; 6719 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6720 const SCEV *BEExact = Result.getExact(L, this); 6721 if (BEExact != getCouldNotCompute()) { 6722 assert(isLoopInvariant(BEExact, L) && 6723 isLoopInvariant(Result.getMax(this), L) && 6724 "Computed backedge-taken count isn't loop invariant for loop!"); 6725 ++NumTripCountsComputed; 6726 } 6727 else if (Result.getMax(this) == getCouldNotCompute() && 6728 isa<PHINode>(L->getHeader()->begin())) { 6729 // Only count loops that have phi nodes as not being computable. 6730 ++NumTripCountsNotComputed; 6731 } 6732 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6733 6734 // Now that we know more about the trip count for this loop, forget any 6735 // existing SCEV values for PHI nodes in this loop since they are only 6736 // conservative estimates made without the benefit of trip count 6737 // information. This is similar to the code in forgetLoop, except that 6738 // it handles SCEVUnknown PHI nodes specially. 6739 if (Result.hasAnyInfo()) { 6740 SmallVector<Instruction *, 16> Worklist; 6741 PushLoopPHIs(L, Worklist); 6742 6743 SmallPtrSet<Instruction *, 8> Discovered; 6744 while (!Worklist.empty()) { 6745 Instruction *I = Worklist.pop_back_val(); 6746 6747 ValueExprMapType::iterator It = 6748 ValueExprMap.find_as(static_cast<Value *>(I)); 6749 if (It != ValueExprMap.end()) { 6750 const SCEV *Old = It->second; 6751 6752 // SCEVUnknown for a PHI either means that it has an unrecognized 6753 // structure, or it's a PHI that's in the progress of being computed 6754 // by createNodeForPHI. In the former case, additional loop trip 6755 // count information isn't going to change anything. In the later 6756 // case, createNodeForPHI will perform the necessary updates on its 6757 // own when it gets to that point. 6758 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6759 eraseValueFromMap(It->first); 6760 forgetMemoizedResults(Old); 6761 } 6762 if (PHINode *PN = dyn_cast<PHINode>(I)) 6763 ConstantEvolutionLoopExitValue.erase(PN); 6764 } 6765 6766 // Since we don't need to invalidate anything for correctness and we're 6767 // only invalidating to make SCEV's results more precise, we get to stop 6768 // early to avoid invalidating too much. This is especially important in 6769 // cases like: 6770 // 6771 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6772 // loop0: 6773 // %pn0 = phi 6774 // ... 6775 // loop1: 6776 // %pn1 = phi 6777 // ... 6778 // 6779 // where both loop0 and loop1's backedge taken count uses the SCEV 6780 // expression for %v. If we don't have the early stop below then in cases 6781 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6782 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6783 // count for loop1, effectively nullifying SCEV's trip count cache. 6784 for (auto *U : I->users()) 6785 if (auto *I = dyn_cast<Instruction>(U)) { 6786 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6787 if (LoopForUser && L->contains(LoopForUser) && 6788 Discovered.insert(I).second) 6789 Worklist.push_back(I); 6790 } 6791 } 6792 } 6793 6794 // Re-lookup the insert position, since the call to 6795 // computeBackedgeTakenCount above could result in a 6796 // recusive call to getBackedgeTakenInfo (on a different 6797 // loop), which would invalidate the iterator computed 6798 // earlier. 6799 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6800 } 6801 6802 void ScalarEvolution::forgetAllLoops() { 6803 // This method is intended to forget all info about loops. It should 6804 // invalidate caches as if the following happened: 6805 // - The trip counts of all loops have changed arbitrarily 6806 // - Every llvm::Value has been updated in place to produce a different 6807 // result. 6808 BackedgeTakenCounts.clear(); 6809 PredicatedBackedgeTakenCounts.clear(); 6810 LoopPropertiesCache.clear(); 6811 ConstantEvolutionLoopExitValue.clear(); 6812 ValueExprMap.clear(); 6813 ValuesAtScopes.clear(); 6814 LoopDispositions.clear(); 6815 BlockDispositions.clear(); 6816 UnsignedRanges.clear(); 6817 SignedRanges.clear(); 6818 ExprValueMap.clear(); 6819 HasRecMap.clear(); 6820 MinTrailingZerosCache.clear(); 6821 PredicatedSCEVRewrites.clear(); 6822 } 6823 6824 void ScalarEvolution::forgetLoop(const Loop *L) { 6825 // Drop any stored trip count value. 6826 auto RemoveLoopFromBackedgeMap = 6827 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6828 auto BTCPos = Map.find(L); 6829 if (BTCPos != Map.end()) { 6830 BTCPos->second.clear(); 6831 Map.erase(BTCPos); 6832 } 6833 }; 6834 6835 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6836 SmallVector<Instruction *, 32> Worklist; 6837 SmallPtrSet<Instruction *, 16> Visited; 6838 6839 // Iterate over all the loops and sub-loops to drop SCEV information. 6840 while (!LoopWorklist.empty()) { 6841 auto *CurrL = LoopWorklist.pop_back_val(); 6842 6843 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6844 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6845 6846 // Drop information about predicated SCEV rewrites for this loop. 6847 for (auto I = PredicatedSCEVRewrites.begin(); 6848 I != PredicatedSCEVRewrites.end();) { 6849 std::pair<const SCEV *, const Loop *> Entry = I->first; 6850 if (Entry.second == CurrL) 6851 PredicatedSCEVRewrites.erase(I++); 6852 else 6853 ++I; 6854 } 6855 6856 auto LoopUsersItr = LoopUsers.find(CurrL); 6857 if (LoopUsersItr != LoopUsers.end()) { 6858 for (auto *S : LoopUsersItr->second) 6859 forgetMemoizedResults(S); 6860 LoopUsers.erase(LoopUsersItr); 6861 } 6862 6863 // Drop information about expressions based on loop-header PHIs. 6864 PushLoopPHIs(CurrL, Worklist); 6865 6866 while (!Worklist.empty()) { 6867 Instruction *I = Worklist.pop_back_val(); 6868 if (!Visited.insert(I).second) 6869 continue; 6870 6871 ValueExprMapType::iterator It = 6872 ValueExprMap.find_as(static_cast<Value *>(I)); 6873 if (It != ValueExprMap.end()) { 6874 eraseValueFromMap(It->first); 6875 forgetMemoizedResults(It->second); 6876 if (PHINode *PN = dyn_cast<PHINode>(I)) 6877 ConstantEvolutionLoopExitValue.erase(PN); 6878 } 6879 6880 PushDefUseChildren(I, Worklist); 6881 } 6882 6883 LoopPropertiesCache.erase(CurrL); 6884 // Forget all contained loops too, to avoid dangling entries in the 6885 // ValuesAtScopes map. 6886 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6887 } 6888 } 6889 6890 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6891 while (Loop *Parent = L->getParentLoop()) 6892 L = Parent; 6893 forgetLoop(L); 6894 } 6895 6896 void ScalarEvolution::forgetValue(Value *V) { 6897 Instruction *I = dyn_cast<Instruction>(V); 6898 if (!I) return; 6899 6900 // Drop information about expressions based on loop-header PHIs. 6901 SmallVector<Instruction *, 16> Worklist; 6902 Worklist.push_back(I); 6903 6904 SmallPtrSet<Instruction *, 8> Visited; 6905 while (!Worklist.empty()) { 6906 I = Worklist.pop_back_val(); 6907 if (!Visited.insert(I).second) 6908 continue; 6909 6910 ValueExprMapType::iterator It = 6911 ValueExprMap.find_as(static_cast<Value *>(I)); 6912 if (It != ValueExprMap.end()) { 6913 eraseValueFromMap(It->first); 6914 forgetMemoizedResults(It->second); 6915 if (PHINode *PN = dyn_cast<PHINode>(I)) 6916 ConstantEvolutionLoopExitValue.erase(PN); 6917 } 6918 6919 PushDefUseChildren(I, Worklist); 6920 } 6921 } 6922 6923 /// Get the exact loop backedge taken count considering all loop exits. A 6924 /// computable result can only be returned for loops with all exiting blocks 6925 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6926 /// is never skipped. This is a valid assumption as long as the loop exits via 6927 /// that test. For precise results, it is the caller's responsibility to specify 6928 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6929 const SCEV * 6930 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6931 SCEVUnionPredicate *Preds) const { 6932 // If any exits were not computable, the loop is not computable. 6933 if (!isComplete() || ExitNotTaken.empty()) 6934 return SE->getCouldNotCompute(); 6935 6936 const BasicBlock *Latch = L->getLoopLatch(); 6937 // All exiting blocks we have collected must dominate the only backedge. 6938 if (!Latch) 6939 return SE->getCouldNotCompute(); 6940 6941 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6942 // count is simply a minimum out of all these calculated exit counts. 6943 SmallVector<const SCEV *, 2> Ops; 6944 for (auto &ENT : ExitNotTaken) { 6945 const SCEV *BECount = ENT.ExactNotTaken; 6946 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6947 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6948 "We should only have known counts for exiting blocks that dominate " 6949 "latch!"); 6950 6951 Ops.push_back(BECount); 6952 6953 if (Preds && !ENT.hasAlwaysTruePredicate()) 6954 Preds->add(ENT.Predicate.get()); 6955 6956 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6957 "Predicate should be always true!"); 6958 } 6959 6960 return SE->getUMinFromMismatchedTypes(Ops); 6961 } 6962 6963 /// Get the exact not taken count for this loop exit. 6964 const SCEV * 6965 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6966 ScalarEvolution *SE) const { 6967 for (auto &ENT : ExitNotTaken) 6968 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6969 return ENT.ExactNotTaken; 6970 6971 return SE->getCouldNotCompute(); 6972 } 6973 6974 const SCEV * 6975 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 6976 ScalarEvolution *SE) const { 6977 for (auto &ENT : ExitNotTaken) 6978 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6979 return ENT.MaxNotTaken; 6980 6981 return SE->getCouldNotCompute(); 6982 } 6983 6984 /// getMax - Get the max backedge taken count for the loop. 6985 const SCEV * 6986 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6987 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6988 return !ENT.hasAlwaysTruePredicate(); 6989 }; 6990 6991 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6992 return SE->getCouldNotCompute(); 6993 6994 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6995 "No point in having a non-constant max backedge taken count!"); 6996 return getMax(); 6997 } 6998 6999 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 7000 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7001 return !ENT.hasAlwaysTruePredicate(); 7002 }; 7003 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7004 } 7005 7006 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7007 ScalarEvolution *SE) const { 7008 if (getMax() && getMax() != SE->getCouldNotCompute() && 7009 SE->hasOperand(getMax(), S)) 7010 return true; 7011 7012 for (auto &ENT : ExitNotTaken) 7013 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7014 SE->hasOperand(ENT.ExactNotTaken, S)) 7015 return true; 7016 7017 return false; 7018 } 7019 7020 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7021 : ExactNotTaken(E), MaxNotTaken(E) { 7022 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7023 isa<SCEVConstant>(MaxNotTaken)) && 7024 "No point in having a non-constant max backedge taken count!"); 7025 } 7026 7027 ScalarEvolution::ExitLimit::ExitLimit( 7028 const SCEV *E, const SCEV *M, bool MaxOrZero, 7029 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7030 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7031 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7032 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7033 "Exact is not allowed to be less precise than Max"); 7034 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7035 isa<SCEVConstant>(MaxNotTaken)) && 7036 "No point in having a non-constant max backedge taken count!"); 7037 for (auto *PredSet : PredSetList) 7038 for (auto *P : *PredSet) 7039 addPredicate(P); 7040 } 7041 7042 ScalarEvolution::ExitLimit::ExitLimit( 7043 const SCEV *E, const SCEV *M, bool MaxOrZero, 7044 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7045 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7046 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7047 isa<SCEVConstant>(MaxNotTaken)) && 7048 "No point in having a non-constant max backedge taken count!"); 7049 } 7050 7051 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7052 bool MaxOrZero) 7053 : ExitLimit(E, M, MaxOrZero, None) { 7054 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7055 isa<SCEVConstant>(MaxNotTaken)) && 7056 "No point in having a non-constant max backedge taken count!"); 7057 } 7058 7059 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7060 /// computable exit into a persistent ExitNotTakenInfo array. 7061 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7062 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7063 ExitCounts, 7064 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7065 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7066 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7067 7068 ExitNotTaken.reserve(ExitCounts.size()); 7069 std::transform( 7070 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7071 [&](const EdgeExitInfo &EEI) { 7072 BasicBlock *ExitBB = EEI.first; 7073 const ExitLimit &EL = EEI.second; 7074 if (EL.Predicates.empty()) 7075 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7076 nullptr); 7077 7078 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7079 for (auto *Pred : EL.Predicates) 7080 Predicate->add(Pred); 7081 7082 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7083 std::move(Predicate)); 7084 }); 7085 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7086 "No point in having a non-constant max backedge taken count!"); 7087 } 7088 7089 /// Invalidate this result and free the ExitNotTakenInfo array. 7090 void ScalarEvolution::BackedgeTakenInfo::clear() { 7091 ExitNotTaken.clear(); 7092 } 7093 7094 /// Compute the number of times the backedge of the specified loop will execute. 7095 ScalarEvolution::BackedgeTakenInfo 7096 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7097 bool AllowPredicates) { 7098 SmallVector<BasicBlock *, 8> ExitingBlocks; 7099 L->getExitingBlocks(ExitingBlocks); 7100 7101 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7102 7103 SmallVector<EdgeExitInfo, 4> ExitCounts; 7104 bool CouldComputeBECount = true; 7105 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7106 const SCEV *MustExitMaxBECount = nullptr; 7107 const SCEV *MayExitMaxBECount = nullptr; 7108 bool MustExitMaxOrZero = false; 7109 7110 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7111 // and compute maxBECount. 7112 // Do a union of all the predicates here. 7113 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7114 BasicBlock *ExitBB = ExitingBlocks[i]; 7115 7116 // We canonicalize untaken exits to br (constant), ignore them so that 7117 // proving an exit untaken doesn't negatively impact our ability to reason 7118 // about the loop as whole. 7119 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7120 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7121 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7122 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7123 continue; 7124 } 7125 7126 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7127 7128 assert((AllowPredicates || EL.Predicates.empty()) && 7129 "Predicated exit limit when predicates are not allowed!"); 7130 7131 // 1. For each exit that can be computed, add an entry to ExitCounts. 7132 // CouldComputeBECount is true only if all exits can be computed. 7133 if (EL.ExactNotTaken == getCouldNotCompute()) 7134 // We couldn't compute an exact value for this exit, so 7135 // we won't be able to compute an exact value for the loop. 7136 CouldComputeBECount = false; 7137 else 7138 ExitCounts.emplace_back(ExitBB, EL); 7139 7140 // 2. Derive the loop's MaxBECount from each exit's max number of 7141 // non-exiting iterations. Partition the loop exits into two kinds: 7142 // LoopMustExits and LoopMayExits. 7143 // 7144 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7145 // is a LoopMayExit. If any computable LoopMustExit is found, then 7146 // MaxBECount is the minimum EL.MaxNotTaken of computable 7147 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7148 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7149 // computable EL.MaxNotTaken. 7150 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7151 DT.dominates(ExitBB, Latch)) { 7152 if (!MustExitMaxBECount) { 7153 MustExitMaxBECount = EL.MaxNotTaken; 7154 MustExitMaxOrZero = EL.MaxOrZero; 7155 } else { 7156 MustExitMaxBECount = 7157 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7158 } 7159 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7160 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7161 MayExitMaxBECount = EL.MaxNotTaken; 7162 else { 7163 MayExitMaxBECount = 7164 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7165 } 7166 } 7167 } 7168 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7169 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7170 // The loop backedge will be taken the maximum or zero times if there's 7171 // a single exit that must be taken the maximum or zero times. 7172 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7173 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7174 MaxBECount, MaxOrZero); 7175 } 7176 7177 ScalarEvolution::ExitLimit 7178 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7179 bool AllowPredicates) { 7180 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7181 // If our exiting block does not dominate the latch, then its connection with 7182 // loop's exit limit may be far from trivial. 7183 const BasicBlock *Latch = L->getLoopLatch(); 7184 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7185 return getCouldNotCompute(); 7186 7187 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7188 Instruction *Term = ExitingBlock->getTerminator(); 7189 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7190 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7191 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7192 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7193 "It should have one successor in loop and one exit block!"); 7194 // Proceed to the next level to examine the exit condition expression. 7195 return computeExitLimitFromCond( 7196 L, BI->getCondition(), ExitIfTrue, 7197 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7198 } 7199 7200 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7201 // For switch, make sure that there is a single exit from the loop. 7202 BasicBlock *Exit = nullptr; 7203 for (auto *SBB : successors(ExitingBlock)) 7204 if (!L->contains(SBB)) { 7205 if (Exit) // Multiple exit successors. 7206 return getCouldNotCompute(); 7207 Exit = SBB; 7208 } 7209 assert(Exit && "Exiting block must have at least one exit"); 7210 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7211 /*ControlsExit=*/IsOnlyExit); 7212 } 7213 7214 return getCouldNotCompute(); 7215 } 7216 7217 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7218 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7219 bool ControlsExit, bool AllowPredicates) { 7220 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7221 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7222 ControlsExit, AllowPredicates); 7223 } 7224 7225 Optional<ScalarEvolution::ExitLimit> 7226 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7227 bool ExitIfTrue, bool ControlsExit, 7228 bool AllowPredicates) { 7229 (void)this->L; 7230 (void)this->ExitIfTrue; 7231 (void)this->AllowPredicates; 7232 7233 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7234 this->AllowPredicates == AllowPredicates && 7235 "Variance in assumed invariant key components!"); 7236 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7237 if (Itr == TripCountMap.end()) 7238 return None; 7239 return Itr->second; 7240 } 7241 7242 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7243 bool ExitIfTrue, 7244 bool ControlsExit, 7245 bool AllowPredicates, 7246 const ExitLimit &EL) { 7247 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7248 this->AllowPredicates == AllowPredicates && 7249 "Variance in assumed invariant key components!"); 7250 7251 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7252 assert(InsertResult.second && "Expected successful insertion!"); 7253 (void)InsertResult; 7254 (void)ExitIfTrue; 7255 } 7256 7257 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7258 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7259 bool ControlsExit, bool AllowPredicates) { 7260 7261 if (auto MaybeEL = 7262 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7263 return *MaybeEL; 7264 7265 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7266 ControlsExit, AllowPredicates); 7267 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7268 return EL; 7269 } 7270 7271 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7272 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7273 bool ControlsExit, bool AllowPredicates) { 7274 // Check if the controlling expression for this loop is an And or Or. 7275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7276 if (BO->getOpcode() == Instruction::And) { 7277 // Recurse on the operands of the and. 7278 bool EitherMayExit = !ExitIfTrue; 7279 ExitLimit EL0 = computeExitLimitFromCondCached( 7280 Cache, L, BO->getOperand(0), ExitIfTrue, 7281 ControlsExit && !EitherMayExit, AllowPredicates); 7282 ExitLimit EL1 = computeExitLimitFromCondCached( 7283 Cache, L, BO->getOperand(1), ExitIfTrue, 7284 ControlsExit && !EitherMayExit, AllowPredicates); 7285 // Be robust against unsimplified IR for the form "and i1 X, true" 7286 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7287 return CI->isOne() ? EL0 : EL1; 7288 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7289 return CI->isOne() ? EL1 : EL0; 7290 const SCEV *BECount = getCouldNotCompute(); 7291 const SCEV *MaxBECount = getCouldNotCompute(); 7292 if (EitherMayExit) { 7293 // Both conditions must be true for the loop to continue executing. 7294 // Choose the less conservative count. 7295 if (EL0.ExactNotTaken == getCouldNotCompute() || 7296 EL1.ExactNotTaken == getCouldNotCompute()) 7297 BECount = getCouldNotCompute(); 7298 else 7299 BECount = 7300 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7301 if (EL0.MaxNotTaken == getCouldNotCompute()) 7302 MaxBECount = EL1.MaxNotTaken; 7303 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7304 MaxBECount = EL0.MaxNotTaken; 7305 else 7306 MaxBECount = 7307 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7308 } else { 7309 // Both conditions must be true at the same time for the loop to exit. 7310 // For now, be conservative. 7311 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7312 MaxBECount = EL0.MaxNotTaken; 7313 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7314 BECount = EL0.ExactNotTaken; 7315 } 7316 7317 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7318 // to be more aggressive when computing BECount than when computing 7319 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7320 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7321 // to not. 7322 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7323 !isa<SCEVCouldNotCompute>(BECount)) 7324 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7325 7326 return ExitLimit(BECount, MaxBECount, false, 7327 {&EL0.Predicates, &EL1.Predicates}); 7328 } 7329 if (BO->getOpcode() == Instruction::Or) { 7330 // Recurse on the operands of the or. 7331 bool EitherMayExit = ExitIfTrue; 7332 ExitLimit EL0 = computeExitLimitFromCondCached( 7333 Cache, L, BO->getOperand(0), ExitIfTrue, 7334 ControlsExit && !EitherMayExit, AllowPredicates); 7335 ExitLimit EL1 = computeExitLimitFromCondCached( 7336 Cache, L, BO->getOperand(1), ExitIfTrue, 7337 ControlsExit && !EitherMayExit, AllowPredicates); 7338 // Be robust against unsimplified IR for the form "or i1 X, true" 7339 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7340 return CI->isZero() ? EL0 : EL1; 7341 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7342 return CI->isZero() ? EL1 : EL0; 7343 const SCEV *BECount = getCouldNotCompute(); 7344 const SCEV *MaxBECount = getCouldNotCompute(); 7345 if (EitherMayExit) { 7346 // Both conditions must be false for the loop to continue executing. 7347 // Choose the less conservative count. 7348 if (EL0.ExactNotTaken == getCouldNotCompute() || 7349 EL1.ExactNotTaken == getCouldNotCompute()) 7350 BECount = getCouldNotCompute(); 7351 else 7352 BECount = 7353 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7354 if (EL0.MaxNotTaken == getCouldNotCompute()) 7355 MaxBECount = EL1.MaxNotTaken; 7356 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7357 MaxBECount = EL0.MaxNotTaken; 7358 else 7359 MaxBECount = 7360 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7361 } else { 7362 // Both conditions must be false at the same time for the loop to exit. 7363 // For now, be conservative. 7364 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7365 MaxBECount = EL0.MaxNotTaken; 7366 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7367 BECount = EL0.ExactNotTaken; 7368 } 7369 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7370 // to be more aggressive when computing BECount than when computing 7371 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7372 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7373 // to not. 7374 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7375 !isa<SCEVCouldNotCompute>(BECount)) 7376 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7377 7378 return ExitLimit(BECount, MaxBECount, false, 7379 {&EL0.Predicates, &EL1.Predicates}); 7380 } 7381 } 7382 7383 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7384 // Proceed to the next level to examine the icmp. 7385 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7386 ExitLimit EL = 7387 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7388 if (EL.hasFullInfo() || !AllowPredicates) 7389 return EL; 7390 7391 // Try again, but use SCEV predicates this time. 7392 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7393 /*AllowPredicates=*/true); 7394 } 7395 7396 // Check for a constant condition. These are normally stripped out by 7397 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7398 // preserve the CFG and is temporarily leaving constant conditions 7399 // in place. 7400 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7401 if (ExitIfTrue == !CI->getZExtValue()) 7402 // The backedge is always taken. 7403 return getCouldNotCompute(); 7404 else 7405 // The backedge is never taken. 7406 return getZero(CI->getType()); 7407 } 7408 7409 // If it's not an integer or pointer comparison then compute it the hard way. 7410 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7411 } 7412 7413 ScalarEvolution::ExitLimit 7414 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7415 ICmpInst *ExitCond, 7416 bool ExitIfTrue, 7417 bool ControlsExit, 7418 bool AllowPredicates) { 7419 // If the condition was exit on true, convert the condition to exit on false 7420 ICmpInst::Predicate Pred; 7421 if (!ExitIfTrue) 7422 Pred = ExitCond->getPredicate(); 7423 else 7424 Pred = ExitCond->getInversePredicate(); 7425 const ICmpInst::Predicate OriginalPred = Pred; 7426 7427 // Handle common loops like: for (X = "string"; *X; ++X) 7428 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7429 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7430 ExitLimit ItCnt = 7431 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7432 if (ItCnt.hasAnyInfo()) 7433 return ItCnt; 7434 } 7435 7436 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7437 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7438 7439 // Try to evaluate any dependencies out of the loop. 7440 LHS = getSCEVAtScope(LHS, L); 7441 RHS = getSCEVAtScope(RHS, L); 7442 7443 // At this point, we would like to compute how many iterations of the 7444 // loop the predicate will return true for these inputs. 7445 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7446 // If there is a loop-invariant, force it into the RHS. 7447 std::swap(LHS, RHS); 7448 Pred = ICmpInst::getSwappedPredicate(Pred); 7449 } 7450 7451 // Simplify the operands before analyzing them. 7452 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7453 7454 // If we have a comparison of a chrec against a constant, try to use value 7455 // ranges to answer this query. 7456 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7457 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7458 if (AddRec->getLoop() == L) { 7459 // Form the constant range. 7460 ConstantRange CompRange = 7461 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7462 7463 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7464 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7465 } 7466 7467 switch (Pred) { 7468 case ICmpInst::ICMP_NE: { // while (X != Y) 7469 // Convert to: while (X-Y != 0) 7470 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7471 AllowPredicates); 7472 if (EL.hasAnyInfo()) return EL; 7473 break; 7474 } 7475 case ICmpInst::ICMP_EQ: { // while (X == Y) 7476 // Convert to: while (X-Y == 0) 7477 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7478 if (EL.hasAnyInfo()) return EL; 7479 break; 7480 } 7481 case ICmpInst::ICMP_SLT: 7482 case ICmpInst::ICMP_ULT: { // while (X < Y) 7483 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7484 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7485 AllowPredicates); 7486 if (EL.hasAnyInfo()) return EL; 7487 break; 7488 } 7489 case ICmpInst::ICMP_SGT: 7490 case ICmpInst::ICMP_UGT: { // while (X > Y) 7491 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7492 ExitLimit EL = 7493 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7494 AllowPredicates); 7495 if (EL.hasAnyInfo()) return EL; 7496 break; 7497 } 7498 default: 7499 break; 7500 } 7501 7502 auto *ExhaustiveCount = 7503 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7504 7505 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7506 return ExhaustiveCount; 7507 7508 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7509 ExitCond->getOperand(1), L, OriginalPred); 7510 } 7511 7512 ScalarEvolution::ExitLimit 7513 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7514 SwitchInst *Switch, 7515 BasicBlock *ExitingBlock, 7516 bool ControlsExit) { 7517 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7518 7519 // Give up if the exit is the default dest of a switch. 7520 if (Switch->getDefaultDest() == ExitingBlock) 7521 return getCouldNotCompute(); 7522 7523 assert(L->contains(Switch->getDefaultDest()) && 7524 "Default case must not exit the loop!"); 7525 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7526 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7527 7528 // while (X != Y) --> while (X-Y != 0) 7529 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7530 if (EL.hasAnyInfo()) 7531 return EL; 7532 7533 return getCouldNotCompute(); 7534 } 7535 7536 static ConstantInt * 7537 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7538 ScalarEvolution &SE) { 7539 const SCEV *InVal = SE.getConstant(C); 7540 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7541 assert(isa<SCEVConstant>(Val) && 7542 "Evaluation of SCEV at constant didn't fold correctly?"); 7543 return cast<SCEVConstant>(Val)->getValue(); 7544 } 7545 7546 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7547 /// compute the backedge execution count. 7548 ScalarEvolution::ExitLimit 7549 ScalarEvolution::computeLoadConstantCompareExitLimit( 7550 LoadInst *LI, 7551 Constant *RHS, 7552 const Loop *L, 7553 ICmpInst::Predicate predicate) { 7554 if (LI->isVolatile()) return getCouldNotCompute(); 7555 7556 // Check to see if the loaded pointer is a getelementptr of a global. 7557 // TODO: Use SCEV instead of manually grubbing with GEPs. 7558 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7559 if (!GEP) return getCouldNotCompute(); 7560 7561 // Make sure that it is really a constant global we are gepping, with an 7562 // initializer, and make sure the first IDX is really 0. 7563 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7564 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7565 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7566 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7567 return getCouldNotCompute(); 7568 7569 // Okay, we allow one non-constant index into the GEP instruction. 7570 Value *VarIdx = nullptr; 7571 std::vector<Constant*> Indexes; 7572 unsigned VarIdxNum = 0; 7573 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7574 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7575 Indexes.push_back(CI); 7576 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7577 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7578 VarIdx = GEP->getOperand(i); 7579 VarIdxNum = i-2; 7580 Indexes.push_back(nullptr); 7581 } 7582 7583 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7584 if (!VarIdx) 7585 return getCouldNotCompute(); 7586 7587 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7588 // Check to see if X is a loop variant variable value now. 7589 const SCEV *Idx = getSCEV(VarIdx); 7590 Idx = getSCEVAtScope(Idx, L); 7591 7592 // We can only recognize very limited forms of loop index expressions, in 7593 // particular, only affine AddRec's like {C1,+,C2}. 7594 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7595 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7596 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7597 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7598 return getCouldNotCompute(); 7599 7600 unsigned MaxSteps = MaxBruteForceIterations; 7601 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7602 ConstantInt *ItCst = ConstantInt::get( 7603 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7604 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7605 7606 // Form the GEP offset. 7607 Indexes[VarIdxNum] = Val; 7608 7609 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7610 Indexes); 7611 if (!Result) break; // Cannot compute! 7612 7613 // Evaluate the condition for this iteration. 7614 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7615 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7616 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7617 ++NumArrayLenItCounts; 7618 return getConstant(ItCst); // Found terminating iteration! 7619 } 7620 } 7621 return getCouldNotCompute(); 7622 } 7623 7624 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7625 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7626 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7627 if (!RHS) 7628 return getCouldNotCompute(); 7629 7630 const BasicBlock *Latch = L->getLoopLatch(); 7631 if (!Latch) 7632 return getCouldNotCompute(); 7633 7634 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7635 if (!Predecessor) 7636 return getCouldNotCompute(); 7637 7638 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7639 // Return LHS in OutLHS and shift_opt in OutOpCode. 7640 auto MatchPositiveShift = 7641 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7642 7643 using namespace PatternMatch; 7644 7645 ConstantInt *ShiftAmt; 7646 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7647 OutOpCode = Instruction::LShr; 7648 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7649 OutOpCode = Instruction::AShr; 7650 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7651 OutOpCode = Instruction::Shl; 7652 else 7653 return false; 7654 7655 return ShiftAmt->getValue().isStrictlyPositive(); 7656 }; 7657 7658 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7659 // 7660 // loop: 7661 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7662 // %iv.shifted = lshr i32 %iv, <positive constant> 7663 // 7664 // Return true on a successful match. Return the corresponding PHI node (%iv 7665 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7666 auto MatchShiftRecurrence = 7667 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7668 Optional<Instruction::BinaryOps> PostShiftOpCode; 7669 7670 { 7671 Instruction::BinaryOps OpC; 7672 Value *V; 7673 7674 // If we encounter a shift instruction, "peel off" the shift operation, 7675 // and remember that we did so. Later when we inspect %iv's backedge 7676 // value, we will make sure that the backedge value uses the same 7677 // operation. 7678 // 7679 // Note: the peeled shift operation does not have to be the same 7680 // instruction as the one feeding into the PHI's backedge value. We only 7681 // really care about it being the same *kind* of shift instruction -- 7682 // that's all that is required for our later inferences to hold. 7683 if (MatchPositiveShift(LHS, V, OpC)) { 7684 PostShiftOpCode = OpC; 7685 LHS = V; 7686 } 7687 } 7688 7689 PNOut = dyn_cast<PHINode>(LHS); 7690 if (!PNOut || PNOut->getParent() != L->getHeader()) 7691 return false; 7692 7693 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7694 Value *OpLHS; 7695 7696 return 7697 // The backedge value for the PHI node must be a shift by a positive 7698 // amount 7699 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7700 7701 // of the PHI node itself 7702 OpLHS == PNOut && 7703 7704 // and the kind of shift should be match the kind of shift we peeled 7705 // off, if any. 7706 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7707 }; 7708 7709 PHINode *PN; 7710 Instruction::BinaryOps OpCode; 7711 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7712 return getCouldNotCompute(); 7713 7714 const DataLayout &DL = getDataLayout(); 7715 7716 // The key rationale for this optimization is that for some kinds of shift 7717 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7718 // within a finite number of iterations. If the condition guarding the 7719 // backedge (in the sense that the backedge is taken if the condition is true) 7720 // is false for the value the shift recurrence stabilizes to, then we know 7721 // that the backedge is taken only a finite number of times. 7722 7723 ConstantInt *StableValue = nullptr; 7724 switch (OpCode) { 7725 default: 7726 llvm_unreachable("Impossible case!"); 7727 7728 case Instruction::AShr: { 7729 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7730 // bitwidth(K) iterations. 7731 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7732 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7733 Predecessor->getTerminator(), &DT); 7734 auto *Ty = cast<IntegerType>(RHS->getType()); 7735 if (Known.isNonNegative()) 7736 StableValue = ConstantInt::get(Ty, 0); 7737 else if (Known.isNegative()) 7738 StableValue = ConstantInt::get(Ty, -1, true); 7739 else 7740 return getCouldNotCompute(); 7741 7742 break; 7743 } 7744 case Instruction::LShr: 7745 case Instruction::Shl: 7746 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7747 // stabilize to 0 in at most bitwidth(K) iterations. 7748 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7749 break; 7750 } 7751 7752 auto *Result = 7753 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7754 assert(Result->getType()->isIntegerTy(1) && 7755 "Otherwise cannot be an operand to a branch instruction"); 7756 7757 if (Result->isZeroValue()) { 7758 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7759 const SCEV *UpperBound = 7760 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7761 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7762 } 7763 7764 return getCouldNotCompute(); 7765 } 7766 7767 /// Return true if we can constant fold an instruction of the specified type, 7768 /// assuming that all operands were constants. 7769 static bool CanConstantFold(const Instruction *I) { 7770 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7771 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7772 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7773 return true; 7774 7775 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7776 if (const Function *F = CI->getCalledFunction()) 7777 return canConstantFoldCallTo(CI, F); 7778 return false; 7779 } 7780 7781 /// Determine whether this instruction can constant evolve within this loop 7782 /// assuming its operands can all constant evolve. 7783 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7784 // An instruction outside of the loop can't be derived from a loop PHI. 7785 if (!L->contains(I)) return false; 7786 7787 if (isa<PHINode>(I)) { 7788 // We don't currently keep track of the control flow needed to evaluate 7789 // PHIs, so we cannot handle PHIs inside of loops. 7790 return L->getHeader() == I->getParent(); 7791 } 7792 7793 // If we won't be able to constant fold this expression even if the operands 7794 // are constants, bail early. 7795 return CanConstantFold(I); 7796 } 7797 7798 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7799 /// recursing through each instruction operand until reaching a loop header phi. 7800 static PHINode * 7801 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7802 DenseMap<Instruction *, PHINode *> &PHIMap, 7803 unsigned Depth) { 7804 if (Depth > MaxConstantEvolvingDepth) 7805 return nullptr; 7806 7807 // Otherwise, we can evaluate this instruction if all of its operands are 7808 // constant or derived from a PHI node themselves. 7809 PHINode *PHI = nullptr; 7810 for (Value *Op : UseInst->operands()) { 7811 if (isa<Constant>(Op)) continue; 7812 7813 Instruction *OpInst = dyn_cast<Instruction>(Op); 7814 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7815 7816 PHINode *P = dyn_cast<PHINode>(OpInst); 7817 if (!P) 7818 // If this operand is already visited, reuse the prior result. 7819 // We may have P != PHI if this is the deepest point at which the 7820 // inconsistent paths meet. 7821 P = PHIMap.lookup(OpInst); 7822 if (!P) { 7823 // Recurse and memoize the results, whether a phi is found or not. 7824 // This recursive call invalidates pointers into PHIMap. 7825 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7826 PHIMap[OpInst] = P; 7827 } 7828 if (!P) 7829 return nullptr; // Not evolving from PHI 7830 if (PHI && PHI != P) 7831 return nullptr; // Evolving from multiple different PHIs. 7832 PHI = P; 7833 } 7834 // This is a expression evolving from a constant PHI! 7835 return PHI; 7836 } 7837 7838 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7839 /// in the loop that V is derived from. We allow arbitrary operations along the 7840 /// way, but the operands of an operation must either be constants or a value 7841 /// derived from a constant PHI. If this expression does not fit with these 7842 /// constraints, return null. 7843 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7844 Instruction *I = dyn_cast<Instruction>(V); 7845 if (!I || !canConstantEvolve(I, L)) return nullptr; 7846 7847 if (PHINode *PN = dyn_cast<PHINode>(I)) 7848 return PN; 7849 7850 // Record non-constant instructions contained by the loop. 7851 DenseMap<Instruction *, PHINode *> PHIMap; 7852 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7853 } 7854 7855 /// EvaluateExpression - Given an expression that passes the 7856 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7857 /// in the loop has the value PHIVal. If we can't fold this expression for some 7858 /// reason, return null. 7859 static Constant *EvaluateExpression(Value *V, const Loop *L, 7860 DenseMap<Instruction *, Constant *> &Vals, 7861 const DataLayout &DL, 7862 const TargetLibraryInfo *TLI) { 7863 // Convenient constant check, but redundant for recursive calls. 7864 if (Constant *C = dyn_cast<Constant>(V)) return C; 7865 Instruction *I = dyn_cast<Instruction>(V); 7866 if (!I) return nullptr; 7867 7868 if (Constant *C = Vals.lookup(I)) return C; 7869 7870 // An instruction inside the loop depends on a value outside the loop that we 7871 // weren't given a mapping for, or a value such as a call inside the loop. 7872 if (!canConstantEvolve(I, L)) return nullptr; 7873 7874 // An unmapped PHI can be due to a branch or another loop inside this loop, 7875 // or due to this not being the initial iteration through a loop where we 7876 // couldn't compute the evolution of this particular PHI last time. 7877 if (isa<PHINode>(I)) return nullptr; 7878 7879 std::vector<Constant*> Operands(I->getNumOperands()); 7880 7881 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7882 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7883 if (!Operand) { 7884 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7885 if (!Operands[i]) return nullptr; 7886 continue; 7887 } 7888 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7889 Vals[Operand] = C; 7890 if (!C) return nullptr; 7891 Operands[i] = C; 7892 } 7893 7894 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7895 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7896 Operands[1], DL, TLI); 7897 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7898 if (!LI->isVolatile()) 7899 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7900 } 7901 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7902 } 7903 7904 7905 // If every incoming value to PN except the one for BB is a specific Constant, 7906 // return that, else return nullptr. 7907 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7908 Constant *IncomingVal = nullptr; 7909 7910 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7911 if (PN->getIncomingBlock(i) == BB) 7912 continue; 7913 7914 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7915 if (!CurrentVal) 7916 return nullptr; 7917 7918 if (IncomingVal != CurrentVal) { 7919 if (IncomingVal) 7920 return nullptr; 7921 IncomingVal = CurrentVal; 7922 } 7923 } 7924 7925 return IncomingVal; 7926 } 7927 7928 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7929 /// in the header of its containing loop, we know the loop executes a 7930 /// constant number of times, and the PHI node is just a recurrence 7931 /// involving constants, fold it. 7932 Constant * 7933 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7934 const APInt &BEs, 7935 const Loop *L) { 7936 auto I = ConstantEvolutionLoopExitValue.find(PN); 7937 if (I != ConstantEvolutionLoopExitValue.end()) 7938 return I->second; 7939 7940 if (BEs.ugt(MaxBruteForceIterations)) 7941 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7942 7943 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7944 7945 DenseMap<Instruction *, Constant *> CurrentIterVals; 7946 BasicBlock *Header = L->getHeader(); 7947 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7948 7949 BasicBlock *Latch = L->getLoopLatch(); 7950 if (!Latch) 7951 return nullptr; 7952 7953 for (PHINode &PHI : Header->phis()) { 7954 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7955 CurrentIterVals[&PHI] = StartCST; 7956 } 7957 if (!CurrentIterVals.count(PN)) 7958 return RetVal = nullptr; 7959 7960 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7961 7962 // Execute the loop symbolically to determine the exit value. 7963 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7964 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7965 7966 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7967 unsigned IterationNum = 0; 7968 const DataLayout &DL = getDataLayout(); 7969 for (; ; ++IterationNum) { 7970 if (IterationNum == NumIterations) 7971 return RetVal = CurrentIterVals[PN]; // Got exit value! 7972 7973 // Compute the value of the PHIs for the next iteration. 7974 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7975 DenseMap<Instruction *, Constant *> NextIterVals; 7976 Constant *NextPHI = 7977 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7978 if (!NextPHI) 7979 return nullptr; // Couldn't evaluate! 7980 NextIterVals[PN] = NextPHI; 7981 7982 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7983 7984 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7985 // cease to be able to evaluate one of them or if they stop evolving, 7986 // because that doesn't necessarily prevent us from computing PN. 7987 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7988 for (const auto &I : CurrentIterVals) { 7989 PHINode *PHI = dyn_cast<PHINode>(I.first); 7990 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7991 PHIsToCompute.emplace_back(PHI, I.second); 7992 } 7993 // We use two distinct loops because EvaluateExpression may invalidate any 7994 // iterators into CurrentIterVals. 7995 for (const auto &I : PHIsToCompute) { 7996 PHINode *PHI = I.first; 7997 Constant *&NextPHI = NextIterVals[PHI]; 7998 if (!NextPHI) { // Not already computed. 7999 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8000 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8001 } 8002 if (NextPHI != I.second) 8003 StoppedEvolving = false; 8004 } 8005 8006 // If all entries in CurrentIterVals == NextIterVals then we can stop 8007 // iterating, the loop can't continue to change. 8008 if (StoppedEvolving) 8009 return RetVal = CurrentIterVals[PN]; 8010 8011 CurrentIterVals.swap(NextIterVals); 8012 } 8013 } 8014 8015 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8016 Value *Cond, 8017 bool ExitWhen) { 8018 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8019 if (!PN) return getCouldNotCompute(); 8020 8021 // If the loop is canonicalized, the PHI will have exactly two entries. 8022 // That's the only form we support here. 8023 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8024 8025 DenseMap<Instruction *, Constant *> CurrentIterVals; 8026 BasicBlock *Header = L->getHeader(); 8027 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8028 8029 BasicBlock *Latch = L->getLoopLatch(); 8030 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8031 8032 for (PHINode &PHI : Header->phis()) { 8033 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8034 CurrentIterVals[&PHI] = StartCST; 8035 } 8036 if (!CurrentIterVals.count(PN)) 8037 return getCouldNotCompute(); 8038 8039 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8040 // the loop symbolically to determine when the condition gets a value of 8041 // "ExitWhen". 8042 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8043 const DataLayout &DL = getDataLayout(); 8044 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8045 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8046 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8047 8048 // Couldn't symbolically evaluate. 8049 if (!CondVal) return getCouldNotCompute(); 8050 8051 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8052 ++NumBruteForceTripCountsComputed; 8053 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8054 } 8055 8056 // Update all the PHI nodes for the next iteration. 8057 DenseMap<Instruction *, Constant *> NextIterVals; 8058 8059 // Create a list of which PHIs we need to compute. We want to do this before 8060 // calling EvaluateExpression on them because that may invalidate iterators 8061 // into CurrentIterVals. 8062 SmallVector<PHINode *, 8> PHIsToCompute; 8063 for (const auto &I : CurrentIterVals) { 8064 PHINode *PHI = dyn_cast<PHINode>(I.first); 8065 if (!PHI || PHI->getParent() != Header) continue; 8066 PHIsToCompute.push_back(PHI); 8067 } 8068 for (PHINode *PHI : PHIsToCompute) { 8069 Constant *&NextPHI = NextIterVals[PHI]; 8070 if (NextPHI) continue; // Already computed! 8071 8072 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8073 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8074 } 8075 CurrentIterVals.swap(NextIterVals); 8076 } 8077 8078 // Too many iterations were needed to evaluate. 8079 return getCouldNotCompute(); 8080 } 8081 8082 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8083 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8084 ValuesAtScopes[V]; 8085 // Check to see if we've folded this expression at this loop before. 8086 for (auto &LS : Values) 8087 if (LS.first == L) 8088 return LS.second ? LS.second : V; 8089 8090 Values.emplace_back(L, nullptr); 8091 8092 // Otherwise compute it. 8093 const SCEV *C = computeSCEVAtScope(V, L); 8094 for (auto &LS : reverse(ValuesAtScopes[V])) 8095 if (LS.first == L) { 8096 LS.second = C; 8097 break; 8098 } 8099 return C; 8100 } 8101 8102 /// This builds up a Constant using the ConstantExpr interface. That way, we 8103 /// will return Constants for objects which aren't represented by a 8104 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8105 /// Returns NULL if the SCEV isn't representable as a Constant. 8106 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8107 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8108 case scCouldNotCompute: 8109 case scAddRecExpr: 8110 break; 8111 case scConstant: 8112 return cast<SCEVConstant>(V)->getValue(); 8113 case scUnknown: 8114 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8115 case scSignExtend: { 8116 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8117 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8118 return ConstantExpr::getSExt(CastOp, SS->getType()); 8119 break; 8120 } 8121 case scZeroExtend: { 8122 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8123 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8124 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8125 break; 8126 } 8127 case scTruncate: { 8128 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8129 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8130 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8131 break; 8132 } 8133 case scAddExpr: { 8134 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8135 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8136 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8137 unsigned AS = PTy->getAddressSpace(); 8138 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8139 C = ConstantExpr::getBitCast(C, DestPtrTy); 8140 } 8141 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8142 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8143 if (!C2) return nullptr; 8144 8145 // First pointer! 8146 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8147 unsigned AS = C2->getType()->getPointerAddressSpace(); 8148 std::swap(C, C2); 8149 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8150 // The offsets have been converted to bytes. We can add bytes to an 8151 // i8* by GEP with the byte count in the first index. 8152 C = ConstantExpr::getBitCast(C, DestPtrTy); 8153 } 8154 8155 // Don't bother trying to sum two pointers. We probably can't 8156 // statically compute a load that results from it anyway. 8157 if (C2->getType()->isPointerTy()) 8158 return nullptr; 8159 8160 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8161 if (PTy->getElementType()->isStructTy()) 8162 C2 = ConstantExpr::getIntegerCast( 8163 C2, Type::getInt32Ty(C->getContext()), true); 8164 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8165 } else 8166 C = ConstantExpr::getAdd(C, C2); 8167 } 8168 return C; 8169 } 8170 break; 8171 } 8172 case scMulExpr: { 8173 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8174 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8175 // Don't bother with pointers at all. 8176 if (C->getType()->isPointerTy()) return nullptr; 8177 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8178 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8179 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8180 C = ConstantExpr::getMul(C, C2); 8181 } 8182 return C; 8183 } 8184 break; 8185 } 8186 case scUDivExpr: { 8187 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8188 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8189 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8190 if (LHS->getType() == RHS->getType()) 8191 return ConstantExpr::getUDiv(LHS, RHS); 8192 break; 8193 } 8194 case scSMaxExpr: 8195 case scUMaxExpr: 8196 case scSMinExpr: 8197 case scUMinExpr: 8198 break; // TODO: smax, umax, smin, umax. 8199 } 8200 return nullptr; 8201 } 8202 8203 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8204 if (isa<SCEVConstant>(V)) return V; 8205 8206 // If this instruction is evolved from a constant-evolving PHI, compute the 8207 // exit value from the loop without using SCEVs. 8208 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8209 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8210 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8211 const Loop *LI = this->LI[I->getParent()]; 8212 // Looking for loop exit value. 8213 if (LI && LI->getParentLoop() == L && 8214 PN->getParent() == LI->getHeader()) { 8215 // Okay, there is no closed form solution for the PHI node. Check 8216 // to see if the loop that contains it has a known backedge-taken 8217 // count. If so, we may be able to force computation of the exit 8218 // value. 8219 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8220 // This trivial case can show up in some degenerate cases where 8221 // the incoming IR has not yet been fully simplified. 8222 if (BackedgeTakenCount->isZero()) { 8223 Value *InitValue = nullptr; 8224 bool MultipleInitValues = false; 8225 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8226 if (!LI->contains(PN->getIncomingBlock(i))) { 8227 if (!InitValue) 8228 InitValue = PN->getIncomingValue(i); 8229 else if (InitValue != PN->getIncomingValue(i)) { 8230 MultipleInitValues = true; 8231 break; 8232 } 8233 } 8234 } 8235 if (!MultipleInitValues && InitValue) 8236 return getSCEV(InitValue); 8237 } 8238 // Do we have a loop invariant value flowing around the backedge 8239 // for a loop which must execute the backedge? 8240 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8241 isKnownPositive(BackedgeTakenCount) && 8242 PN->getNumIncomingValues() == 2) { 8243 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8244 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8245 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8246 return OnBackedge; 8247 } 8248 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8249 // Okay, we know how many times the containing loop executes. If 8250 // this is a constant evolving PHI node, get the final value at 8251 // the specified iteration number. 8252 Constant *RV = 8253 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8254 if (RV) return getSCEV(RV); 8255 } 8256 } 8257 8258 // If there is a single-input Phi, evaluate it at our scope. If we can 8259 // prove that this replacement does not break LCSSA form, use new value. 8260 if (PN->getNumOperands() == 1) { 8261 const SCEV *Input = getSCEV(PN->getOperand(0)); 8262 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8263 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8264 // for the simplest case just support constants. 8265 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8266 } 8267 } 8268 8269 // Okay, this is an expression that we cannot symbolically evaluate 8270 // into a SCEV. Check to see if it's possible to symbolically evaluate 8271 // the arguments into constants, and if so, try to constant propagate the 8272 // result. This is particularly useful for computing loop exit values. 8273 if (CanConstantFold(I)) { 8274 SmallVector<Constant *, 4> Operands; 8275 bool MadeImprovement = false; 8276 for (Value *Op : I->operands()) { 8277 if (Constant *C = dyn_cast<Constant>(Op)) { 8278 Operands.push_back(C); 8279 continue; 8280 } 8281 8282 // If any of the operands is non-constant and if they are 8283 // non-integer and non-pointer, don't even try to analyze them 8284 // with scev techniques. 8285 if (!isSCEVable(Op->getType())) 8286 return V; 8287 8288 const SCEV *OrigV = getSCEV(Op); 8289 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8290 MadeImprovement |= OrigV != OpV; 8291 8292 Constant *C = BuildConstantFromSCEV(OpV); 8293 if (!C) return V; 8294 if (C->getType() != Op->getType()) 8295 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8296 Op->getType(), 8297 false), 8298 C, Op->getType()); 8299 Operands.push_back(C); 8300 } 8301 8302 // Check to see if getSCEVAtScope actually made an improvement. 8303 if (MadeImprovement) { 8304 Constant *C = nullptr; 8305 const DataLayout &DL = getDataLayout(); 8306 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8307 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8308 Operands[1], DL, &TLI); 8309 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8310 if (!LI->isVolatile()) 8311 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8312 } else 8313 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8314 if (!C) return V; 8315 return getSCEV(C); 8316 } 8317 } 8318 } 8319 8320 // This is some other type of SCEVUnknown, just return it. 8321 return V; 8322 } 8323 8324 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8325 // Avoid performing the look-up in the common case where the specified 8326 // expression has no loop-variant portions. 8327 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8328 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8329 if (OpAtScope != Comm->getOperand(i)) { 8330 // Okay, at least one of these operands is loop variant but might be 8331 // foldable. Build a new instance of the folded commutative expression. 8332 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8333 Comm->op_begin()+i); 8334 NewOps.push_back(OpAtScope); 8335 8336 for (++i; i != e; ++i) { 8337 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8338 NewOps.push_back(OpAtScope); 8339 } 8340 if (isa<SCEVAddExpr>(Comm)) 8341 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8342 if (isa<SCEVMulExpr>(Comm)) 8343 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8344 if (isa<SCEVMinMaxExpr>(Comm)) 8345 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8346 llvm_unreachable("Unknown commutative SCEV type!"); 8347 } 8348 } 8349 // If we got here, all operands are loop invariant. 8350 return Comm; 8351 } 8352 8353 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8354 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8355 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8356 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8357 return Div; // must be loop invariant 8358 return getUDivExpr(LHS, RHS); 8359 } 8360 8361 // If this is a loop recurrence for a loop that does not contain L, then we 8362 // are dealing with the final value computed by the loop. 8363 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8364 // First, attempt to evaluate each operand. 8365 // Avoid performing the look-up in the common case where the specified 8366 // expression has no loop-variant portions. 8367 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8368 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8369 if (OpAtScope == AddRec->getOperand(i)) 8370 continue; 8371 8372 // Okay, at least one of these operands is loop variant but might be 8373 // foldable. Build a new instance of the folded commutative expression. 8374 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8375 AddRec->op_begin()+i); 8376 NewOps.push_back(OpAtScope); 8377 for (++i; i != e; ++i) 8378 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8379 8380 const SCEV *FoldedRec = 8381 getAddRecExpr(NewOps, AddRec->getLoop(), 8382 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8383 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8384 // The addrec may be folded to a nonrecurrence, for example, if the 8385 // induction variable is multiplied by zero after constant folding. Go 8386 // ahead and return the folded value. 8387 if (!AddRec) 8388 return FoldedRec; 8389 break; 8390 } 8391 8392 // If the scope is outside the addrec's loop, evaluate it by using the 8393 // loop exit value of the addrec. 8394 if (!AddRec->getLoop()->contains(L)) { 8395 // To evaluate this recurrence, we need to know how many times the AddRec 8396 // loop iterates. Compute this now. 8397 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8398 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8399 8400 // Then, evaluate the AddRec. 8401 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8402 } 8403 8404 return AddRec; 8405 } 8406 8407 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8408 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8409 if (Op == Cast->getOperand()) 8410 return Cast; // must be loop invariant 8411 return getZeroExtendExpr(Op, Cast->getType()); 8412 } 8413 8414 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8415 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8416 if (Op == Cast->getOperand()) 8417 return Cast; // must be loop invariant 8418 return getSignExtendExpr(Op, Cast->getType()); 8419 } 8420 8421 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8422 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8423 if (Op == Cast->getOperand()) 8424 return Cast; // must be loop invariant 8425 return getTruncateExpr(Op, Cast->getType()); 8426 } 8427 8428 llvm_unreachable("Unknown SCEV type!"); 8429 } 8430 8431 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8432 return getSCEVAtScope(getSCEV(V), L); 8433 } 8434 8435 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8436 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8437 return stripInjectiveFunctions(ZExt->getOperand()); 8438 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8439 return stripInjectiveFunctions(SExt->getOperand()); 8440 return S; 8441 } 8442 8443 /// Finds the minimum unsigned root of the following equation: 8444 /// 8445 /// A * X = B (mod N) 8446 /// 8447 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8448 /// A and B isn't important. 8449 /// 8450 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8451 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8452 ScalarEvolution &SE) { 8453 uint32_t BW = A.getBitWidth(); 8454 assert(BW == SE.getTypeSizeInBits(B->getType())); 8455 assert(A != 0 && "A must be non-zero."); 8456 8457 // 1. D = gcd(A, N) 8458 // 8459 // The gcd of A and N may have only one prime factor: 2. The number of 8460 // trailing zeros in A is its multiplicity 8461 uint32_t Mult2 = A.countTrailingZeros(); 8462 // D = 2^Mult2 8463 8464 // 2. Check if B is divisible by D. 8465 // 8466 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8467 // is not less than multiplicity of this prime factor for D. 8468 if (SE.GetMinTrailingZeros(B) < Mult2) 8469 return SE.getCouldNotCompute(); 8470 8471 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8472 // modulo (N / D). 8473 // 8474 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8475 // (N / D) in general. The inverse itself always fits into BW bits, though, 8476 // so we immediately truncate it. 8477 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8478 APInt Mod(BW + 1, 0); 8479 Mod.setBit(BW - Mult2); // Mod = N / D 8480 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8481 8482 // 4. Compute the minimum unsigned root of the equation: 8483 // I * (B / D) mod (N / D) 8484 // To simplify the computation, we factor out the divide by D: 8485 // (I * B mod N) / D 8486 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8487 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8488 } 8489 8490 /// For a given quadratic addrec, generate coefficients of the corresponding 8491 /// quadratic equation, multiplied by a common value to ensure that they are 8492 /// integers. 8493 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8494 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8495 /// were multiplied by, and BitWidth is the bit width of the original addrec 8496 /// coefficients. 8497 /// This function returns None if the addrec coefficients are not compile- 8498 /// time constants. 8499 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8500 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8501 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8502 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8503 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8504 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8505 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8506 << *AddRec << '\n'); 8507 8508 // We currently can only solve this if the coefficients are constants. 8509 if (!LC || !MC || !NC) { 8510 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8511 return None; 8512 } 8513 8514 APInt L = LC->getAPInt(); 8515 APInt M = MC->getAPInt(); 8516 APInt N = NC->getAPInt(); 8517 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8518 8519 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8520 unsigned NewWidth = BitWidth + 1; 8521 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8522 << BitWidth << '\n'); 8523 // The sign-extension (as opposed to a zero-extension) here matches the 8524 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8525 N = N.sext(NewWidth); 8526 M = M.sext(NewWidth); 8527 L = L.sext(NewWidth); 8528 8529 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8530 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8531 // L+M, L+2M+N, L+3M+3N, ... 8532 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8533 // 8534 // The equation Acc = 0 is then 8535 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8536 // In a quadratic form it becomes: 8537 // N n^2 + (2M-N) n + 2L = 0. 8538 8539 APInt A = N; 8540 APInt B = 2 * M - A; 8541 APInt C = 2 * L; 8542 APInt T = APInt(NewWidth, 2); 8543 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8544 << "x + " << C << ", coeff bw: " << NewWidth 8545 << ", multiplied by " << T << '\n'); 8546 return std::make_tuple(A, B, C, T, BitWidth); 8547 } 8548 8549 /// Helper function to compare optional APInts: 8550 /// (a) if X and Y both exist, return min(X, Y), 8551 /// (b) if neither X nor Y exist, return None, 8552 /// (c) if exactly one of X and Y exists, return that value. 8553 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8554 if (X.hasValue() && Y.hasValue()) { 8555 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8556 APInt XW = X->sextOrSelf(W); 8557 APInt YW = Y->sextOrSelf(W); 8558 return XW.slt(YW) ? *X : *Y; 8559 } 8560 if (!X.hasValue() && !Y.hasValue()) 8561 return None; 8562 return X.hasValue() ? *X : *Y; 8563 } 8564 8565 /// Helper function to truncate an optional APInt to a given BitWidth. 8566 /// When solving addrec-related equations, it is preferable to return a value 8567 /// that has the same bit width as the original addrec's coefficients. If the 8568 /// solution fits in the original bit width, truncate it (except for i1). 8569 /// Returning a value of a different bit width may inhibit some optimizations. 8570 /// 8571 /// In general, a solution to a quadratic equation generated from an addrec 8572 /// may require BW+1 bits, where BW is the bit width of the addrec's 8573 /// coefficients. The reason is that the coefficients of the quadratic 8574 /// equation are BW+1 bits wide (to avoid truncation when converting from 8575 /// the addrec to the equation). 8576 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8577 if (!X.hasValue()) 8578 return None; 8579 unsigned W = X->getBitWidth(); 8580 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8581 return X->trunc(BitWidth); 8582 return X; 8583 } 8584 8585 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8586 /// iterations. The values L, M, N are assumed to be signed, and they 8587 /// should all have the same bit widths. 8588 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8589 /// where BW is the bit width of the addrec's coefficients. 8590 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8591 /// returned as such, otherwise the bit width of the returned value may 8592 /// be greater than BW. 8593 /// 8594 /// This function returns None if 8595 /// (a) the addrec coefficients are not constant, or 8596 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8597 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8598 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8599 static Optional<APInt> 8600 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8601 APInt A, B, C, M; 8602 unsigned BitWidth; 8603 auto T = GetQuadraticEquation(AddRec); 8604 if (!T.hasValue()) 8605 return None; 8606 8607 std::tie(A, B, C, M, BitWidth) = *T; 8608 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8609 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8610 if (!X.hasValue()) 8611 return None; 8612 8613 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8614 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8615 if (!V->isZero()) 8616 return None; 8617 8618 return TruncIfPossible(X, BitWidth); 8619 } 8620 8621 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8622 /// iterations. The values M, N are assumed to be signed, and they 8623 /// should all have the same bit widths. 8624 /// Find the least n such that c(n) does not belong to the given range, 8625 /// while c(n-1) does. 8626 /// 8627 /// This function returns None if 8628 /// (a) the addrec coefficients are not constant, or 8629 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8630 /// bounds of the range. 8631 static Optional<APInt> 8632 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8633 const ConstantRange &Range, ScalarEvolution &SE) { 8634 assert(AddRec->getOperand(0)->isZero() && 8635 "Starting value of addrec should be 0"); 8636 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8637 << Range << ", addrec " << *AddRec << '\n'); 8638 // This case is handled in getNumIterationsInRange. Here we can assume that 8639 // we start in the range. 8640 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8641 "Addrec's initial value should be in range"); 8642 8643 APInt A, B, C, M; 8644 unsigned BitWidth; 8645 auto T = GetQuadraticEquation(AddRec); 8646 if (!T.hasValue()) 8647 return None; 8648 8649 // Be careful about the return value: there can be two reasons for not 8650 // returning an actual number. First, if no solutions to the equations 8651 // were found, and second, if the solutions don't leave the given range. 8652 // The first case means that the actual solution is "unknown", the second 8653 // means that it's known, but not valid. If the solution is unknown, we 8654 // cannot make any conclusions. 8655 // Return a pair: the optional solution and a flag indicating if the 8656 // solution was found. 8657 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8658 // Solve for signed overflow and unsigned overflow, pick the lower 8659 // solution. 8660 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8661 << Bound << " (before multiplying by " << M << ")\n"); 8662 Bound *= M; // The quadratic equation multiplier. 8663 8664 Optional<APInt> SO = None; 8665 if (BitWidth > 1) { 8666 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8667 "signed overflow\n"); 8668 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8669 } 8670 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8671 "unsigned overflow\n"); 8672 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8673 BitWidth+1); 8674 8675 auto LeavesRange = [&] (const APInt &X) { 8676 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8677 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8678 if (Range.contains(V0->getValue())) 8679 return false; 8680 // X should be at least 1, so X-1 is non-negative. 8681 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8682 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8683 if (Range.contains(V1->getValue())) 8684 return true; 8685 return false; 8686 }; 8687 8688 // If SolveQuadraticEquationWrap returns None, it means that there can 8689 // be a solution, but the function failed to find it. We cannot treat it 8690 // as "no solution". 8691 if (!SO.hasValue() || !UO.hasValue()) 8692 return { None, false }; 8693 8694 // Check the smaller value first to see if it leaves the range. 8695 // At this point, both SO and UO must have values. 8696 Optional<APInt> Min = MinOptional(SO, UO); 8697 if (LeavesRange(*Min)) 8698 return { Min, true }; 8699 Optional<APInt> Max = Min == SO ? UO : SO; 8700 if (LeavesRange(*Max)) 8701 return { Max, true }; 8702 8703 // Solutions were found, but were eliminated, hence the "true". 8704 return { None, true }; 8705 }; 8706 8707 std::tie(A, B, C, M, BitWidth) = *T; 8708 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8709 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8710 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8711 auto SL = SolveForBoundary(Lower); 8712 auto SU = SolveForBoundary(Upper); 8713 // If any of the solutions was unknown, no meaninigful conclusions can 8714 // be made. 8715 if (!SL.second || !SU.second) 8716 return None; 8717 8718 // Claim: The correct solution is not some value between Min and Max. 8719 // 8720 // Justification: Assuming that Min and Max are different values, one of 8721 // them is when the first signed overflow happens, the other is when the 8722 // first unsigned overflow happens. Crossing the range boundary is only 8723 // possible via an overflow (treating 0 as a special case of it, modeling 8724 // an overflow as crossing k*2^W for some k). 8725 // 8726 // The interesting case here is when Min was eliminated as an invalid 8727 // solution, but Max was not. The argument is that if there was another 8728 // overflow between Min and Max, it would also have been eliminated if 8729 // it was considered. 8730 // 8731 // For a given boundary, it is possible to have two overflows of the same 8732 // type (signed/unsigned) without having the other type in between: this 8733 // can happen when the vertex of the parabola is between the iterations 8734 // corresponding to the overflows. This is only possible when the two 8735 // overflows cross k*2^W for the same k. In such case, if the second one 8736 // left the range (and was the first one to do so), the first overflow 8737 // would have to enter the range, which would mean that either we had left 8738 // the range before or that we started outside of it. Both of these cases 8739 // are contradictions. 8740 // 8741 // Claim: In the case where SolveForBoundary returns None, the correct 8742 // solution is not some value between the Max for this boundary and the 8743 // Min of the other boundary. 8744 // 8745 // Justification: Assume that we had such Max_A and Min_B corresponding 8746 // to range boundaries A and B and such that Max_A < Min_B. If there was 8747 // a solution between Max_A and Min_B, it would have to be caused by an 8748 // overflow corresponding to either A or B. It cannot correspond to B, 8749 // since Min_B is the first occurrence of such an overflow. If it 8750 // corresponded to A, it would have to be either a signed or an unsigned 8751 // overflow that is larger than both eliminated overflows for A. But 8752 // between the eliminated overflows and this overflow, the values would 8753 // cover the entire value space, thus crossing the other boundary, which 8754 // is a contradiction. 8755 8756 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8757 } 8758 8759 ScalarEvolution::ExitLimit 8760 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8761 bool AllowPredicates) { 8762 8763 // This is only used for loops with a "x != y" exit test. The exit condition 8764 // is now expressed as a single expression, V = x-y. So the exit test is 8765 // effectively V != 0. We know and take advantage of the fact that this 8766 // expression only being used in a comparison by zero context. 8767 8768 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8769 // If the value is a constant 8770 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8771 // If the value is already zero, the branch will execute zero times. 8772 if (C->getValue()->isZero()) return C; 8773 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8774 } 8775 8776 const SCEVAddRecExpr *AddRec = 8777 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8778 8779 if (!AddRec && AllowPredicates) 8780 // Try to make this an AddRec using runtime tests, in the first X 8781 // iterations of this loop, where X is the SCEV expression found by the 8782 // algorithm below. 8783 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8784 8785 if (!AddRec || AddRec->getLoop() != L) 8786 return getCouldNotCompute(); 8787 8788 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8789 // the quadratic equation to solve it. 8790 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8791 // We can only use this value if the chrec ends up with an exact zero 8792 // value at this index. When solving for "X*X != 5", for example, we 8793 // should not accept a root of 2. 8794 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8795 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8796 return ExitLimit(R, R, false, Predicates); 8797 } 8798 return getCouldNotCompute(); 8799 } 8800 8801 // Otherwise we can only handle this if it is affine. 8802 if (!AddRec->isAffine()) 8803 return getCouldNotCompute(); 8804 8805 // If this is an affine expression, the execution count of this branch is 8806 // the minimum unsigned root of the following equation: 8807 // 8808 // Start + Step*N = 0 (mod 2^BW) 8809 // 8810 // equivalent to: 8811 // 8812 // Step*N = -Start (mod 2^BW) 8813 // 8814 // where BW is the common bit width of Start and Step. 8815 8816 // Get the initial value for the loop. 8817 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8818 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8819 8820 // For now we handle only constant steps. 8821 // 8822 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8823 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8824 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8825 // We have not yet seen any such cases. 8826 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8827 if (!StepC || StepC->getValue()->isZero()) 8828 return getCouldNotCompute(); 8829 8830 // For positive steps (counting up until unsigned overflow): 8831 // N = -Start/Step (as unsigned) 8832 // For negative steps (counting down to zero): 8833 // N = Start/-Step 8834 // First compute the unsigned distance from zero in the direction of Step. 8835 bool CountDown = StepC->getAPInt().isNegative(); 8836 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8837 8838 // Handle unitary steps, which cannot wraparound. 8839 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8840 // N = Distance (as unsigned) 8841 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8842 APInt MaxBECount = getUnsignedRangeMax(Distance); 8843 8844 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8845 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8846 // case, and see if we can improve the bound. 8847 // 8848 // Explicitly handling this here is necessary because getUnsignedRange 8849 // isn't context-sensitive; it doesn't know that we only care about the 8850 // range inside the loop. 8851 const SCEV *Zero = getZero(Distance->getType()); 8852 const SCEV *One = getOne(Distance->getType()); 8853 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8854 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8855 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8856 // as "unsigned_max(Distance + 1) - 1". 8857 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8858 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8859 } 8860 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8861 } 8862 8863 // If the condition controls loop exit (the loop exits only if the expression 8864 // is true) and the addition is no-wrap we can use unsigned divide to 8865 // compute the backedge count. In this case, the step may not divide the 8866 // distance, but we don't care because if the condition is "missed" the loop 8867 // will have undefined behavior due to wrapping. 8868 if (ControlsExit && AddRec->hasNoSelfWrap() && 8869 loopHasNoAbnormalExits(AddRec->getLoop())) { 8870 const SCEV *Exact = 8871 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8872 const SCEV *Max = 8873 Exact == getCouldNotCompute() 8874 ? Exact 8875 : getConstant(getUnsignedRangeMax(Exact)); 8876 return ExitLimit(Exact, Max, false, Predicates); 8877 } 8878 8879 // Solve the general equation. 8880 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8881 getNegativeSCEV(Start), *this); 8882 const SCEV *M = E == getCouldNotCompute() 8883 ? E 8884 : getConstant(getUnsignedRangeMax(E)); 8885 return ExitLimit(E, M, false, Predicates); 8886 } 8887 8888 ScalarEvolution::ExitLimit 8889 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8890 // Loops that look like: while (X == 0) are very strange indeed. We don't 8891 // handle them yet except for the trivial case. This could be expanded in the 8892 // future as needed. 8893 8894 // If the value is a constant, check to see if it is known to be non-zero 8895 // already. If so, the backedge will execute zero times. 8896 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8897 if (!C->getValue()->isZero()) 8898 return getZero(C->getType()); 8899 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8900 } 8901 8902 // We could implement others, but I really doubt anyone writes loops like 8903 // this, and if they did, they would already be constant folded. 8904 return getCouldNotCompute(); 8905 } 8906 8907 std::pair<BasicBlock *, BasicBlock *> 8908 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8909 // If the block has a unique predecessor, then there is no path from the 8910 // predecessor to the block that does not go through the direct edge 8911 // from the predecessor to the block. 8912 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8913 return {Pred, BB}; 8914 8915 // A loop's header is defined to be a block that dominates the loop. 8916 // If the header has a unique predecessor outside the loop, it must be 8917 // a block that has exactly one successor that can reach the loop. 8918 if (Loop *L = LI.getLoopFor(BB)) 8919 return {L->getLoopPredecessor(), L->getHeader()}; 8920 8921 return {nullptr, nullptr}; 8922 } 8923 8924 /// SCEV structural equivalence is usually sufficient for testing whether two 8925 /// expressions are equal, however for the purposes of looking for a condition 8926 /// guarding a loop, it can be useful to be a little more general, since a 8927 /// front-end may have replicated the controlling expression. 8928 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8929 // Quick check to see if they are the same SCEV. 8930 if (A == B) return true; 8931 8932 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8933 // Not all instructions that are "identical" compute the same value. For 8934 // instance, two distinct alloca instructions allocating the same type are 8935 // identical and do not read memory; but compute distinct values. 8936 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8937 }; 8938 8939 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8940 // two different instructions with the same value. Check for this case. 8941 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8942 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8943 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8944 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8945 if (ComputesEqualValues(AI, BI)) 8946 return true; 8947 8948 // Otherwise assume they may have a different value. 8949 return false; 8950 } 8951 8952 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8953 const SCEV *&LHS, const SCEV *&RHS, 8954 unsigned Depth) { 8955 bool Changed = false; 8956 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8957 // '0 != 0'. 8958 auto TrivialCase = [&](bool TriviallyTrue) { 8959 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8960 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8961 return true; 8962 }; 8963 // If we hit the max recursion limit bail out. 8964 if (Depth >= 3) 8965 return false; 8966 8967 // Canonicalize a constant to the right side. 8968 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8969 // Check for both operands constant. 8970 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8971 if (ConstantExpr::getICmp(Pred, 8972 LHSC->getValue(), 8973 RHSC->getValue())->isNullValue()) 8974 return TrivialCase(false); 8975 else 8976 return TrivialCase(true); 8977 } 8978 // Otherwise swap the operands to put the constant on the right. 8979 std::swap(LHS, RHS); 8980 Pred = ICmpInst::getSwappedPredicate(Pred); 8981 Changed = true; 8982 } 8983 8984 // If we're comparing an addrec with a value which is loop-invariant in the 8985 // addrec's loop, put the addrec on the left. Also make a dominance check, 8986 // as both operands could be addrecs loop-invariant in each other's loop. 8987 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8988 const Loop *L = AR->getLoop(); 8989 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8990 std::swap(LHS, RHS); 8991 Pred = ICmpInst::getSwappedPredicate(Pred); 8992 Changed = true; 8993 } 8994 } 8995 8996 // If there's a constant operand, canonicalize comparisons with boundary 8997 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8998 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8999 const APInt &RA = RC->getAPInt(); 9000 9001 bool SimplifiedByConstantRange = false; 9002 9003 if (!ICmpInst::isEquality(Pred)) { 9004 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9005 if (ExactCR.isFullSet()) 9006 return TrivialCase(true); 9007 else if (ExactCR.isEmptySet()) 9008 return TrivialCase(false); 9009 9010 APInt NewRHS; 9011 CmpInst::Predicate NewPred; 9012 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9013 ICmpInst::isEquality(NewPred)) { 9014 // We were able to convert an inequality to an equality. 9015 Pred = NewPred; 9016 RHS = getConstant(NewRHS); 9017 Changed = SimplifiedByConstantRange = true; 9018 } 9019 } 9020 9021 if (!SimplifiedByConstantRange) { 9022 switch (Pred) { 9023 default: 9024 break; 9025 case ICmpInst::ICMP_EQ: 9026 case ICmpInst::ICMP_NE: 9027 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9028 if (!RA) 9029 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9030 if (const SCEVMulExpr *ME = 9031 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9032 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9033 ME->getOperand(0)->isAllOnesValue()) { 9034 RHS = AE->getOperand(1); 9035 LHS = ME->getOperand(1); 9036 Changed = true; 9037 } 9038 break; 9039 9040 9041 // The "Should have been caught earlier!" messages refer to the fact 9042 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9043 // should have fired on the corresponding cases, and canonicalized the 9044 // check to trivial case. 9045 9046 case ICmpInst::ICMP_UGE: 9047 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9048 Pred = ICmpInst::ICMP_UGT; 9049 RHS = getConstant(RA - 1); 9050 Changed = true; 9051 break; 9052 case ICmpInst::ICMP_ULE: 9053 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9054 Pred = ICmpInst::ICMP_ULT; 9055 RHS = getConstant(RA + 1); 9056 Changed = true; 9057 break; 9058 case ICmpInst::ICMP_SGE: 9059 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9060 Pred = ICmpInst::ICMP_SGT; 9061 RHS = getConstant(RA - 1); 9062 Changed = true; 9063 break; 9064 case ICmpInst::ICMP_SLE: 9065 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9066 Pred = ICmpInst::ICMP_SLT; 9067 RHS = getConstant(RA + 1); 9068 Changed = true; 9069 break; 9070 } 9071 } 9072 } 9073 9074 // Check for obvious equality. 9075 if (HasSameValue(LHS, RHS)) { 9076 if (ICmpInst::isTrueWhenEqual(Pred)) 9077 return TrivialCase(true); 9078 if (ICmpInst::isFalseWhenEqual(Pred)) 9079 return TrivialCase(false); 9080 } 9081 9082 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9083 // adding or subtracting 1 from one of the operands. 9084 switch (Pred) { 9085 case ICmpInst::ICMP_SLE: 9086 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9087 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9088 SCEV::FlagNSW); 9089 Pred = ICmpInst::ICMP_SLT; 9090 Changed = true; 9091 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9092 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9093 SCEV::FlagNSW); 9094 Pred = ICmpInst::ICMP_SLT; 9095 Changed = true; 9096 } 9097 break; 9098 case ICmpInst::ICMP_SGE: 9099 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9100 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9101 SCEV::FlagNSW); 9102 Pred = ICmpInst::ICMP_SGT; 9103 Changed = true; 9104 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9105 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9106 SCEV::FlagNSW); 9107 Pred = ICmpInst::ICMP_SGT; 9108 Changed = true; 9109 } 9110 break; 9111 case ICmpInst::ICMP_ULE: 9112 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9113 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9114 SCEV::FlagNUW); 9115 Pred = ICmpInst::ICMP_ULT; 9116 Changed = true; 9117 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9118 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9119 Pred = ICmpInst::ICMP_ULT; 9120 Changed = true; 9121 } 9122 break; 9123 case ICmpInst::ICMP_UGE: 9124 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9125 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9126 Pred = ICmpInst::ICMP_UGT; 9127 Changed = true; 9128 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9129 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9130 SCEV::FlagNUW); 9131 Pred = ICmpInst::ICMP_UGT; 9132 Changed = true; 9133 } 9134 break; 9135 default: 9136 break; 9137 } 9138 9139 // TODO: More simplifications are possible here. 9140 9141 // Recursively simplify until we either hit a recursion limit or nothing 9142 // changes. 9143 if (Changed) 9144 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9145 9146 return Changed; 9147 } 9148 9149 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9150 return getSignedRangeMax(S).isNegative(); 9151 } 9152 9153 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9154 return getSignedRangeMin(S).isStrictlyPositive(); 9155 } 9156 9157 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9158 return !getSignedRangeMin(S).isNegative(); 9159 } 9160 9161 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9162 return !getSignedRangeMax(S).isStrictlyPositive(); 9163 } 9164 9165 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9166 return isKnownNegative(S) || isKnownPositive(S); 9167 } 9168 9169 std::pair<const SCEV *, const SCEV *> 9170 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9171 // Compute SCEV on entry of loop L. 9172 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9173 if (Start == getCouldNotCompute()) 9174 return { Start, Start }; 9175 // Compute post increment SCEV for loop L. 9176 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9177 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9178 return { Start, PostInc }; 9179 } 9180 9181 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9182 const SCEV *LHS, const SCEV *RHS) { 9183 // First collect all loops. 9184 SmallPtrSet<const Loop *, 8> LoopsUsed; 9185 getUsedLoops(LHS, LoopsUsed); 9186 getUsedLoops(RHS, LoopsUsed); 9187 9188 if (LoopsUsed.empty()) 9189 return false; 9190 9191 // Domination relationship must be a linear order on collected loops. 9192 #ifndef NDEBUG 9193 for (auto *L1 : LoopsUsed) 9194 for (auto *L2 : LoopsUsed) 9195 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9196 DT.dominates(L2->getHeader(), L1->getHeader())) && 9197 "Domination relationship is not a linear order"); 9198 #endif 9199 9200 const Loop *MDL = 9201 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9202 [&](const Loop *L1, const Loop *L2) { 9203 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9204 }); 9205 9206 // Get init and post increment value for LHS. 9207 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9208 // if LHS contains unknown non-invariant SCEV then bail out. 9209 if (SplitLHS.first == getCouldNotCompute()) 9210 return false; 9211 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9212 // Get init and post increment value for RHS. 9213 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9214 // if RHS contains unknown non-invariant SCEV then bail out. 9215 if (SplitRHS.first == getCouldNotCompute()) 9216 return false; 9217 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9218 // It is possible that init SCEV contains an invariant load but it does 9219 // not dominate MDL and is not available at MDL loop entry, so we should 9220 // check it here. 9221 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9222 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9223 return false; 9224 9225 // It seems backedge guard check is faster than entry one so in some cases 9226 // it can speed up whole estimation by short circuit 9227 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9228 SplitRHS.second) && 9229 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9230 } 9231 9232 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9233 const SCEV *LHS, const SCEV *RHS) { 9234 // Canonicalize the inputs first. 9235 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9236 9237 if (isKnownViaInduction(Pred, LHS, RHS)) 9238 return true; 9239 9240 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9241 return true; 9242 9243 // Otherwise see what can be done with some simple reasoning. 9244 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9245 } 9246 9247 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9248 const SCEVAddRecExpr *LHS, 9249 const SCEV *RHS) { 9250 const Loop *L = LHS->getLoop(); 9251 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9252 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9253 } 9254 9255 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9256 ICmpInst::Predicate Pred, 9257 bool &Increasing) { 9258 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9259 9260 #ifndef NDEBUG 9261 // Verify an invariant: inverting the predicate should turn a monotonically 9262 // increasing change to a monotonically decreasing one, and vice versa. 9263 bool IncreasingSwapped; 9264 bool ResultSwapped = isMonotonicPredicateImpl( 9265 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9266 9267 assert(Result == ResultSwapped && "should be able to analyze both!"); 9268 if (ResultSwapped) 9269 assert(Increasing == !IncreasingSwapped && 9270 "monotonicity should flip as we flip the predicate"); 9271 #endif 9272 9273 return Result; 9274 } 9275 9276 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9277 ICmpInst::Predicate Pred, 9278 bool &Increasing) { 9279 9280 // A zero step value for LHS means the induction variable is essentially a 9281 // loop invariant value. We don't really depend on the predicate actually 9282 // flipping from false to true (for increasing predicates, and the other way 9283 // around for decreasing predicates), all we care about is that *if* the 9284 // predicate changes then it only changes from false to true. 9285 // 9286 // A zero step value in itself is not very useful, but there may be places 9287 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9288 // as general as possible. 9289 9290 switch (Pred) { 9291 default: 9292 return false; // Conservative answer 9293 9294 case ICmpInst::ICMP_UGT: 9295 case ICmpInst::ICMP_UGE: 9296 case ICmpInst::ICMP_ULT: 9297 case ICmpInst::ICMP_ULE: 9298 if (!LHS->hasNoUnsignedWrap()) 9299 return false; 9300 9301 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9302 return true; 9303 9304 case ICmpInst::ICMP_SGT: 9305 case ICmpInst::ICMP_SGE: 9306 case ICmpInst::ICMP_SLT: 9307 case ICmpInst::ICMP_SLE: { 9308 if (!LHS->hasNoSignedWrap()) 9309 return false; 9310 9311 const SCEV *Step = LHS->getStepRecurrence(*this); 9312 9313 if (isKnownNonNegative(Step)) { 9314 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9315 return true; 9316 } 9317 9318 if (isKnownNonPositive(Step)) { 9319 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9320 return true; 9321 } 9322 9323 return false; 9324 } 9325 9326 } 9327 9328 llvm_unreachable("switch has default clause!"); 9329 } 9330 9331 bool ScalarEvolution::isLoopInvariantPredicate( 9332 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9333 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9334 const SCEV *&InvariantRHS) { 9335 9336 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9337 if (!isLoopInvariant(RHS, L)) { 9338 if (!isLoopInvariant(LHS, L)) 9339 return false; 9340 9341 std::swap(LHS, RHS); 9342 Pred = ICmpInst::getSwappedPredicate(Pred); 9343 } 9344 9345 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9346 if (!ArLHS || ArLHS->getLoop() != L) 9347 return false; 9348 9349 bool Increasing; 9350 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9351 return false; 9352 9353 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9354 // true as the loop iterates, and the backedge is control dependent on 9355 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9356 // 9357 // * if the predicate was false in the first iteration then the predicate 9358 // is never evaluated again, since the loop exits without taking the 9359 // backedge. 9360 // * if the predicate was true in the first iteration then it will 9361 // continue to be true for all future iterations since it is 9362 // monotonically increasing. 9363 // 9364 // For both the above possibilities, we can replace the loop varying 9365 // predicate with its value on the first iteration of the loop (which is 9366 // loop invariant). 9367 // 9368 // A similar reasoning applies for a monotonically decreasing predicate, by 9369 // replacing true with false and false with true in the above two bullets. 9370 9371 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9372 9373 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9374 return false; 9375 9376 InvariantPred = Pred; 9377 InvariantLHS = ArLHS->getStart(); 9378 InvariantRHS = RHS; 9379 return true; 9380 } 9381 9382 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9383 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9384 if (HasSameValue(LHS, RHS)) 9385 return ICmpInst::isTrueWhenEqual(Pred); 9386 9387 // This code is split out from isKnownPredicate because it is called from 9388 // within isLoopEntryGuardedByCond. 9389 9390 auto CheckRanges = 9391 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9392 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9393 .contains(RangeLHS); 9394 }; 9395 9396 // The check at the top of the function catches the case where the values are 9397 // known to be equal. 9398 if (Pred == CmpInst::ICMP_EQ) 9399 return false; 9400 9401 if (Pred == CmpInst::ICMP_NE) 9402 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9403 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9404 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9405 9406 if (CmpInst::isSigned(Pred)) 9407 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9408 9409 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9410 } 9411 9412 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9413 const SCEV *LHS, 9414 const SCEV *RHS) { 9415 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9416 // Return Y via OutY. 9417 auto MatchBinaryAddToConst = 9418 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9419 SCEV::NoWrapFlags ExpectedFlags) { 9420 const SCEV *NonConstOp, *ConstOp; 9421 SCEV::NoWrapFlags FlagsPresent; 9422 9423 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9424 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9425 return false; 9426 9427 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9428 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9429 }; 9430 9431 APInt C; 9432 9433 switch (Pred) { 9434 default: 9435 break; 9436 9437 case ICmpInst::ICMP_SGE: 9438 std::swap(LHS, RHS); 9439 LLVM_FALLTHROUGH; 9440 case ICmpInst::ICMP_SLE: 9441 // X s<= (X + C)<nsw> if C >= 0 9442 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9443 return true; 9444 9445 // (X + C)<nsw> s<= X if C <= 0 9446 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9447 !C.isStrictlyPositive()) 9448 return true; 9449 break; 9450 9451 case ICmpInst::ICMP_SGT: 9452 std::swap(LHS, RHS); 9453 LLVM_FALLTHROUGH; 9454 case ICmpInst::ICMP_SLT: 9455 // X s< (X + C)<nsw> if C > 0 9456 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9457 C.isStrictlyPositive()) 9458 return true; 9459 9460 // (X + C)<nsw> s< X if C < 0 9461 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9462 return true; 9463 break; 9464 } 9465 9466 return false; 9467 } 9468 9469 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9470 const SCEV *LHS, 9471 const SCEV *RHS) { 9472 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9473 return false; 9474 9475 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9476 // the stack can result in exponential time complexity. 9477 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9478 9479 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9480 // 9481 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9482 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9483 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9484 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9485 // use isKnownPredicate later if needed. 9486 return isKnownNonNegative(RHS) && 9487 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9488 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9489 } 9490 9491 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9492 ICmpInst::Predicate Pred, 9493 const SCEV *LHS, const SCEV *RHS) { 9494 // No need to even try if we know the module has no guards. 9495 if (!HasGuards) 9496 return false; 9497 9498 return any_of(*BB, [&](Instruction &I) { 9499 using namespace llvm::PatternMatch; 9500 9501 Value *Condition; 9502 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9503 m_Value(Condition))) && 9504 isImpliedCond(Pred, LHS, RHS, Condition, false); 9505 }); 9506 } 9507 9508 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9509 /// protected by a conditional between LHS and RHS. This is used to 9510 /// to eliminate casts. 9511 bool 9512 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9513 ICmpInst::Predicate Pred, 9514 const SCEV *LHS, const SCEV *RHS) { 9515 // Interpret a null as meaning no loop, where there is obviously no guard 9516 // (interprocedural conditions notwithstanding). 9517 if (!L) return true; 9518 9519 if (VerifyIR) 9520 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9521 "This cannot be done on broken IR!"); 9522 9523 9524 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9525 return true; 9526 9527 BasicBlock *Latch = L->getLoopLatch(); 9528 if (!Latch) 9529 return false; 9530 9531 BranchInst *LoopContinuePredicate = 9532 dyn_cast<BranchInst>(Latch->getTerminator()); 9533 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9534 isImpliedCond(Pred, LHS, RHS, 9535 LoopContinuePredicate->getCondition(), 9536 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9537 return true; 9538 9539 // We don't want more than one activation of the following loops on the stack 9540 // -- that can lead to O(n!) time complexity. 9541 if (WalkingBEDominatingConds) 9542 return false; 9543 9544 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9545 9546 // See if we can exploit a trip count to prove the predicate. 9547 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9548 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9549 if (LatchBECount != getCouldNotCompute()) { 9550 // We know that Latch branches back to the loop header exactly 9551 // LatchBECount times. This means the backdege condition at Latch is 9552 // equivalent to "{0,+,1} u< LatchBECount". 9553 Type *Ty = LatchBECount->getType(); 9554 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9555 const SCEV *LoopCounter = 9556 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9557 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9558 LatchBECount)) 9559 return true; 9560 } 9561 9562 // Check conditions due to any @llvm.assume intrinsics. 9563 for (auto &AssumeVH : AC.assumptions()) { 9564 if (!AssumeVH) 9565 continue; 9566 auto *CI = cast<CallInst>(AssumeVH); 9567 if (!DT.dominates(CI, Latch->getTerminator())) 9568 continue; 9569 9570 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9571 return true; 9572 } 9573 9574 // If the loop is not reachable from the entry block, we risk running into an 9575 // infinite loop as we walk up into the dom tree. These loops do not matter 9576 // anyway, so we just return a conservative answer when we see them. 9577 if (!DT.isReachableFromEntry(L->getHeader())) 9578 return false; 9579 9580 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9581 return true; 9582 9583 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9584 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9585 assert(DTN && "should reach the loop header before reaching the root!"); 9586 9587 BasicBlock *BB = DTN->getBlock(); 9588 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9589 return true; 9590 9591 BasicBlock *PBB = BB->getSinglePredecessor(); 9592 if (!PBB) 9593 continue; 9594 9595 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9596 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9597 continue; 9598 9599 Value *Condition = ContinuePredicate->getCondition(); 9600 9601 // If we have an edge `E` within the loop body that dominates the only 9602 // latch, the condition guarding `E` also guards the backedge. This 9603 // reasoning works only for loops with a single latch. 9604 9605 BasicBlockEdge DominatingEdge(PBB, BB); 9606 if (DominatingEdge.isSingleEdge()) { 9607 // We're constructively (and conservatively) enumerating edges within the 9608 // loop body that dominate the latch. The dominator tree better agree 9609 // with us on this: 9610 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9611 9612 if (isImpliedCond(Pred, LHS, RHS, Condition, 9613 BB != ContinuePredicate->getSuccessor(0))) 9614 return true; 9615 } 9616 } 9617 9618 return false; 9619 } 9620 9621 bool 9622 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9623 ICmpInst::Predicate Pred, 9624 const SCEV *LHS, const SCEV *RHS) { 9625 // Interpret a null as meaning no loop, where there is obviously no guard 9626 // (interprocedural conditions notwithstanding). 9627 if (!L) return false; 9628 9629 if (VerifyIR) 9630 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9631 "This cannot be done on broken IR!"); 9632 9633 // Both LHS and RHS must be available at loop entry. 9634 assert(isAvailableAtLoopEntry(LHS, L) && 9635 "LHS is not available at Loop Entry"); 9636 assert(isAvailableAtLoopEntry(RHS, L) && 9637 "RHS is not available at Loop Entry"); 9638 9639 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9640 return true; 9641 9642 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9643 // the facts (a >= b && a != b) separately. A typical situation is when the 9644 // non-strict comparison is known from ranges and non-equality is known from 9645 // dominating predicates. If we are proving strict comparison, we always try 9646 // to prove non-equality and non-strict comparison separately. 9647 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9648 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9649 bool ProvedNonStrictComparison = false; 9650 bool ProvedNonEquality = false; 9651 9652 if (ProvingStrictComparison) { 9653 ProvedNonStrictComparison = 9654 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9655 ProvedNonEquality = 9656 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9657 if (ProvedNonStrictComparison && ProvedNonEquality) 9658 return true; 9659 } 9660 9661 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9662 auto ProveViaGuard = [&](BasicBlock *Block) { 9663 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9664 return true; 9665 if (ProvingStrictComparison) { 9666 if (!ProvedNonStrictComparison) 9667 ProvedNonStrictComparison = 9668 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9669 if (!ProvedNonEquality) 9670 ProvedNonEquality = 9671 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9672 if (ProvedNonStrictComparison && ProvedNonEquality) 9673 return true; 9674 } 9675 return false; 9676 }; 9677 9678 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9679 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9680 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9681 return true; 9682 if (ProvingStrictComparison) { 9683 if (!ProvedNonStrictComparison) 9684 ProvedNonStrictComparison = 9685 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9686 if (!ProvedNonEquality) 9687 ProvedNonEquality = 9688 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9689 if (ProvedNonStrictComparison && ProvedNonEquality) 9690 return true; 9691 } 9692 return false; 9693 }; 9694 9695 // Starting at the loop predecessor, climb up the predecessor chain, as long 9696 // as there are predecessors that can be found that have unique successors 9697 // leading to the original header. 9698 for (std::pair<BasicBlock *, BasicBlock *> 9699 Pair(L->getLoopPredecessor(), L->getHeader()); 9700 Pair.first; 9701 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9702 9703 if (ProveViaGuard(Pair.first)) 9704 return true; 9705 9706 BranchInst *LoopEntryPredicate = 9707 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9708 if (!LoopEntryPredicate || 9709 LoopEntryPredicate->isUnconditional()) 9710 continue; 9711 9712 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9713 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9714 return true; 9715 } 9716 9717 // Check conditions due to any @llvm.assume intrinsics. 9718 for (auto &AssumeVH : AC.assumptions()) { 9719 if (!AssumeVH) 9720 continue; 9721 auto *CI = cast<CallInst>(AssumeVH); 9722 if (!DT.dominates(CI, L->getHeader())) 9723 continue; 9724 9725 if (ProveViaCond(CI->getArgOperand(0), false)) 9726 return true; 9727 } 9728 9729 return false; 9730 } 9731 9732 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9733 const SCEV *LHS, const SCEV *RHS, 9734 Value *FoundCondValue, 9735 bool Inverse) { 9736 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9737 return false; 9738 9739 auto ClearOnExit = 9740 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9741 9742 // Recursively handle And and Or conditions. 9743 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9744 if (BO->getOpcode() == Instruction::And) { 9745 if (!Inverse) 9746 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9747 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9748 } else if (BO->getOpcode() == Instruction::Or) { 9749 if (Inverse) 9750 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9751 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9752 } 9753 } 9754 9755 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9756 if (!ICI) return false; 9757 9758 // Now that we found a conditional branch that dominates the loop or controls 9759 // the loop latch. Check to see if it is the comparison we are looking for. 9760 ICmpInst::Predicate FoundPred; 9761 if (Inverse) 9762 FoundPred = ICI->getInversePredicate(); 9763 else 9764 FoundPred = ICI->getPredicate(); 9765 9766 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9767 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9768 9769 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9770 } 9771 9772 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9773 const SCEV *RHS, 9774 ICmpInst::Predicate FoundPred, 9775 const SCEV *FoundLHS, 9776 const SCEV *FoundRHS) { 9777 // Balance the types. 9778 if (getTypeSizeInBits(LHS->getType()) < 9779 getTypeSizeInBits(FoundLHS->getType())) { 9780 if (CmpInst::isSigned(Pred)) { 9781 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9782 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9783 } else { 9784 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9785 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9786 } 9787 } else if (getTypeSizeInBits(LHS->getType()) > 9788 getTypeSizeInBits(FoundLHS->getType())) { 9789 if (CmpInst::isSigned(FoundPred)) { 9790 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9791 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9792 } else { 9793 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9794 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9795 } 9796 } 9797 9798 // Canonicalize the query to match the way instcombine will have 9799 // canonicalized the comparison. 9800 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9801 if (LHS == RHS) 9802 return CmpInst::isTrueWhenEqual(Pred); 9803 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9804 if (FoundLHS == FoundRHS) 9805 return CmpInst::isFalseWhenEqual(FoundPred); 9806 9807 // Check to see if we can make the LHS or RHS match. 9808 if (LHS == FoundRHS || RHS == FoundLHS) { 9809 if (isa<SCEVConstant>(RHS)) { 9810 std::swap(FoundLHS, FoundRHS); 9811 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9812 } else { 9813 std::swap(LHS, RHS); 9814 Pred = ICmpInst::getSwappedPredicate(Pred); 9815 } 9816 } 9817 9818 // Check whether the found predicate is the same as the desired predicate. 9819 if (FoundPred == Pred) 9820 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9821 9822 // Check whether swapping the found predicate makes it the same as the 9823 // desired predicate. 9824 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9825 if (isa<SCEVConstant>(RHS)) 9826 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9827 else 9828 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9829 RHS, LHS, FoundLHS, FoundRHS); 9830 } 9831 9832 // Unsigned comparison is the same as signed comparison when both the operands 9833 // are non-negative. 9834 if (CmpInst::isUnsigned(FoundPred) && 9835 CmpInst::getSignedPredicate(FoundPred) == Pred && 9836 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9837 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9838 9839 // Check if we can make progress by sharpening ranges. 9840 if (FoundPred == ICmpInst::ICMP_NE && 9841 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9842 9843 const SCEVConstant *C = nullptr; 9844 const SCEV *V = nullptr; 9845 9846 if (isa<SCEVConstant>(FoundLHS)) { 9847 C = cast<SCEVConstant>(FoundLHS); 9848 V = FoundRHS; 9849 } else { 9850 C = cast<SCEVConstant>(FoundRHS); 9851 V = FoundLHS; 9852 } 9853 9854 // The guarding predicate tells us that C != V. If the known range 9855 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9856 // range we consider has to correspond to same signedness as the 9857 // predicate we're interested in folding. 9858 9859 APInt Min = ICmpInst::isSigned(Pred) ? 9860 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9861 9862 if (Min == C->getAPInt()) { 9863 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9864 // This is true even if (Min + 1) wraps around -- in case of 9865 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9866 9867 APInt SharperMin = Min + 1; 9868 9869 switch (Pred) { 9870 case ICmpInst::ICMP_SGE: 9871 case ICmpInst::ICMP_UGE: 9872 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9873 // RHS, we're done. 9874 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9875 getConstant(SharperMin))) 9876 return true; 9877 LLVM_FALLTHROUGH; 9878 9879 case ICmpInst::ICMP_SGT: 9880 case ICmpInst::ICMP_UGT: 9881 // We know from the range information that (V `Pred` Min || 9882 // V == Min). We know from the guarding condition that !(V 9883 // == Min). This gives us 9884 // 9885 // V `Pred` Min || V == Min && !(V == Min) 9886 // => V `Pred` Min 9887 // 9888 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9889 9890 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9891 return true; 9892 LLVM_FALLTHROUGH; 9893 9894 default: 9895 // No change 9896 break; 9897 } 9898 } 9899 } 9900 9901 // Check whether the actual condition is beyond sufficient. 9902 if (FoundPred == ICmpInst::ICMP_EQ) 9903 if (ICmpInst::isTrueWhenEqual(Pred)) 9904 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9905 return true; 9906 if (Pred == ICmpInst::ICMP_NE) 9907 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9908 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9909 return true; 9910 9911 // Otherwise assume the worst. 9912 return false; 9913 } 9914 9915 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9916 const SCEV *&L, const SCEV *&R, 9917 SCEV::NoWrapFlags &Flags) { 9918 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9919 if (!AE || AE->getNumOperands() != 2) 9920 return false; 9921 9922 L = AE->getOperand(0); 9923 R = AE->getOperand(1); 9924 Flags = AE->getNoWrapFlags(); 9925 return true; 9926 } 9927 9928 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9929 const SCEV *Less) { 9930 // We avoid subtracting expressions here because this function is usually 9931 // fairly deep in the call stack (i.e. is called many times). 9932 9933 // X - X = 0. 9934 if (More == Less) 9935 return APInt(getTypeSizeInBits(More->getType()), 0); 9936 9937 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9938 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9939 const auto *MAR = cast<SCEVAddRecExpr>(More); 9940 9941 if (LAR->getLoop() != MAR->getLoop()) 9942 return None; 9943 9944 // We look at affine expressions only; not for correctness but to keep 9945 // getStepRecurrence cheap. 9946 if (!LAR->isAffine() || !MAR->isAffine()) 9947 return None; 9948 9949 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9950 return None; 9951 9952 Less = LAR->getStart(); 9953 More = MAR->getStart(); 9954 9955 // fall through 9956 } 9957 9958 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9959 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9960 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9961 return M - L; 9962 } 9963 9964 SCEV::NoWrapFlags Flags; 9965 const SCEV *LLess = nullptr, *RLess = nullptr; 9966 const SCEV *LMore = nullptr, *RMore = nullptr; 9967 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9968 // Compare (X + C1) vs X. 9969 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9970 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9971 if (RLess == More) 9972 return -(C1->getAPInt()); 9973 9974 // Compare X vs (X + C2). 9975 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9976 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9977 if (RMore == Less) 9978 return C2->getAPInt(); 9979 9980 // Compare (X + C1) vs (X + C2). 9981 if (C1 && C2 && RLess == RMore) 9982 return C2->getAPInt() - C1->getAPInt(); 9983 9984 return None; 9985 } 9986 9987 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9988 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9989 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9990 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9991 return false; 9992 9993 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9994 if (!AddRecLHS) 9995 return false; 9996 9997 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9998 if (!AddRecFoundLHS) 9999 return false; 10000 10001 // We'd like to let SCEV reason about control dependencies, so we constrain 10002 // both the inequalities to be about add recurrences on the same loop. This 10003 // way we can use isLoopEntryGuardedByCond later. 10004 10005 const Loop *L = AddRecFoundLHS->getLoop(); 10006 if (L != AddRecLHS->getLoop()) 10007 return false; 10008 10009 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10010 // 10011 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10012 // ... (2) 10013 // 10014 // Informal proof for (2), assuming (1) [*]: 10015 // 10016 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10017 // 10018 // Then 10019 // 10020 // FoundLHS s< FoundRHS s< INT_MIN - C 10021 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10022 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10023 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10024 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10025 // <=> FoundLHS + C s< FoundRHS + C 10026 // 10027 // [*]: (1) can be proved by ruling out overflow. 10028 // 10029 // [**]: This can be proved by analyzing all the four possibilities: 10030 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10031 // (A s>= 0, B s>= 0). 10032 // 10033 // Note: 10034 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10035 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10036 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10037 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10038 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10039 // C)". 10040 10041 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10042 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10043 if (!LDiff || !RDiff || *LDiff != *RDiff) 10044 return false; 10045 10046 if (LDiff->isMinValue()) 10047 return true; 10048 10049 APInt FoundRHSLimit; 10050 10051 if (Pred == CmpInst::ICMP_ULT) { 10052 FoundRHSLimit = -(*RDiff); 10053 } else { 10054 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10055 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10056 } 10057 10058 // Try to prove (1) or (2), as needed. 10059 return isAvailableAtLoopEntry(FoundRHS, L) && 10060 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10061 getConstant(FoundRHSLimit)); 10062 } 10063 10064 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10065 const SCEV *LHS, const SCEV *RHS, 10066 const SCEV *FoundLHS, 10067 const SCEV *FoundRHS, unsigned Depth) { 10068 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10069 10070 auto ClearOnExit = make_scope_exit([&]() { 10071 if (LPhi) { 10072 bool Erased = PendingMerges.erase(LPhi); 10073 assert(Erased && "Failed to erase LPhi!"); 10074 (void)Erased; 10075 } 10076 if (RPhi) { 10077 bool Erased = PendingMerges.erase(RPhi); 10078 assert(Erased && "Failed to erase RPhi!"); 10079 (void)Erased; 10080 } 10081 }); 10082 10083 // Find respective Phis and check that they are not being pending. 10084 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10085 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10086 if (!PendingMerges.insert(Phi).second) 10087 return false; 10088 LPhi = Phi; 10089 } 10090 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10091 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10092 // If we detect a loop of Phi nodes being processed by this method, for 10093 // example: 10094 // 10095 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10096 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10097 // 10098 // we don't want to deal with a case that complex, so return conservative 10099 // answer false. 10100 if (!PendingMerges.insert(Phi).second) 10101 return false; 10102 RPhi = Phi; 10103 } 10104 10105 // If none of LHS, RHS is a Phi, nothing to do here. 10106 if (!LPhi && !RPhi) 10107 return false; 10108 10109 // If there is a SCEVUnknown Phi we are interested in, make it left. 10110 if (!LPhi) { 10111 std::swap(LHS, RHS); 10112 std::swap(FoundLHS, FoundRHS); 10113 std::swap(LPhi, RPhi); 10114 Pred = ICmpInst::getSwappedPredicate(Pred); 10115 } 10116 10117 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10118 const BasicBlock *LBB = LPhi->getParent(); 10119 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10120 10121 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10122 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10123 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10124 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10125 }; 10126 10127 if (RPhi && RPhi->getParent() == LBB) { 10128 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10129 // If we compare two Phis from the same block, and for each entry block 10130 // the predicate is true for incoming values from this block, then the 10131 // predicate is also true for the Phis. 10132 for (const BasicBlock *IncBB : predecessors(LBB)) { 10133 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10134 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10135 if (!ProvedEasily(L, R)) 10136 return false; 10137 } 10138 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10139 // Case two: RHS is also a Phi from the same basic block, and it is an 10140 // AddRec. It means that there is a loop which has both AddRec and Unknown 10141 // PHIs, for it we can compare incoming values of AddRec from above the loop 10142 // and latch with their respective incoming values of LPhi. 10143 // TODO: Generalize to handle loops with many inputs in a header. 10144 if (LPhi->getNumIncomingValues() != 2) return false; 10145 10146 auto *RLoop = RAR->getLoop(); 10147 auto *Predecessor = RLoop->getLoopPredecessor(); 10148 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10149 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10150 if (!ProvedEasily(L1, RAR->getStart())) 10151 return false; 10152 auto *Latch = RLoop->getLoopLatch(); 10153 assert(Latch && "Loop with AddRec with no latch?"); 10154 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10155 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10156 return false; 10157 } else { 10158 // In all other cases go over inputs of LHS and compare each of them to RHS, 10159 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10160 // At this point RHS is either a non-Phi, or it is a Phi from some block 10161 // different from LBB. 10162 for (const BasicBlock *IncBB : predecessors(LBB)) { 10163 // Check that RHS is available in this block. 10164 if (!dominates(RHS, IncBB)) 10165 return false; 10166 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10167 if (!ProvedEasily(L, RHS)) 10168 return false; 10169 } 10170 } 10171 return true; 10172 } 10173 10174 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10175 const SCEV *LHS, const SCEV *RHS, 10176 const SCEV *FoundLHS, 10177 const SCEV *FoundRHS) { 10178 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10179 return true; 10180 10181 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10182 return true; 10183 10184 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10185 FoundLHS, FoundRHS) || 10186 // ~x < ~y --> x > y 10187 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10188 getNotSCEV(FoundRHS), 10189 getNotSCEV(FoundLHS)); 10190 } 10191 10192 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10193 template <typename MinMaxExprType> 10194 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10195 const SCEV *Candidate) { 10196 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10197 if (!MinMaxExpr) 10198 return false; 10199 10200 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10201 } 10202 10203 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10204 ICmpInst::Predicate Pred, 10205 const SCEV *LHS, const SCEV *RHS) { 10206 // If both sides are affine addrecs for the same loop, with equal 10207 // steps, and we know the recurrences don't wrap, then we only 10208 // need to check the predicate on the starting values. 10209 10210 if (!ICmpInst::isRelational(Pred)) 10211 return false; 10212 10213 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10214 if (!LAR) 10215 return false; 10216 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10217 if (!RAR) 10218 return false; 10219 if (LAR->getLoop() != RAR->getLoop()) 10220 return false; 10221 if (!LAR->isAffine() || !RAR->isAffine()) 10222 return false; 10223 10224 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10225 return false; 10226 10227 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10228 SCEV::FlagNSW : SCEV::FlagNUW; 10229 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10230 return false; 10231 10232 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10233 } 10234 10235 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10236 /// expression? 10237 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10238 ICmpInst::Predicate Pred, 10239 const SCEV *LHS, const SCEV *RHS) { 10240 switch (Pred) { 10241 default: 10242 return false; 10243 10244 case ICmpInst::ICMP_SGE: 10245 std::swap(LHS, RHS); 10246 LLVM_FALLTHROUGH; 10247 case ICmpInst::ICMP_SLE: 10248 return 10249 // min(A, ...) <= A 10250 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10251 // A <= max(A, ...) 10252 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10253 10254 case ICmpInst::ICMP_UGE: 10255 std::swap(LHS, RHS); 10256 LLVM_FALLTHROUGH; 10257 case ICmpInst::ICMP_ULE: 10258 return 10259 // min(A, ...) <= A 10260 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10261 // A <= max(A, ...) 10262 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10263 } 10264 10265 llvm_unreachable("covered switch fell through?!"); 10266 } 10267 10268 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10269 const SCEV *LHS, const SCEV *RHS, 10270 const SCEV *FoundLHS, 10271 const SCEV *FoundRHS, 10272 unsigned Depth) { 10273 assert(getTypeSizeInBits(LHS->getType()) == 10274 getTypeSizeInBits(RHS->getType()) && 10275 "LHS and RHS have different sizes?"); 10276 assert(getTypeSizeInBits(FoundLHS->getType()) == 10277 getTypeSizeInBits(FoundRHS->getType()) && 10278 "FoundLHS and FoundRHS have different sizes?"); 10279 // We want to avoid hurting the compile time with analysis of too big trees. 10280 if (Depth > MaxSCEVOperationsImplicationDepth) 10281 return false; 10282 // We only want to work with ICMP_SGT comparison so far. 10283 // TODO: Extend to ICMP_UGT? 10284 if (Pred == ICmpInst::ICMP_SLT) { 10285 Pred = ICmpInst::ICMP_SGT; 10286 std::swap(LHS, RHS); 10287 std::swap(FoundLHS, FoundRHS); 10288 } 10289 if (Pred != ICmpInst::ICMP_SGT) 10290 return false; 10291 10292 auto GetOpFromSExt = [&](const SCEV *S) { 10293 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10294 return Ext->getOperand(); 10295 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10296 // the constant in some cases. 10297 return S; 10298 }; 10299 10300 // Acquire values from extensions. 10301 auto *OrigLHS = LHS; 10302 auto *OrigFoundLHS = FoundLHS; 10303 LHS = GetOpFromSExt(LHS); 10304 FoundLHS = GetOpFromSExt(FoundLHS); 10305 10306 // Is the SGT predicate can be proved trivially or using the found context. 10307 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10308 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10309 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10310 FoundRHS, Depth + 1); 10311 }; 10312 10313 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10314 // We want to avoid creation of any new non-constant SCEV. Since we are 10315 // going to compare the operands to RHS, we should be certain that we don't 10316 // need any size extensions for this. So let's decline all cases when the 10317 // sizes of types of LHS and RHS do not match. 10318 // TODO: Maybe try to get RHS from sext to catch more cases? 10319 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10320 return false; 10321 10322 // Should not overflow. 10323 if (!LHSAddExpr->hasNoSignedWrap()) 10324 return false; 10325 10326 auto *LL = LHSAddExpr->getOperand(0); 10327 auto *LR = LHSAddExpr->getOperand(1); 10328 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10329 10330 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10331 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10332 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10333 }; 10334 // Try to prove the following rule: 10335 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10336 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10337 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10338 return true; 10339 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10340 Value *LL, *LR; 10341 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10342 10343 using namespace llvm::PatternMatch; 10344 10345 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10346 // Rules for division. 10347 // We are going to perform some comparisons with Denominator and its 10348 // derivative expressions. In general case, creating a SCEV for it may 10349 // lead to a complex analysis of the entire graph, and in particular it 10350 // can request trip count recalculation for the same loop. This would 10351 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10352 // this, we only want to create SCEVs that are constants in this section. 10353 // So we bail if Denominator is not a constant. 10354 if (!isa<ConstantInt>(LR)) 10355 return false; 10356 10357 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10358 10359 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10360 // then a SCEV for the numerator already exists and matches with FoundLHS. 10361 auto *Numerator = getExistingSCEV(LL); 10362 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10363 return false; 10364 10365 // Make sure that the numerator matches with FoundLHS and the denominator 10366 // is positive. 10367 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10368 return false; 10369 10370 auto *DTy = Denominator->getType(); 10371 auto *FRHSTy = FoundRHS->getType(); 10372 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10373 // One of types is a pointer and another one is not. We cannot extend 10374 // them properly to a wider type, so let us just reject this case. 10375 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10376 // to avoid this check. 10377 return false; 10378 10379 // Given that: 10380 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10381 auto *WTy = getWiderType(DTy, FRHSTy); 10382 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10383 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10384 10385 // Try to prove the following rule: 10386 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10387 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10388 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10389 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10390 if (isKnownNonPositive(RHS) && 10391 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10392 return true; 10393 10394 // Try to prove the following rule: 10395 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10396 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10397 // If we divide it by Denominator > 2, then: 10398 // 1. If FoundLHS is negative, then the result is 0. 10399 // 2. If FoundLHS is non-negative, then the result is non-negative. 10400 // Anyways, the result is non-negative. 10401 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10402 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10403 if (isKnownNegative(RHS) && 10404 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10405 return true; 10406 } 10407 } 10408 10409 // If our expression contained SCEVUnknown Phis, and we split it down and now 10410 // need to prove something for them, try to prove the predicate for every 10411 // possible incoming values of those Phis. 10412 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10413 return true; 10414 10415 return false; 10416 } 10417 10418 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10419 const SCEV *LHS, const SCEV *RHS) { 10420 // zext x u<= sext x, sext x s<= zext x 10421 switch (Pred) { 10422 case ICmpInst::ICMP_SGE: 10423 std::swap(LHS, RHS); 10424 LLVM_FALLTHROUGH; 10425 case ICmpInst::ICMP_SLE: { 10426 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10427 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10428 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10429 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10430 return true; 10431 break; 10432 } 10433 case ICmpInst::ICMP_UGE: 10434 std::swap(LHS, RHS); 10435 LLVM_FALLTHROUGH; 10436 case ICmpInst::ICMP_ULE: { 10437 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10438 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10439 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10440 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10441 return true; 10442 break; 10443 } 10444 default: 10445 break; 10446 }; 10447 return false; 10448 } 10449 10450 bool 10451 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10452 const SCEV *LHS, const SCEV *RHS) { 10453 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10454 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10455 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10456 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10457 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10458 } 10459 10460 bool 10461 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10462 const SCEV *LHS, const SCEV *RHS, 10463 const SCEV *FoundLHS, 10464 const SCEV *FoundRHS) { 10465 switch (Pred) { 10466 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10467 case ICmpInst::ICMP_EQ: 10468 case ICmpInst::ICMP_NE: 10469 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10470 return true; 10471 break; 10472 case ICmpInst::ICMP_SLT: 10473 case ICmpInst::ICMP_SLE: 10474 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10475 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10476 return true; 10477 break; 10478 case ICmpInst::ICMP_SGT: 10479 case ICmpInst::ICMP_SGE: 10480 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10481 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10482 return true; 10483 break; 10484 case ICmpInst::ICMP_ULT: 10485 case ICmpInst::ICMP_ULE: 10486 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10487 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10488 return true; 10489 break; 10490 case ICmpInst::ICMP_UGT: 10491 case ICmpInst::ICMP_UGE: 10492 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10493 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10494 return true; 10495 break; 10496 } 10497 10498 // Maybe it can be proved via operations? 10499 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10500 return true; 10501 10502 return false; 10503 } 10504 10505 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10506 const SCEV *LHS, 10507 const SCEV *RHS, 10508 const SCEV *FoundLHS, 10509 const SCEV *FoundRHS) { 10510 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10511 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10512 // reduce the compile time impact of this optimization. 10513 return false; 10514 10515 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10516 if (!Addend) 10517 return false; 10518 10519 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10520 10521 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10522 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10523 ConstantRange FoundLHSRange = 10524 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10525 10526 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10527 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10528 10529 // We can also compute the range of values for `LHS` that satisfy the 10530 // consequent, "`LHS` `Pred` `RHS`": 10531 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10532 ConstantRange SatisfyingLHSRange = 10533 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10534 10535 // The antecedent implies the consequent if every value of `LHS` that 10536 // satisfies the antecedent also satisfies the consequent. 10537 return SatisfyingLHSRange.contains(LHSRange); 10538 } 10539 10540 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10541 bool IsSigned, bool NoWrap) { 10542 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10543 10544 if (NoWrap) return false; 10545 10546 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10547 const SCEV *One = getOne(Stride->getType()); 10548 10549 if (IsSigned) { 10550 APInt MaxRHS = getSignedRangeMax(RHS); 10551 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10552 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10553 10554 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10555 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10556 } 10557 10558 APInt MaxRHS = getUnsignedRangeMax(RHS); 10559 APInt MaxValue = APInt::getMaxValue(BitWidth); 10560 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10561 10562 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10563 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10564 } 10565 10566 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10567 bool IsSigned, bool NoWrap) { 10568 if (NoWrap) return false; 10569 10570 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10571 const SCEV *One = getOne(Stride->getType()); 10572 10573 if (IsSigned) { 10574 APInt MinRHS = getSignedRangeMin(RHS); 10575 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10576 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10577 10578 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10579 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10580 } 10581 10582 APInt MinRHS = getUnsignedRangeMin(RHS); 10583 APInt MinValue = APInt::getMinValue(BitWidth); 10584 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10585 10586 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10587 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10588 } 10589 10590 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10591 bool Equality) { 10592 const SCEV *One = getOne(Step->getType()); 10593 Delta = Equality ? getAddExpr(Delta, Step) 10594 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10595 return getUDivExpr(Delta, Step); 10596 } 10597 10598 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10599 const SCEV *Stride, 10600 const SCEV *End, 10601 unsigned BitWidth, 10602 bool IsSigned) { 10603 10604 assert(!isKnownNonPositive(Stride) && 10605 "Stride is expected strictly positive!"); 10606 // Calculate the maximum backedge count based on the range of values 10607 // permitted by Start, End, and Stride. 10608 const SCEV *MaxBECount; 10609 APInt MinStart = 10610 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10611 10612 APInt StrideForMaxBECount = 10613 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10614 10615 // We already know that the stride is positive, so we paper over conservatism 10616 // in our range computation by forcing StrideForMaxBECount to be at least one. 10617 // In theory this is unnecessary, but we expect MaxBECount to be a 10618 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10619 // is nothing to constant fold it to). 10620 APInt One(BitWidth, 1, IsSigned); 10621 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10622 10623 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10624 : APInt::getMaxValue(BitWidth); 10625 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10626 10627 // Although End can be a MAX expression we estimate MaxEnd considering only 10628 // the case End = RHS of the loop termination condition. This is safe because 10629 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10630 // taken count. 10631 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10632 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10633 10634 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10635 getConstant(StrideForMaxBECount) /* Step */, 10636 false /* Equality */); 10637 10638 return MaxBECount; 10639 } 10640 10641 ScalarEvolution::ExitLimit 10642 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10643 const Loop *L, bool IsSigned, 10644 bool ControlsExit, bool AllowPredicates) { 10645 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10646 10647 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10648 bool PredicatedIV = false; 10649 10650 if (!IV && AllowPredicates) { 10651 // Try to make this an AddRec using runtime tests, in the first X 10652 // iterations of this loop, where X is the SCEV expression found by the 10653 // algorithm below. 10654 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10655 PredicatedIV = true; 10656 } 10657 10658 // Avoid weird loops 10659 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10660 return getCouldNotCompute(); 10661 10662 bool NoWrap = ControlsExit && 10663 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10664 10665 const SCEV *Stride = IV->getStepRecurrence(*this); 10666 10667 bool PositiveStride = isKnownPositive(Stride); 10668 10669 // Avoid negative or zero stride values. 10670 if (!PositiveStride) { 10671 // We can compute the correct backedge taken count for loops with unknown 10672 // strides if we can prove that the loop is not an infinite loop with side 10673 // effects. Here's the loop structure we are trying to handle - 10674 // 10675 // i = start 10676 // do { 10677 // A[i] = i; 10678 // i += s; 10679 // } while (i < end); 10680 // 10681 // The backedge taken count for such loops is evaluated as - 10682 // (max(end, start + stride) - start - 1) /u stride 10683 // 10684 // The additional preconditions that we need to check to prove correctness 10685 // of the above formula is as follows - 10686 // 10687 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10688 // NoWrap flag). 10689 // b) loop is single exit with no side effects. 10690 // 10691 // 10692 // Precondition a) implies that if the stride is negative, this is a single 10693 // trip loop. The backedge taken count formula reduces to zero in this case. 10694 // 10695 // Precondition b) implies that the unknown stride cannot be zero otherwise 10696 // we have UB. 10697 // 10698 // The positive stride case is the same as isKnownPositive(Stride) returning 10699 // true (original behavior of the function). 10700 // 10701 // We want to make sure that the stride is truly unknown as there are edge 10702 // cases where ScalarEvolution propagates no wrap flags to the 10703 // post-increment/decrement IV even though the increment/decrement operation 10704 // itself is wrapping. The computed backedge taken count may be wrong in 10705 // such cases. This is prevented by checking that the stride is not known to 10706 // be either positive or non-positive. For example, no wrap flags are 10707 // propagated to the post-increment IV of this loop with a trip count of 2 - 10708 // 10709 // unsigned char i; 10710 // for(i=127; i<128; i+=129) 10711 // A[i] = i; 10712 // 10713 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10714 !loopHasNoSideEffects(L)) 10715 return getCouldNotCompute(); 10716 } else if (!Stride->isOne() && 10717 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10718 // Avoid proven overflow cases: this will ensure that the backedge taken 10719 // count will not generate any unsigned overflow. Relaxed no-overflow 10720 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10721 // undefined behaviors like the case of C language. 10722 return getCouldNotCompute(); 10723 10724 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10725 : ICmpInst::ICMP_ULT; 10726 const SCEV *Start = IV->getStart(); 10727 const SCEV *End = RHS; 10728 // When the RHS is not invariant, we do not know the end bound of the loop and 10729 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10730 // calculate the MaxBECount, given the start, stride and max value for the end 10731 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10732 // checked above). 10733 if (!isLoopInvariant(RHS, L)) { 10734 const SCEV *MaxBECount = computeMaxBECountForLT( 10735 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10736 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10737 false /*MaxOrZero*/, Predicates); 10738 } 10739 // If the backedge is taken at least once, then it will be taken 10740 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10741 // is the LHS value of the less-than comparison the first time it is evaluated 10742 // and End is the RHS. 10743 const SCEV *BECountIfBackedgeTaken = 10744 computeBECount(getMinusSCEV(End, Start), Stride, false); 10745 // If the loop entry is guarded by the result of the backedge test of the 10746 // first loop iteration, then we know the backedge will be taken at least 10747 // once and so the backedge taken count is as above. If not then we use the 10748 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10749 // as if the backedge is taken at least once max(End,Start) is End and so the 10750 // result is as above, and if not max(End,Start) is Start so we get a backedge 10751 // count of zero. 10752 const SCEV *BECount; 10753 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10754 BECount = BECountIfBackedgeTaken; 10755 else { 10756 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10757 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10758 } 10759 10760 const SCEV *MaxBECount; 10761 bool MaxOrZero = false; 10762 if (isa<SCEVConstant>(BECount)) 10763 MaxBECount = BECount; 10764 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10765 // If we know exactly how many times the backedge will be taken if it's 10766 // taken at least once, then the backedge count will either be that or 10767 // zero. 10768 MaxBECount = BECountIfBackedgeTaken; 10769 MaxOrZero = true; 10770 } else { 10771 MaxBECount = computeMaxBECountForLT( 10772 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10773 } 10774 10775 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10776 !isa<SCEVCouldNotCompute>(BECount)) 10777 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10778 10779 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10780 } 10781 10782 ScalarEvolution::ExitLimit 10783 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10784 const Loop *L, bool IsSigned, 10785 bool ControlsExit, bool AllowPredicates) { 10786 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10787 // We handle only IV > Invariant 10788 if (!isLoopInvariant(RHS, L)) 10789 return getCouldNotCompute(); 10790 10791 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10792 if (!IV && AllowPredicates) 10793 // Try to make this an AddRec using runtime tests, in the first X 10794 // iterations of this loop, where X is the SCEV expression found by the 10795 // algorithm below. 10796 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10797 10798 // Avoid weird loops 10799 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10800 return getCouldNotCompute(); 10801 10802 bool NoWrap = ControlsExit && 10803 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10804 10805 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10806 10807 // Avoid negative or zero stride values 10808 if (!isKnownPositive(Stride)) 10809 return getCouldNotCompute(); 10810 10811 // Avoid proven overflow cases: this will ensure that the backedge taken count 10812 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10813 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10814 // behaviors like the case of C language. 10815 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10816 return getCouldNotCompute(); 10817 10818 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10819 : ICmpInst::ICMP_UGT; 10820 10821 const SCEV *Start = IV->getStart(); 10822 const SCEV *End = RHS; 10823 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10824 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10825 10826 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10827 10828 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10829 : getUnsignedRangeMax(Start); 10830 10831 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10832 : getUnsignedRangeMin(Stride); 10833 10834 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10835 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10836 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10837 10838 // Although End can be a MIN expression we estimate MinEnd considering only 10839 // the case End = RHS. This is safe because in the other case (Start - End) 10840 // is zero, leading to a zero maximum backedge taken count. 10841 APInt MinEnd = 10842 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10843 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10844 10845 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10846 ? BECount 10847 : computeBECount(getConstant(MaxStart - MinEnd), 10848 getConstant(MinStride), false); 10849 10850 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10851 MaxBECount = BECount; 10852 10853 return ExitLimit(BECount, MaxBECount, false, Predicates); 10854 } 10855 10856 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10857 ScalarEvolution &SE) const { 10858 if (Range.isFullSet()) // Infinite loop. 10859 return SE.getCouldNotCompute(); 10860 10861 // If the start is a non-zero constant, shift the range to simplify things. 10862 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10863 if (!SC->getValue()->isZero()) { 10864 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10865 Operands[0] = SE.getZero(SC->getType()); 10866 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10867 getNoWrapFlags(FlagNW)); 10868 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10869 return ShiftedAddRec->getNumIterationsInRange( 10870 Range.subtract(SC->getAPInt()), SE); 10871 // This is strange and shouldn't happen. 10872 return SE.getCouldNotCompute(); 10873 } 10874 10875 // The only time we can solve this is when we have all constant indices. 10876 // Otherwise, we cannot determine the overflow conditions. 10877 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10878 return SE.getCouldNotCompute(); 10879 10880 // Okay at this point we know that all elements of the chrec are constants and 10881 // that the start element is zero. 10882 10883 // First check to see if the range contains zero. If not, the first 10884 // iteration exits. 10885 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10886 if (!Range.contains(APInt(BitWidth, 0))) 10887 return SE.getZero(getType()); 10888 10889 if (isAffine()) { 10890 // If this is an affine expression then we have this situation: 10891 // Solve {0,+,A} in Range === Ax in Range 10892 10893 // We know that zero is in the range. If A is positive then we know that 10894 // the upper value of the range must be the first possible exit value. 10895 // If A is negative then the lower of the range is the last possible loop 10896 // value. Also note that we already checked for a full range. 10897 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10898 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10899 10900 // The exit value should be (End+A)/A. 10901 APInt ExitVal = (End + A).udiv(A); 10902 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10903 10904 // Evaluate at the exit value. If we really did fall out of the valid 10905 // range, then we computed our trip count, otherwise wrap around or other 10906 // things must have happened. 10907 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10908 if (Range.contains(Val->getValue())) 10909 return SE.getCouldNotCompute(); // Something strange happened 10910 10911 // Ensure that the previous value is in the range. This is a sanity check. 10912 assert(Range.contains( 10913 EvaluateConstantChrecAtConstant(this, 10914 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10915 "Linear scev computation is off in a bad way!"); 10916 return SE.getConstant(ExitValue); 10917 } 10918 10919 if (isQuadratic()) { 10920 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10921 return SE.getConstant(S.getValue()); 10922 } 10923 10924 return SE.getCouldNotCompute(); 10925 } 10926 10927 const SCEVAddRecExpr * 10928 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10929 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10930 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10931 // but in this case we cannot guarantee that the value returned will be an 10932 // AddRec because SCEV does not have a fixed point where it stops 10933 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10934 // may happen if we reach arithmetic depth limit while simplifying. So we 10935 // construct the returned value explicitly. 10936 SmallVector<const SCEV *, 3> Ops; 10937 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10938 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10939 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10940 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10941 // We know that the last operand is not a constant zero (otherwise it would 10942 // have been popped out earlier). This guarantees us that if the result has 10943 // the same last operand, then it will also not be popped out, meaning that 10944 // the returned value will be an AddRec. 10945 const SCEV *Last = getOperand(getNumOperands() - 1); 10946 assert(!Last->isZero() && "Recurrency with zero step?"); 10947 Ops.push_back(Last); 10948 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10949 SCEV::FlagAnyWrap)); 10950 } 10951 10952 // Return true when S contains at least an undef value. 10953 static inline bool containsUndefs(const SCEV *S) { 10954 return SCEVExprContains(S, [](const SCEV *S) { 10955 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10956 return isa<UndefValue>(SU->getValue()); 10957 return false; 10958 }); 10959 } 10960 10961 namespace { 10962 10963 // Collect all steps of SCEV expressions. 10964 struct SCEVCollectStrides { 10965 ScalarEvolution &SE; 10966 SmallVectorImpl<const SCEV *> &Strides; 10967 10968 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10969 : SE(SE), Strides(S) {} 10970 10971 bool follow(const SCEV *S) { 10972 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10973 Strides.push_back(AR->getStepRecurrence(SE)); 10974 return true; 10975 } 10976 10977 bool isDone() const { return false; } 10978 }; 10979 10980 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10981 struct SCEVCollectTerms { 10982 SmallVectorImpl<const SCEV *> &Terms; 10983 10984 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10985 10986 bool follow(const SCEV *S) { 10987 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10988 isa<SCEVSignExtendExpr>(S)) { 10989 if (!containsUndefs(S)) 10990 Terms.push_back(S); 10991 10992 // Stop recursion: once we collected a term, do not walk its operands. 10993 return false; 10994 } 10995 10996 // Keep looking. 10997 return true; 10998 } 10999 11000 bool isDone() const { return false; } 11001 }; 11002 11003 // Check if a SCEV contains an AddRecExpr. 11004 struct SCEVHasAddRec { 11005 bool &ContainsAddRec; 11006 11007 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11008 ContainsAddRec = false; 11009 } 11010 11011 bool follow(const SCEV *S) { 11012 if (isa<SCEVAddRecExpr>(S)) { 11013 ContainsAddRec = true; 11014 11015 // Stop recursion: once we collected a term, do not walk its operands. 11016 return false; 11017 } 11018 11019 // Keep looking. 11020 return true; 11021 } 11022 11023 bool isDone() const { return false; } 11024 }; 11025 11026 // Find factors that are multiplied with an expression that (possibly as a 11027 // subexpression) contains an AddRecExpr. In the expression: 11028 // 11029 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11030 // 11031 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11032 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11033 // parameters as they form a product with an induction variable. 11034 // 11035 // This collector expects all array size parameters to be in the same MulExpr. 11036 // It might be necessary to later add support for collecting parameters that are 11037 // spread over different nested MulExpr. 11038 struct SCEVCollectAddRecMultiplies { 11039 SmallVectorImpl<const SCEV *> &Terms; 11040 ScalarEvolution &SE; 11041 11042 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11043 : Terms(T), SE(SE) {} 11044 11045 bool follow(const SCEV *S) { 11046 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11047 bool HasAddRec = false; 11048 SmallVector<const SCEV *, 0> Operands; 11049 for (auto Op : Mul->operands()) { 11050 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11051 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11052 Operands.push_back(Op); 11053 } else if (Unknown) { 11054 HasAddRec = true; 11055 } else { 11056 bool ContainsAddRec = false; 11057 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11058 visitAll(Op, ContiansAddRec); 11059 HasAddRec |= ContainsAddRec; 11060 } 11061 } 11062 if (Operands.size() == 0) 11063 return true; 11064 11065 if (!HasAddRec) 11066 return false; 11067 11068 Terms.push_back(SE.getMulExpr(Operands)); 11069 // Stop recursion: once we collected a term, do not walk its operands. 11070 return false; 11071 } 11072 11073 // Keep looking. 11074 return true; 11075 } 11076 11077 bool isDone() const { return false; } 11078 }; 11079 11080 } // end anonymous namespace 11081 11082 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11083 /// two places: 11084 /// 1) The strides of AddRec expressions. 11085 /// 2) Unknowns that are multiplied with AddRec expressions. 11086 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11087 SmallVectorImpl<const SCEV *> &Terms) { 11088 SmallVector<const SCEV *, 4> Strides; 11089 SCEVCollectStrides StrideCollector(*this, Strides); 11090 visitAll(Expr, StrideCollector); 11091 11092 LLVM_DEBUG({ 11093 dbgs() << "Strides:\n"; 11094 for (const SCEV *S : Strides) 11095 dbgs() << *S << "\n"; 11096 }); 11097 11098 for (const SCEV *S : Strides) { 11099 SCEVCollectTerms TermCollector(Terms); 11100 visitAll(S, TermCollector); 11101 } 11102 11103 LLVM_DEBUG({ 11104 dbgs() << "Terms:\n"; 11105 for (const SCEV *T : Terms) 11106 dbgs() << *T << "\n"; 11107 }); 11108 11109 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11110 visitAll(Expr, MulCollector); 11111 } 11112 11113 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11114 SmallVectorImpl<const SCEV *> &Terms, 11115 SmallVectorImpl<const SCEV *> &Sizes) { 11116 int Last = Terms.size() - 1; 11117 const SCEV *Step = Terms[Last]; 11118 11119 // End of recursion. 11120 if (Last == 0) { 11121 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11122 SmallVector<const SCEV *, 2> Qs; 11123 for (const SCEV *Op : M->operands()) 11124 if (!isa<SCEVConstant>(Op)) 11125 Qs.push_back(Op); 11126 11127 Step = SE.getMulExpr(Qs); 11128 } 11129 11130 Sizes.push_back(Step); 11131 return true; 11132 } 11133 11134 for (const SCEV *&Term : Terms) { 11135 // Normalize the terms before the next call to findArrayDimensionsRec. 11136 const SCEV *Q, *R; 11137 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11138 11139 // Bail out when GCD does not evenly divide one of the terms. 11140 if (!R->isZero()) 11141 return false; 11142 11143 Term = Q; 11144 } 11145 11146 // Remove all SCEVConstants. 11147 Terms.erase( 11148 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11149 Terms.end()); 11150 11151 if (Terms.size() > 0) 11152 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11153 return false; 11154 11155 Sizes.push_back(Step); 11156 return true; 11157 } 11158 11159 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11160 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11161 for (const SCEV *T : Terms) 11162 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11163 return true; 11164 return false; 11165 } 11166 11167 // Return the number of product terms in S. 11168 static inline int numberOfTerms(const SCEV *S) { 11169 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11170 return Expr->getNumOperands(); 11171 return 1; 11172 } 11173 11174 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11175 if (isa<SCEVConstant>(T)) 11176 return nullptr; 11177 11178 if (isa<SCEVUnknown>(T)) 11179 return T; 11180 11181 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11182 SmallVector<const SCEV *, 2> Factors; 11183 for (const SCEV *Op : M->operands()) 11184 if (!isa<SCEVConstant>(Op)) 11185 Factors.push_back(Op); 11186 11187 return SE.getMulExpr(Factors); 11188 } 11189 11190 return T; 11191 } 11192 11193 /// Return the size of an element read or written by Inst. 11194 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11195 Type *Ty; 11196 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11197 Ty = Store->getValueOperand()->getType(); 11198 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11199 Ty = Load->getType(); 11200 else 11201 return nullptr; 11202 11203 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11204 return getSizeOfExpr(ETy, Ty); 11205 } 11206 11207 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11208 SmallVectorImpl<const SCEV *> &Sizes, 11209 const SCEV *ElementSize) { 11210 if (Terms.size() < 1 || !ElementSize) 11211 return; 11212 11213 // Early return when Terms do not contain parameters: we do not delinearize 11214 // non parametric SCEVs. 11215 if (!containsParameters(Terms)) 11216 return; 11217 11218 LLVM_DEBUG({ 11219 dbgs() << "Terms:\n"; 11220 for (const SCEV *T : Terms) 11221 dbgs() << *T << "\n"; 11222 }); 11223 11224 // Remove duplicates. 11225 array_pod_sort(Terms.begin(), Terms.end()); 11226 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11227 11228 // Put larger terms first. 11229 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11230 return numberOfTerms(LHS) > numberOfTerms(RHS); 11231 }); 11232 11233 // Try to divide all terms by the element size. If term is not divisible by 11234 // element size, proceed with the original term. 11235 for (const SCEV *&Term : Terms) { 11236 const SCEV *Q, *R; 11237 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11238 if (!Q->isZero()) 11239 Term = Q; 11240 } 11241 11242 SmallVector<const SCEV *, 4> NewTerms; 11243 11244 // Remove constant factors. 11245 for (const SCEV *T : Terms) 11246 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11247 NewTerms.push_back(NewT); 11248 11249 LLVM_DEBUG({ 11250 dbgs() << "Terms after sorting:\n"; 11251 for (const SCEV *T : NewTerms) 11252 dbgs() << *T << "\n"; 11253 }); 11254 11255 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11256 Sizes.clear(); 11257 return; 11258 } 11259 11260 // The last element to be pushed into Sizes is the size of an element. 11261 Sizes.push_back(ElementSize); 11262 11263 LLVM_DEBUG({ 11264 dbgs() << "Sizes:\n"; 11265 for (const SCEV *S : Sizes) 11266 dbgs() << *S << "\n"; 11267 }); 11268 } 11269 11270 void ScalarEvolution::computeAccessFunctions( 11271 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11272 SmallVectorImpl<const SCEV *> &Sizes) { 11273 // Early exit in case this SCEV is not an affine multivariate function. 11274 if (Sizes.empty()) 11275 return; 11276 11277 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11278 if (!AR->isAffine()) 11279 return; 11280 11281 const SCEV *Res = Expr; 11282 int Last = Sizes.size() - 1; 11283 for (int i = Last; i >= 0; i--) { 11284 const SCEV *Q, *R; 11285 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11286 11287 LLVM_DEBUG({ 11288 dbgs() << "Res: " << *Res << "\n"; 11289 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11290 dbgs() << "Res divided by Sizes[i]:\n"; 11291 dbgs() << "Quotient: " << *Q << "\n"; 11292 dbgs() << "Remainder: " << *R << "\n"; 11293 }); 11294 11295 Res = Q; 11296 11297 // Do not record the last subscript corresponding to the size of elements in 11298 // the array. 11299 if (i == Last) { 11300 11301 // Bail out if the remainder is too complex. 11302 if (isa<SCEVAddRecExpr>(R)) { 11303 Subscripts.clear(); 11304 Sizes.clear(); 11305 return; 11306 } 11307 11308 continue; 11309 } 11310 11311 // Record the access function for the current subscript. 11312 Subscripts.push_back(R); 11313 } 11314 11315 // Also push in last position the remainder of the last division: it will be 11316 // the access function of the innermost dimension. 11317 Subscripts.push_back(Res); 11318 11319 std::reverse(Subscripts.begin(), Subscripts.end()); 11320 11321 LLVM_DEBUG({ 11322 dbgs() << "Subscripts:\n"; 11323 for (const SCEV *S : Subscripts) 11324 dbgs() << *S << "\n"; 11325 }); 11326 } 11327 11328 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11329 /// sizes of an array access. Returns the remainder of the delinearization that 11330 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11331 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11332 /// expressions in the stride and base of a SCEV corresponding to the 11333 /// computation of a GCD (greatest common divisor) of base and stride. When 11334 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11335 /// 11336 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11337 /// 11338 /// void foo(long n, long m, long o, double A[n][m][o]) { 11339 /// 11340 /// for (long i = 0; i < n; i++) 11341 /// for (long j = 0; j < m; j++) 11342 /// for (long k = 0; k < o; k++) 11343 /// A[i][j][k] = 1.0; 11344 /// } 11345 /// 11346 /// the delinearization input is the following AddRec SCEV: 11347 /// 11348 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11349 /// 11350 /// From this SCEV, we are able to say that the base offset of the access is %A 11351 /// because it appears as an offset that does not divide any of the strides in 11352 /// the loops: 11353 /// 11354 /// CHECK: Base offset: %A 11355 /// 11356 /// and then SCEV->delinearize determines the size of some of the dimensions of 11357 /// the array as these are the multiples by which the strides are happening: 11358 /// 11359 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11360 /// 11361 /// Note that the outermost dimension remains of UnknownSize because there are 11362 /// no strides that would help identifying the size of the last dimension: when 11363 /// the array has been statically allocated, one could compute the size of that 11364 /// dimension by dividing the overall size of the array by the size of the known 11365 /// dimensions: %m * %o * 8. 11366 /// 11367 /// Finally delinearize provides the access functions for the array reference 11368 /// that does correspond to A[i][j][k] of the above C testcase: 11369 /// 11370 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11371 /// 11372 /// The testcases are checking the output of a function pass: 11373 /// DelinearizationPass that walks through all loads and stores of a function 11374 /// asking for the SCEV of the memory access with respect to all enclosing 11375 /// loops, calling SCEV->delinearize on that and printing the results. 11376 void ScalarEvolution::delinearize(const SCEV *Expr, 11377 SmallVectorImpl<const SCEV *> &Subscripts, 11378 SmallVectorImpl<const SCEV *> &Sizes, 11379 const SCEV *ElementSize) { 11380 // First step: collect parametric terms. 11381 SmallVector<const SCEV *, 4> Terms; 11382 collectParametricTerms(Expr, Terms); 11383 11384 if (Terms.empty()) 11385 return; 11386 11387 // Second step: find subscript sizes. 11388 findArrayDimensions(Terms, Sizes, ElementSize); 11389 11390 if (Sizes.empty()) 11391 return; 11392 11393 // Third step: compute the access functions for each subscript. 11394 computeAccessFunctions(Expr, Subscripts, Sizes); 11395 11396 if (Subscripts.empty()) 11397 return; 11398 11399 LLVM_DEBUG({ 11400 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11401 dbgs() << "ArrayDecl[UnknownSize]"; 11402 for (const SCEV *S : Sizes) 11403 dbgs() << "[" << *S << "]"; 11404 11405 dbgs() << "\nArrayRef"; 11406 for (const SCEV *S : Subscripts) 11407 dbgs() << "[" << *S << "]"; 11408 dbgs() << "\n"; 11409 }); 11410 } 11411 11412 //===----------------------------------------------------------------------===// 11413 // SCEVCallbackVH Class Implementation 11414 //===----------------------------------------------------------------------===// 11415 11416 void ScalarEvolution::SCEVCallbackVH::deleted() { 11417 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11418 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11419 SE->ConstantEvolutionLoopExitValue.erase(PN); 11420 SE->eraseValueFromMap(getValPtr()); 11421 // this now dangles! 11422 } 11423 11424 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11425 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11426 11427 // Forget all the expressions associated with users of the old value, 11428 // so that future queries will recompute the expressions using the new 11429 // value. 11430 Value *Old = getValPtr(); 11431 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11432 SmallPtrSet<User *, 8> Visited; 11433 while (!Worklist.empty()) { 11434 User *U = Worklist.pop_back_val(); 11435 // Deleting the Old value will cause this to dangle. Postpone 11436 // that until everything else is done. 11437 if (U == Old) 11438 continue; 11439 if (!Visited.insert(U).second) 11440 continue; 11441 if (PHINode *PN = dyn_cast<PHINode>(U)) 11442 SE->ConstantEvolutionLoopExitValue.erase(PN); 11443 SE->eraseValueFromMap(U); 11444 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11445 } 11446 // Delete the Old value. 11447 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11448 SE->ConstantEvolutionLoopExitValue.erase(PN); 11449 SE->eraseValueFromMap(Old); 11450 // this now dangles! 11451 } 11452 11453 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11454 : CallbackVH(V), SE(se) {} 11455 11456 //===----------------------------------------------------------------------===// 11457 // ScalarEvolution Class Implementation 11458 //===----------------------------------------------------------------------===// 11459 11460 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11461 AssumptionCache &AC, DominatorTree &DT, 11462 LoopInfo &LI) 11463 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11464 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11465 LoopDispositions(64), BlockDispositions(64) { 11466 // To use guards for proving predicates, we need to scan every instruction in 11467 // relevant basic blocks, and not just terminators. Doing this is a waste of 11468 // time if the IR does not actually contain any calls to 11469 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11470 // 11471 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11472 // to _add_ guards to the module when there weren't any before, and wants 11473 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11474 // efficient in lieu of being smart in that rather obscure case. 11475 11476 auto *GuardDecl = F.getParent()->getFunction( 11477 Intrinsic::getName(Intrinsic::experimental_guard)); 11478 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11479 } 11480 11481 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11482 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11483 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11484 ValueExprMap(std::move(Arg.ValueExprMap)), 11485 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11486 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11487 PendingMerges(std::move(Arg.PendingMerges)), 11488 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11489 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11490 PredicatedBackedgeTakenCounts( 11491 std::move(Arg.PredicatedBackedgeTakenCounts)), 11492 ConstantEvolutionLoopExitValue( 11493 std::move(Arg.ConstantEvolutionLoopExitValue)), 11494 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11495 LoopDispositions(std::move(Arg.LoopDispositions)), 11496 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11497 BlockDispositions(std::move(Arg.BlockDispositions)), 11498 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11499 SignedRanges(std::move(Arg.SignedRanges)), 11500 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11501 UniquePreds(std::move(Arg.UniquePreds)), 11502 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11503 LoopUsers(std::move(Arg.LoopUsers)), 11504 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11505 FirstUnknown(Arg.FirstUnknown) { 11506 Arg.FirstUnknown = nullptr; 11507 } 11508 11509 ScalarEvolution::~ScalarEvolution() { 11510 // Iterate through all the SCEVUnknown instances and call their 11511 // destructors, so that they release their references to their values. 11512 for (SCEVUnknown *U = FirstUnknown; U;) { 11513 SCEVUnknown *Tmp = U; 11514 U = U->Next; 11515 Tmp->~SCEVUnknown(); 11516 } 11517 FirstUnknown = nullptr; 11518 11519 ExprValueMap.clear(); 11520 ValueExprMap.clear(); 11521 HasRecMap.clear(); 11522 11523 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11524 // that a loop had multiple computable exits. 11525 for (auto &BTCI : BackedgeTakenCounts) 11526 BTCI.second.clear(); 11527 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11528 BTCI.second.clear(); 11529 11530 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11531 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11532 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11533 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11534 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11535 } 11536 11537 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11538 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11539 } 11540 11541 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11542 const Loop *L) { 11543 // Print all inner loops first 11544 for (Loop *I : *L) 11545 PrintLoopInfo(OS, SE, I); 11546 11547 OS << "Loop "; 11548 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11549 OS << ": "; 11550 11551 SmallVector<BasicBlock *, 8> ExitingBlocks; 11552 L->getExitingBlocks(ExitingBlocks); 11553 if (ExitingBlocks.size() != 1) 11554 OS << "<multiple exits> "; 11555 11556 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11557 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11558 else 11559 OS << "Unpredictable backedge-taken count.\n"; 11560 11561 if (ExitingBlocks.size() > 1) 11562 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11563 OS << " exit count for " << ExitingBlock->getName() << ": " 11564 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11565 } 11566 11567 OS << "Loop "; 11568 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11569 OS << ": "; 11570 11571 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11572 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11573 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11574 OS << ", actual taken count either this or zero."; 11575 } else { 11576 OS << "Unpredictable max backedge-taken count. "; 11577 } 11578 11579 OS << "\n" 11580 "Loop "; 11581 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11582 OS << ": "; 11583 11584 SCEVUnionPredicate Pred; 11585 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11586 if (!isa<SCEVCouldNotCompute>(PBT)) { 11587 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11588 OS << " Predicates:\n"; 11589 Pred.print(OS, 4); 11590 } else { 11591 OS << "Unpredictable predicated backedge-taken count. "; 11592 } 11593 OS << "\n"; 11594 11595 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11596 OS << "Loop "; 11597 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11598 OS << ": "; 11599 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11600 } 11601 } 11602 11603 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11604 switch (LD) { 11605 case ScalarEvolution::LoopVariant: 11606 return "Variant"; 11607 case ScalarEvolution::LoopInvariant: 11608 return "Invariant"; 11609 case ScalarEvolution::LoopComputable: 11610 return "Computable"; 11611 } 11612 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11613 } 11614 11615 void ScalarEvolution::print(raw_ostream &OS) const { 11616 // ScalarEvolution's implementation of the print method is to print 11617 // out SCEV values of all instructions that are interesting. Doing 11618 // this potentially causes it to create new SCEV objects though, 11619 // which technically conflicts with the const qualifier. This isn't 11620 // observable from outside the class though, so casting away the 11621 // const isn't dangerous. 11622 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11623 11624 if (ClassifyExpressions) { 11625 OS << "Classifying expressions for: "; 11626 F.printAsOperand(OS, /*PrintType=*/false); 11627 OS << "\n"; 11628 for (Instruction &I : instructions(F)) 11629 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11630 OS << I << '\n'; 11631 OS << " --> "; 11632 const SCEV *SV = SE.getSCEV(&I); 11633 SV->print(OS); 11634 if (!isa<SCEVCouldNotCompute>(SV)) { 11635 OS << " U: "; 11636 SE.getUnsignedRange(SV).print(OS); 11637 OS << " S: "; 11638 SE.getSignedRange(SV).print(OS); 11639 } 11640 11641 const Loop *L = LI.getLoopFor(I.getParent()); 11642 11643 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11644 if (AtUse != SV) { 11645 OS << " --> "; 11646 AtUse->print(OS); 11647 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11648 OS << " U: "; 11649 SE.getUnsignedRange(AtUse).print(OS); 11650 OS << " S: "; 11651 SE.getSignedRange(AtUse).print(OS); 11652 } 11653 } 11654 11655 if (L) { 11656 OS << "\t\t" "Exits: "; 11657 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11658 if (!SE.isLoopInvariant(ExitValue, L)) { 11659 OS << "<<Unknown>>"; 11660 } else { 11661 OS << *ExitValue; 11662 } 11663 11664 bool First = true; 11665 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11666 if (First) { 11667 OS << "\t\t" "LoopDispositions: { "; 11668 First = false; 11669 } else { 11670 OS << ", "; 11671 } 11672 11673 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11674 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11675 } 11676 11677 for (auto *InnerL : depth_first(L)) { 11678 if (InnerL == L) 11679 continue; 11680 if (First) { 11681 OS << "\t\t" "LoopDispositions: { "; 11682 First = false; 11683 } else { 11684 OS << ", "; 11685 } 11686 11687 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11688 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11689 } 11690 11691 OS << " }"; 11692 } 11693 11694 OS << "\n"; 11695 } 11696 } 11697 11698 OS << "Determining loop execution counts for: "; 11699 F.printAsOperand(OS, /*PrintType=*/false); 11700 OS << "\n"; 11701 for (Loop *I : LI) 11702 PrintLoopInfo(OS, &SE, I); 11703 } 11704 11705 ScalarEvolution::LoopDisposition 11706 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11707 auto &Values = LoopDispositions[S]; 11708 for (auto &V : Values) { 11709 if (V.getPointer() == L) 11710 return V.getInt(); 11711 } 11712 Values.emplace_back(L, LoopVariant); 11713 LoopDisposition D = computeLoopDisposition(S, L); 11714 auto &Values2 = LoopDispositions[S]; 11715 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11716 if (V.getPointer() == L) { 11717 V.setInt(D); 11718 break; 11719 } 11720 } 11721 return D; 11722 } 11723 11724 ScalarEvolution::LoopDisposition 11725 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11726 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11727 case scConstant: 11728 return LoopInvariant; 11729 case scTruncate: 11730 case scZeroExtend: 11731 case scSignExtend: 11732 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11733 case scAddRecExpr: { 11734 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11735 11736 // If L is the addrec's loop, it's computable. 11737 if (AR->getLoop() == L) 11738 return LoopComputable; 11739 11740 // Add recurrences are never invariant in the function-body (null loop). 11741 if (!L) 11742 return LoopVariant; 11743 11744 // Everything that is not defined at loop entry is variant. 11745 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11746 return LoopVariant; 11747 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11748 " dominate the contained loop's header?"); 11749 11750 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11751 if (AR->getLoop()->contains(L)) 11752 return LoopInvariant; 11753 11754 // This recurrence is variant w.r.t. L if any of its operands 11755 // are variant. 11756 for (auto *Op : AR->operands()) 11757 if (!isLoopInvariant(Op, L)) 11758 return LoopVariant; 11759 11760 // Otherwise it's loop-invariant. 11761 return LoopInvariant; 11762 } 11763 case scAddExpr: 11764 case scMulExpr: 11765 case scUMaxExpr: 11766 case scSMaxExpr: 11767 case scUMinExpr: 11768 case scSMinExpr: { 11769 bool HasVarying = false; 11770 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11771 LoopDisposition D = getLoopDisposition(Op, L); 11772 if (D == LoopVariant) 11773 return LoopVariant; 11774 if (D == LoopComputable) 11775 HasVarying = true; 11776 } 11777 return HasVarying ? LoopComputable : LoopInvariant; 11778 } 11779 case scUDivExpr: { 11780 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11781 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11782 if (LD == LoopVariant) 11783 return LoopVariant; 11784 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11785 if (RD == LoopVariant) 11786 return LoopVariant; 11787 return (LD == LoopInvariant && RD == LoopInvariant) ? 11788 LoopInvariant : LoopComputable; 11789 } 11790 case scUnknown: 11791 // All non-instruction values are loop invariant. All instructions are loop 11792 // invariant if they are not contained in the specified loop. 11793 // Instructions are never considered invariant in the function body 11794 // (null loop) because they are defined within the "loop". 11795 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11796 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11797 return LoopInvariant; 11798 case scCouldNotCompute: 11799 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11800 } 11801 llvm_unreachable("Unknown SCEV kind!"); 11802 } 11803 11804 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11805 return getLoopDisposition(S, L) == LoopInvariant; 11806 } 11807 11808 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11809 return getLoopDisposition(S, L) == LoopComputable; 11810 } 11811 11812 ScalarEvolution::BlockDisposition 11813 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11814 auto &Values = BlockDispositions[S]; 11815 for (auto &V : Values) { 11816 if (V.getPointer() == BB) 11817 return V.getInt(); 11818 } 11819 Values.emplace_back(BB, DoesNotDominateBlock); 11820 BlockDisposition D = computeBlockDisposition(S, BB); 11821 auto &Values2 = BlockDispositions[S]; 11822 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11823 if (V.getPointer() == BB) { 11824 V.setInt(D); 11825 break; 11826 } 11827 } 11828 return D; 11829 } 11830 11831 ScalarEvolution::BlockDisposition 11832 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11833 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11834 case scConstant: 11835 return ProperlyDominatesBlock; 11836 case scTruncate: 11837 case scZeroExtend: 11838 case scSignExtend: 11839 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11840 case scAddRecExpr: { 11841 // This uses a "dominates" query instead of "properly dominates" query 11842 // to test for proper dominance too, because the instruction which 11843 // produces the addrec's value is a PHI, and a PHI effectively properly 11844 // dominates its entire containing block. 11845 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11846 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11847 return DoesNotDominateBlock; 11848 11849 // Fall through into SCEVNAryExpr handling. 11850 LLVM_FALLTHROUGH; 11851 } 11852 case scAddExpr: 11853 case scMulExpr: 11854 case scUMaxExpr: 11855 case scSMaxExpr: 11856 case scUMinExpr: 11857 case scSMinExpr: { 11858 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11859 bool Proper = true; 11860 for (const SCEV *NAryOp : NAry->operands()) { 11861 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11862 if (D == DoesNotDominateBlock) 11863 return DoesNotDominateBlock; 11864 if (D == DominatesBlock) 11865 Proper = false; 11866 } 11867 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11868 } 11869 case scUDivExpr: { 11870 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11871 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11872 BlockDisposition LD = getBlockDisposition(LHS, BB); 11873 if (LD == DoesNotDominateBlock) 11874 return DoesNotDominateBlock; 11875 BlockDisposition RD = getBlockDisposition(RHS, BB); 11876 if (RD == DoesNotDominateBlock) 11877 return DoesNotDominateBlock; 11878 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11879 ProperlyDominatesBlock : DominatesBlock; 11880 } 11881 case scUnknown: 11882 if (Instruction *I = 11883 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11884 if (I->getParent() == BB) 11885 return DominatesBlock; 11886 if (DT.properlyDominates(I->getParent(), BB)) 11887 return ProperlyDominatesBlock; 11888 return DoesNotDominateBlock; 11889 } 11890 return ProperlyDominatesBlock; 11891 case scCouldNotCompute: 11892 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11893 } 11894 llvm_unreachable("Unknown SCEV kind!"); 11895 } 11896 11897 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11898 return getBlockDisposition(S, BB) >= DominatesBlock; 11899 } 11900 11901 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11902 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11903 } 11904 11905 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11906 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11907 } 11908 11909 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11910 auto IsS = [&](const SCEV *X) { return S == X; }; 11911 auto ContainsS = [&](const SCEV *X) { 11912 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11913 }; 11914 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11915 } 11916 11917 void 11918 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11919 ValuesAtScopes.erase(S); 11920 LoopDispositions.erase(S); 11921 BlockDispositions.erase(S); 11922 UnsignedRanges.erase(S); 11923 SignedRanges.erase(S); 11924 ExprValueMap.erase(S); 11925 HasRecMap.erase(S); 11926 MinTrailingZerosCache.erase(S); 11927 11928 for (auto I = PredicatedSCEVRewrites.begin(); 11929 I != PredicatedSCEVRewrites.end();) { 11930 std::pair<const SCEV *, const Loop *> Entry = I->first; 11931 if (Entry.first == S) 11932 PredicatedSCEVRewrites.erase(I++); 11933 else 11934 ++I; 11935 } 11936 11937 auto RemoveSCEVFromBackedgeMap = 11938 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11939 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11940 BackedgeTakenInfo &BEInfo = I->second; 11941 if (BEInfo.hasOperand(S, this)) { 11942 BEInfo.clear(); 11943 Map.erase(I++); 11944 } else 11945 ++I; 11946 } 11947 }; 11948 11949 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11950 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11951 } 11952 11953 void 11954 ScalarEvolution::getUsedLoops(const SCEV *S, 11955 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11956 struct FindUsedLoops { 11957 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11958 : LoopsUsed(LoopsUsed) {} 11959 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11960 bool follow(const SCEV *S) { 11961 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11962 LoopsUsed.insert(AR->getLoop()); 11963 return true; 11964 } 11965 11966 bool isDone() const { return false; } 11967 }; 11968 11969 FindUsedLoops F(LoopsUsed); 11970 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11971 } 11972 11973 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11974 SmallPtrSet<const Loop *, 8> LoopsUsed; 11975 getUsedLoops(S, LoopsUsed); 11976 for (auto *L : LoopsUsed) 11977 LoopUsers[L].push_back(S); 11978 } 11979 11980 void ScalarEvolution::verify() const { 11981 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11982 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11983 11984 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11985 11986 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11987 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11988 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11989 11990 const SCEV *visitConstant(const SCEVConstant *Constant) { 11991 return SE.getConstant(Constant->getAPInt()); 11992 } 11993 11994 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11995 return SE.getUnknown(Expr->getValue()); 11996 } 11997 11998 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11999 return SE.getCouldNotCompute(); 12000 } 12001 }; 12002 12003 SCEVMapper SCM(SE2); 12004 12005 while (!LoopStack.empty()) { 12006 auto *L = LoopStack.pop_back_val(); 12007 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12008 12009 auto *CurBECount = SCM.visit( 12010 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12011 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12012 12013 if (CurBECount == SE2.getCouldNotCompute() || 12014 NewBECount == SE2.getCouldNotCompute()) { 12015 // NB! This situation is legal, but is very suspicious -- whatever pass 12016 // change the loop to make a trip count go from could not compute to 12017 // computable or vice-versa *should have* invalidated SCEV. However, we 12018 // choose not to assert here (for now) since we don't want false 12019 // positives. 12020 continue; 12021 } 12022 12023 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12024 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12025 // not propagate undef aggressively). This means we can (and do) fail 12026 // verification in cases where a transform makes the trip count of a loop 12027 // go from "undef" to "undef+1" (say). The transform is fine, since in 12028 // both cases the loop iterates "undef" times, but SCEV thinks we 12029 // increased the trip count of the loop by 1 incorrectly. 12030 continue; 12031 } 12032 12033 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12034 SE.getTypeSizeInBits(NewBECount->getType())) 12035 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12036 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12037 SE.getTypeSizeInBits(NewBECount->getType())) 12038 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12039 12040 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12041 12042 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12043 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12044 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12045 dbgs() << "Old: " << *CurBECount << "\n"; 12046 dbgs() << "New: " << *NewBECount << "\n"; 12047 dbgs() << "Delta: " << *Delta << "\n"; 12048 std::abort(); 12049 } 12050 } 12051 } 12052 12053 bool ScalarEvolution::invalidate( 12054 Function &F, const PreservedAnalyses &PA, 12055 FunctionAnalysisManager::Invalidator &Inv) { 12056 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12057 // of its dependencies is invalidated. 12058 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12059 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12060 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12061 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12062 Inv.invalidate<LoopAnalysis>(F, PA); 12063 } 12064 12065 AnalysisKey ScalarEvolutionAnalysis::Key; 12066 12067 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12068 FunctionAnalysisManager &AM) { 12069 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12070 AM.getResult<AssumptionAnalysis>(F), 12071 AM.getResult<DominatorTreeAnalysis>(F), 12072 AM.getResult<LoopAnalysis>(F)); 12073 } 12074 12075 PreservedAnalyses 12076 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12077 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12078 return PreservedAnalyses::all(); 12079 } 12080 12081 PreservedAnalyses 12082 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12083 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12084 return PreservedAnalyses::all(); 12085 } 12086 12087 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12088 "Scalar Evolution Analysis", false, true) 12089 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12090 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12091 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12092 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12093 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12094 "Scalar Evolution Analysis", false, true) 12095 12096 char ScalarEvolutionWrapperPass::ID = 0; 12097 12098 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12099 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12100 } 12101 12102 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12103 SE.reset(new ScalarEvolution( 12104 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12105 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12106 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12107 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12108 return false; 12109 } 12110 12111 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12112 12113 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12114 SE->print(OS); 12115 } 12116 12117 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12118 if (!VerifySCEV) 12119 return; 12120 12121 SE->verify(); 12122 } 12123 12124 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12125 AU.setPreservesAll(); 12126 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12127 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12128 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12129 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12130 } 12131 12132 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12133 const SCEV *RHS) { 12134 FoldingSetNodeID ID; 12135 assert(LHS->getType() == RHS->getType() && 12136 "Type mismatch between LHS and RHS"); 12137 // Unique this node based on the arguments 12138 ID.AddInteger(SCEVPredicate::P_Equal); 12139 ID.AddPointer(LHS); 12140 ID.AddPointer(RHS); 12141 void *IP = nullptr; 12142 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12143 return S; 12144 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12145 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12146 UniquePreds.InsertNode(Eq, IP); 12147 return Eq; 12148 } 12149 12150 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12151 const SCEVAddRecExpr *AR, 12152 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12153 FoldingSetNodeID ID; 12154 // Unique this node based on the arguments 12155 ID.AddInteger(SCEVPredicate::P_Wrap); 12156 ID.AddPointer(AR); 12157 ID.AddInteger(AddedFlags); 12158 void *IP = nullptr; 12159 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12160 return S; 12161 auto *OF = new (SCEVAllocator) 12162 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12163 UniquePreds.InsertNode(OF, IP); 12164 return OF; 12165 } 12166 12167 namespace { 12168 12169 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12170 public: 12171 12172 /// Rewrites \p S in the context of a loop L and the SCEV predication 12173 /// infrastructure. 12174 /// 12175 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12176 /// equivalences present in \p Pred. 12177 /// 12178 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12179 /// \p NewPreds such that the result will be an AddRecExpr. 12180 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12181 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12182 SCEVUnionPredicate *Pred) { 12183 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12184 return Rewriter.visit(S); 12185 } 12186 12187 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12188 if (Pred) { 12189 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12190 for (auto *Pred : ExprPreds) 12191 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12192 if (IPred->getLHS() == Expr) 12193 return IPred->getRHS(); 12194 } 12195 return convertToAddRecWithPreds(Expr); 12196 } 12197 12198 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12199 const SCEV *Operand = visit(Expr->getOperand()); 12200 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12201 if (AR && AR->getLoop() == L && AR->isAffine()) { 12202 // This couldn't be folded because the operand didn't have the nuw 12203 // flag. Add the nusw flag as an assumption that we could make. 12204 const SCEV *Step = AR->getStepRecurrence(SE); 12205 Type *Ty = Expr->getType(); 12206 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12207 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12208 SE.getSignExtendExpr(Step, Ty), L, 12209 AR->getNoWrapFlags()); 12210 } 12211 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12212 } 12213 12214 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12215 const SCEV *Operand = visit(Expr->getOperand()); 12216 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12217 if (AR && AR->getLoop() == L && AR->isAffine()) { 12218 // This couldn't be folded because the operand didn't have the nsw 12219 // flag. Add the nssw flag as an assumption that we could make. 12220 const SCEV *Step = AR->getStepRecurrence(SE); 12221 Type *Ty = Expr->getType(); 12222 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12223 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12224 SE.getSignExtendExpr(Step, Ty), L, 12225 AR->getNoWrapFlags()); 12226 } 12227 return SE.getSignExtendExpr(Operand, Expr->getType()); 12228 } 12229 12230 private: 12231 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12232 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12233 SCEVUnionPredicate *Pred) 12234 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12235 12236 bool addOverflowAssumption(const SCEVPredicate *P) { 12237 if (!NewPreds) { 12238 // Check if we've already made this assumption. 12239 return Pred && Pred->implies(P); 12240 } 12241 NewPreds->insert(P); 12242 return true; 12243 } 12244 12245 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12246 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12247 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12248 return addOverflowAssumption(A); 12249 } 12250 12251 // If \p Expr represents a PHINode, we try to see if it can be represented 12252 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12253 // to add this predicate as a runtime overflow check, we return the AddRec. 12254 // If \p Expr does not meet these conditions (is not a PHI node, or we 12255 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12256 // return \p Expr. 12257 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12258 if (!isa<PHINode>(Expr->getValue())) 12259 return Expr; 12260 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12261 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12262 if (!PredicatedRewrite) 12263 return Expr; 12264 for (auto *P : PredicatedRewrite->second){ 12265 // Wrap predicates from outer loops are not supported. 12266 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12267 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12268 if (L != AR->getLoop()) 12269 return Expr; 12270 } 12271 if (!addOverflowAssumption(P)) 12272 return Expr; 12273 } 12274 return PredicatedRewrite->first; 12275 } 12276 12277 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12278 SCEVUnionPredicate *Pred; 12279 const Loop *L; 12280 }; 12281 12282 } // end anonymous namespace 12283 12284 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12285 SCEVUnionPredicate &Preds) { 12286 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12287 } 12288 12289 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12290 const SCEV *S, const Loop *L, 12291 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12292 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12293 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12294 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12295 12296 if (!AddRec) 12297 return nullptr; 12298 12299 // Since the transformation was successful, we can now transfer the SCEV 12300 // predicates. 12301 for (auto *P : TransformPreds) 12302 Preds.insert(P); 12303 12304 return AddRec; 12305 } 12306 12307 /// SCEV predicates 12308 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12309 SCEVPredicateKind Kind) 12310 : FastID(ID), Kind(Kind) {} 12311 12312 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12313 const SCEV *LHS, const SCEV *RHS) 12314 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12315 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12316 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12317 } 12318 12319 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12320 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12321 12322 if (!Op) 12323 return false; 12324 12325 return Op->LHS == LHS && Op->RHS == RHS; 12326 } 12327 12328 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12329 12330 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12331 12332 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12333 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12334 } 12335 12336 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12337 const SCEVAddRecExpr *AR, 12338 IncrementWrapFlags Flags) 12339 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12340 12341 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12342 12343 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12344 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12345 12346 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12347 } 12348 12349 bool SCEVWrapPredicate::isAlwaysTrue() const { 12350 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12351 IncrementWrapFlags IFlags = Flags; 12352 12353 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12354 IFlags = clearFlags(IFlags, IncrementNSSW); 12355 12356 return IFlags == IncrementAnyWrap; 12357 } 12358 12359 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12360 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12361 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12362 OS << "<nusw>"; 12363 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12364 OS << "<nssw>"; 12365 OS << "\n"; 12366 } 12367 12368 SCEVWrapPredicate::IncrementWrapFlags 12369 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12370 ScalarEvolution &SE) { 12371 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12372 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12373 12374 // We can safely transfer the NSW flag as NSSW. 12375 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12376 ImpliedFlags = IncrementNSSW; 12377 12378 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12379 // If the increment is positive, the SCEV NUW flag will also imply the 12380 // WrapPredicate NUSW flag. 12381 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12382 if (Step->getValue()->getValue().isNonNegative()) 12383 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12384 } 12385 12386 return ImpliedFlags; 12387 } 12388 12389 /// Union predicates don't get cached so create a dummy set ID for it. 12390 SCEVUnionPredicate::SCEVUnionPredicate() 12391 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12392 12393 bool SCEVUnionPredicate::isAlwaysTrue() const { 12394 return all_of(Preds, 12395 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12396 } 12397 12398 ArrayRef<const SCEVPredicate *> 12399 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12400 auto I = SCEVToPreds.find(Expr); 12401 if (I == SCEVToPreds.end()) 12402 return ArrayRef<const SCEVPredicate *>(); 12403 return I->second; 12404 } 12405 12406 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12407 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12408 return all_of(Set->Preds, 12409 [this](const SCEVPredicate *I) { return this->implies(I); }); 12410 12411 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12412 if (ScevPredsIt == SCEVToPreds.end()) 12413 return false; 12414 auto &SCEVPreds = ScevPredsIt->second; 12415 12416 return any_of(SCEVPreds, 12417 [N](const SCEVPredicate *I) { return I->implies(N); }); 12418 } 12419 12420 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12421 12422 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12423 for (auto Pred : Preds) 12424 Pred->print(OS, Depth); 12425 } 12426 12427 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12428 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12429 for (auto Pred : Set->Preds) 12430 add(Pred); 12431 return; 12432 } 12433 12434 if (implies(N)) 12435 return; 12436 12437 const SCEV *Key = N->getExpr(); 12438 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12439 " associated expression!"); 12440 12441 SCEVToPreds[Key].push_back(N); 12442 Preds.push_back(N); 12443 } 12444 12445 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12446 Loop &L) 12447 : SE(SE), L(L) {} 12448 12449 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12450 const SCEV *Expr = SE.getSCEV(V); 12451 RewriteEntry &Entry = RewriteMap[Expr]; 12452 12453 // If we already have an entry and the version matches, return it. 12454 if (Entry.second && Generation == Entry.first) 12455 return Entry.second; 12456 12457 // We found an entry but it's stale. Rewrite the stale entry 12458 // according to the current predicate. 12459 if (Entry.second) 12460 Expr = Entry.second; 12461 12462 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12463 Entry = {Generation, NewSCEV}; 12464 12465 return NewSCEV; 12466 } 12467 12468 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12469 if (!BackedgeCount) { 12470 SCEVUnionPredicate BackedgePred; 12471 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12472 addPredicate(BackedgePred); 12473 } 12474 return BackedgeCount; 12475 } 12476 12477 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12478 if (Preds.implies(&Pred)) 12479 return; 12480 Preds.add(&Pred); 12481 updateGeneration(); 12482 } 12483 12484 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12485 return Preds; 12486 } 12487 12488 void PredicatedScalarEvolution::updateGeneration() { 12489 // If the generation number wrapped recompute everything. 12490 if (++Generation == 0) { 12491 for (auto &II : RewriteMap) { 12492 const SCEV *Rewritten = II.second.second; 12493 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12494 } 12495 } 12496 } 12497 12498 void PredicatedScalarEvolution::setNoOverflow( 12499 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12500 const SCEV *Expr = getSCEV(V); 12501 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12502 12503 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12504 12505 // Clear the statically implied flags. 12506 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12507 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12508 12509 auto II = FlagsMap.insert({V, Flags}); 12510 if (!II.second) 12511 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12512 } 12513 12514 bool PredicatedScalarEvolution::hasNoOverflow( 12515 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12516 const SCEV *Expr = getSCEV(V); 12517 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12518 12519 Flags = SCEVWrapPredicate::clearFlags( 12520 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12521 12522 auto II = FlagsMap.find(V); 12523 12524 if (II != FlagsMap.end()) 12525 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12526 12527 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12528 } 12529 12530 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12531 const SCEV *Expr = this->getSCEV(V); 12532 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12533 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12534 12535 if (!New) 12536 return nullptr; 12537 12538 for (auto *P : NewPreds) 12539 Preds.add(P); 12540 12541 updateGeneration(); 12542 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12543 return New; 12544 } 12545 12546 PredicatedScalarEvolution::PredicatedScalarEvolution( 12547 const PredicatedScalarEvolution &Init) 12548 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12549 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12550 for (auto I : Init.FlagsMap) 12551 FlagsMap.insert(I); 12552 } 12553 12554 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12555 // For each block. 12556 for (auto *BB : L.getBlocks()) 12557 for (auto &I : *BB) { 12558 if (!SE.isSCEVable(I.getType())) 12559 continue; 12560 12561 auto *Expr = SE.getSCEV(&I); 12562 auto II = RewriteMap.find(Expr); 12563 12564 if (II == RewriteMap.end()) 12565 continue; 12566 12567 // Don't print things that are not interesting. 12568 if (II->second.second == Expr) 12569 continue; 12570 12571 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12572 OS.indent(Depth + 2) << *Expr << "\n"; 12573 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12574 } 12575 } 12576 12577 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12578 // arbitrary expressions. 12579 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12580 // 4, A / B becomes X / 8). 12581 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12582 const SCEV *&RHS) { 12583 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12584 if (Add == nullptr || Add->getNumOperands() != 2) 12585 return false; 12586 12587 const SCEV *A = Add->getOperand(1); 12588 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12589 12590 if (Mul == nullptr) 12591 return false; 12592 12593 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12594 // (SomeExpr + (-(SomeExpr / B) * B)). 12595 if (Expr == getURemExpr(A, B)) { 12596 LHS = A; 12597 RHS = B; 12598 return true; 12599 } 12600 return false; 12601 }; 12602 12603 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12604 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12605 return MatchURemWithDivisor(Mul->getOperand(1)) || 12606 MatchURemWithDivisor(Mul->getOperand(2)); 12607 12608 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12609 if (Mul->getNumOperands() == 2) 12610 return MatchURemWithDivisor(Mul->getOperand(1)) || 12611 MatchURemWithDivisor(Mul->getOperand(0)) || 12612 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12613 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12614 return false; 12615 } 12616