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 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2456 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2457 return S; 2458 } 2459 2460 // Okay, check to see if the same value occurs in the operand list more than 2461 // once. If so, merge them together into an multiply expression. Since we 2462 // sorted the list, these values are required to be adjacent. 2463 Type *Ty = Ops[0]->getType(); 2464 bool FoundMatch = false; 2465 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2466 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2467 // Scan ahead to count how many equal operands there are. 2468 unsigned Count = 2; 2469 while (i+Count != e && Ops[i+Count] == Ops[i]) 2470 ++Count; 2471 // Merge the values into a multiply. 2472 const SCEV *Scale = getConstant(Ty, Count); 2473 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2474 if (Ops.size() == Count) 2475 return Mul; 2476 Ops[i] = Mul; 2477 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2478 --i; e -= Count - 1; 2479 FoundMatch = true; 2480 } 2481 if (FoundMatch) 2482 return getAddExpr(Ops, Flags, Depth + 1); 2483 2484 // Check for truncates. If all the operands are truncated from the same 2485 // type, see if factoring out the truncate would permit the result to be 2486 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2487 // if the contents of the resulting outer trunc fold to something simple. 2488 auto FindTruncSrcType = [&]() -> Type * { 2489 // We're ultimately looking to fold an addrec of truncs and muls of only 2490 // constants and truncs, so if we find any other types of SCEV 2491 // as operands of the addrec then we bail and return nullptr here. 2492 // Otherwise, we return the type of the operand of a trunc that we find. 2493 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2494 return T->getOperand()->getType(); 2495 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2496 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2497 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2498 return T->getOperand()->getType(); 2499 } 2500 return nullptr; 2501 }; 2502 if (auto *SrcType = FindTruncSrcType()) { 2503 SmallVector<const SCEV *, 8> LargeOps; 2504 bool Ok = true; 2505 // Check all the operands to see if they can be represented in the 2506 // source type of the truncate. 2507 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2508 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2509 if (T->getOperand()->getType() != SrcType) { 2510 Ok = false; 2511 break; 2512 } 2513 LargeOps.push_back(T->getOperand()); 2514 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2515 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2516 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2517 SmallVector<const SCEV *, 8> LargeMulOps; 2518 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2519 if (const SCEVTruncateExpr *T = 2520 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2521 if (T->getOperand()->getType() != SrcType) { 2522 Ok = false; 2523 break; 2524 } 2525 LargeMulOps.push_back(T->getOperand()); 2526 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2527 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2528 } else { 2529 Ok = false; 2530 break; 2531 } 2532 } 2533 if (Ok) 2534 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2535 } else { 2536 Ok = false; 2537 break; 2538 } 2539 } 2540 if (Ok) { 2541 // Evaluate the expression in the larger type. 2542 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2543 // If it folds to something simple, use it. Otherwise, don't. 2544 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2545 return getTruncateExpr(Fold, Ty); 2546 } 2547 } 2548 2549 // Skip past any other cast SCEVs. 2550 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2551 ++Idx; 2552 2553 // If there are add operands they would be next. 2554 if (Idx < Ops.size()) { 2555 bool DeletedAdd = false; 2556 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2557 if (Ops.size() > AddOpsInlineThreshold || 2558 Add->getNumOperands() > AddOpsInlineThreshold) 2559 break; 2560 // If we have an add, expand the add operands onto the end of the operands 2561 // list. 2562 Ops.erase(Ops.begin()+Idx); 2563 Ops.append(Add->op_begin(), Add->op_end()); 2564 DeletedAdd = true; 2565 } 2566 2567 // If we deleted at least one add, we added operands to the end of the list, 2568 // and they are not necessarily sorted. Recurse to resort and resimplify 2569 // any operands we just acquired. 2570 if (DeletedAdd) 2571 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2572 } 2573 2574 // Skip over the add expression until we get to a multiply. 2575 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2576 ++Idx; 2577 2578 // Check to see if there are any folding opportunities present with 2579 // operands multiplied by constant values. 2580 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2581 uint64_t BitWidth = getTypeSizeInBits(Ty); 2582 DenseMap<const SCEV *, APInt> M; 2583 SmallVector<const SCEV *, 8> NewOps; 2584 APInt AccumulatedConstant(BitWidth, 0); 2585 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2586 Ops.data(), Ops.size(), 2587 APInt(BitWidth, 1), *this)) { 2588 struct APIntCompare { 2589 bool operator()(const APInt &LHS, const APInt &RHS) const { 2590 return LHS.ult(RHS); 2591 } 2592 }; 2593 2594 // Some interesting folding opportunity is present, so its worthwhile to 2595 // re-generate the operands list. Group the operands by constant scale, 2596 // to avoid multiplying by the same constant scale multiple times. 2597 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2598 for (const SCEV *NewOp : NewOps) 2599 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2600 // Re-generate the operands list. 2601 Ops.clear(); 2602 if (AccumulatedConstant != 0) 2603 Ops.push_back(getConstant(AccumulatedConstant)); 2604 for (auto &MulOp : MulOpLists) 2605 if (MulOp.first != 0) 2606 Ops.push_back(getMulExpr( 2607 getConstant(MulOp.first), 2608 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2609 SCEV::FlagAnyWrap, Depth + 1)); 2610 if (Ops.empty()) 2611 return getZero(Ty); 2612 if (Ops.size() == 1) 2613 return Ops[0]; 2614 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2615 } 2616 } 2617 2618 // If we are adding something to a multiply expression, make sure the 2619 // something is not already an operand of the multiply. If so, merge it into 2620 // the multiply. 2621 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2622 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2623 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2624 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2625 if (isa<SCEVConstant>(MulOpSCEV)) 2626 continue; 2627 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2628 if (MulOpSCEV == Ops[AddOp]) { 2629 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2630 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2631 if (Mul->getNumOperands() != 2) { 2632 // If the multiply has more than two operands, we must get the 2633 // Y*Z term. 2634 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2635 Mul->op_begin()+MulOp); 2636 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2637 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2638 } 2639 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2640 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2641 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2642 SCEV::FlagAnyWrap, Depth + 1); 2643 if (Ops.size() == 2) return OuterMul; 2644 if (AddOp < Idx) { 2645 Ops.erase(Ops.begin()+AddOp); 2646 Ops.erase(Ops.begin()+Idx-1); 2647 } else { 2648 Ops.erase(Ops.begin()+Idx); 2649 Ops.erase(Ops.begin()+AddOp-1); 2650 } 2651 Ops.push_back(OuterMul); 2652 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2653 } 2654 2655 // Check this multiply against other multiplies being added together. 2656 for (unsigned OtherMulIdx = Idx+1; 2657 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2658 ++OtherMulIdx) { 2659 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2660 // If MulOp occurs in OtherMul, we can fold the two multiplies 2661 // together. 2662 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2663 OMulOp != e; ++OMulOp) 2664 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2665 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2666 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2667 if (Mul->getNumOperands() != 2) { 2668 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2669 Mul->op_begin()+MulOp); 2670 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2671 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2672 } 2673 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2674 if (OtherMul->getNumOperands() != 2) { 2675 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2676 OtherMul->op_begin()+OMulOp); 2677 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2678 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2679 } 2680 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2681 const SCEV *InnerMulSum = 2682 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2683 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2684 SCEV::FlagAnyWrap, Depth + 1); 2685 if (Ops.size() == 2) return OuterMul; 2686 Ops.erase(Ops.begin()+Idx); 2687 Ops.erase(Ops.begin()+OtherMulIdx-1); 2688 Ops.push_back(OuterMul); 2689 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2690 } 2691 } 2692 } 2693 } 2694 2695 // If there are any add recurrences in the operands list, see if any other 2696 // added values are loop invariant. If so, we can fold them into the 2697 // recurrence. 2698 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2699 ++Idx; 2700 2701 // Scan over all recurrences, trying to fold loop invariants into them. 2702 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2703 // Scan all of the other operands to this add and add them to the vector if 2704 // they are loop invariant w.r.t. the recurrence. 2705 SmallVector<const SCEV *, 8> LIOps; 2706 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2707 const Loop *AddRecLoop = AddRec->getLoop(); 2708 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2709 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2710 LIOps.push_back(Ops[i]); 2711 Ops.erase(Ops.begin()+i); 2712 --i; --e; 2713 } 2714 2715 // If we found some loop invariants, fold them into the recurrence. 2716 if (!LIOps.empty()) { 2717 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2718 LIOps.push_back(AddRec->getStart()); 2719 2720 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2721 AddRec->op_end()); 2722 // This follows from the fact that the no-wrap flags on the outer add 2723 // expression are applicable on the 0th iteration, when the add recurrence 2724 // will be equal to its start value. 2725 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2726 2727 // Build the new addrec. Propagate the NUW and NSW flags if both the 2728 // outer add and the inner addrec are guaranteed to have no overflow. 2729 // Always propagate NW. 2730 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2731 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2732 2733 // If all of the other operands were loop invariant, we are done. 2734 if (Ops.size() == 1) return NewRec; 2735 2736 // Otherwise, add the folded AddRec by the non-invariant parts. 2737 for (unsigned i = 0;; ++i) 2738 if (Ops[i] == AddRec) { 2739 Ops[i] = NewRec; 2740 break; 2741 } 2742 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2743 } 2744 2745 // Okay, if there weren't any loop invariants to be folded, check to see if 2746 // there are multiple AddRec's with the same loop induction variable being 2747 // added together. If so, we can fold them. 2748 for (unsigned OtherIdx = Idx+1; 2749 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2750 ++OtherIdx) { 2751 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2752 // so that the 1st found AddRecExpr is dominated by all others. 2753 assert(DT.dominates( 2754 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2755 AddRec->getLoop()->getHeader()) && 2756 "AddRecExprs are not sorted in reverse dominance order?"); 2757 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2758 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2759 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2760 AddRec->op_end()); 2761 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2762 ++OtherIdx) { 2763 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2764 if (OtherAddRec->getLoop() == AddRecLoop) { 2765 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2766 i != e; ++i) { 2767 if (i >= AddRecOps.size()) { 2768 AddRecOps.append(OtherAddRec->op_begin()+i, 2769 OtherAddRec->op_end()); 2770 break; 2771 } 2772 SmallVector<const SCEV *, 2> TwoOps = { 2773 AddRecOps[i], OtherAddRec->getOperand(i)}; 2774 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2775 } 2776 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2777 } 2778 } 2779 // Step size has changed, so we cannot guarantee no self-wraparound. 2780 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2781 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2782 } 2783 } 2784 2785 // Otherwise couldn't fold anything into this recurrence. Move onto the 2786 // next one. 2787 } 2788 2789 // Okay, it looks like we really DO need an add expr. Check to see if we 2790 // already have one, otherwise create a new one. 2791 return getOrCreateAddExpr(Ops, Flags); 2792 } 2793 2794 const SCEV * 2795 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2796 SCEV::NoWrapFlags Flags) { 2797 FoldingSetNodeID ID; 2798 ID.AddInteger(scAddExpr); 2799 for (const SCEV *Op : Ops) 2800 ID.AddPointer(Op); 2801 void *IP = nullptr; 2802 SCEVAddExpr *S = 2803 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2804 if (!S) { 2805 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2806 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2807 S = new (SCEVAllocator) 2808 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2809 UniqueSCEVs.InsertNode(S, IP); 2810 addToLoopUseLists(S); 2811 } 2812 S->setNoWrapFlags(Flags); 2813 return S; 2814 } 2815 2816 const SCEV * 2817 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2818 const Loop *L, SCEV::NoWrapFlags Flags) { 2819 FoldingSetNodeID ID; 2820 ID.AddInteger(scAddRecExpr); 2821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2822 ID.AddPointer(Ops[i]); 2823 ID.AddPointer(L); 2824 void *IP = nullptr; 2825 SCEVAddRecExpr *S = 2826 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2827 if (!S) { 2828 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2829 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2830 S = new (SCEVAllocator) 2831 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2832 UniqueSCEVs.InsertNode(S, IP); 2833 addToLoopUseLists(S); 2834 } 2835 S->setNoWrapFlags(Flags); 2836 return S; 2837 } 2838 2839 const SCEV * 2840 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2841 SCEV::NoWrapFlags Flags) { 2842 FoldingSetNodeID ID; 2843 ID.AddInteger(scMulExpr); 2844 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2845 ID.AddPointer(Ops[i]); 2846 void *IP = nullptr; 2847 SCEVMulExpr *S = 2848 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2849 if (!S) { 2850 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2851 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2852 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2853 O, Ops.size()); 2854 UniqueSCEVs.InsertNode(S, IP); 2855 addToLoopUseLists(S); 2856 } 2857 S->setNoWrapFlags(Flags); 2858 return S; 2859 } 2860 2861 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2862 uint64_t k = i*j; 2863 if (j > 1 && k / j != i) Overflow = true; 2864 return k; 2865 } 2866 2867 /// Compute the result of "n choose k", the binomial coefficient. If an 2868 /// intermediate computation overflows, Overflow will be set and the return will 2869 /// be garbage. Overflow is not cleared on absence of overflow. 2870 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2871 // We use the multiplicative formula: 2872 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2873 // At each iteration, we take the n-th term of the numeral and divide by the 2874 // (k-n)th term of the denominator. This division will always produce an 2875 // integral result, and helps reduce the chance of overflow in the 2876 // intermediate computations. However, we can still overflow even when the 2877 // final result would fit. 2878 2879 if (n == 0 || n == k) return 1; 2880 if (k > n) return 0; 2881 2882 if (k > n/2) 2883 k = n-k; 2884 2885 uint64_t r = 1; 2886 for (uint64_t i = 1; i <= k; ++i) { 2887 r = umul_ov(r, n-(i-1), Overflow); 2888 r /= i; 2889 } 2890 return r; 2891 } 2892 2893 /// Determine if any of the operands in this SCEV are a constant or if 2894 /// any of the add or multiply expressions in this SCEV contain a constant. 2895 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2896 struct FindConstantInAddMulChain { 2897 bool FoundConstant = false; 2898 2899 bool follow(const SCEV *S) { 2900 FoundConstant |= isa<SCEVConstant>(S); 2901 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2902 } 2903 2904 bool isDone() const { 2905 return FoundConstant; 2906 } 2907 }; 2908 2909 FindConstantInAddMulChain F; 2910 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2911 ST.visitAll(StartExpr); 2912 return F.FoundConstant; 2913 } 2914 2915 /// Get a canonical multiply expression, or something simpler if possible. 2916 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2917 SCEV::NoWrapFlags Flags, 2918 unsigned Depth) { 2919 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2920 "only nuw or nsw allowed"); 2921 assert(!Ops.empty() && "Cannot get empty mul!"); 2922 if (Ops.size() == 1) return Ops[0]; 2923 #ifndef NDEBUG 2924 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2925 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2926 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2927 "SCEVMulExpr operand types don't match!"); 2928 #endif 2929 2930 // Sort by complexity, this groups all similar expression types together. 2931 GroupByComplexity(Ops, &LI, DT); 2932 2933 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2934 2935 // Limit recursion calls depth. 2936 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2937 return getOrCreateMulExpr(Ops, Flags); 2938 2939 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2940 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2941 return S; 2942 } 2943 2944 // If there are any constants, fold them together. 2945 unsigned Idx = 0; 2946 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2947 2948 if (Ops.size() == 2) 2949 // C1*(C2+V) -> C1*C2 + C1*V 2950 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2951 // If any of Add's ops are Adds or Muls with a constant, apply this 2952 // transformation as well. 2953 // 2954 // TODO: There are some cases where this transformation is not 2955 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2956 // this transformation should be narrowed down. 2957 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2958 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2959 SCEV::FlagAnyWrap, Depth + 1), 2960 getMulExpr(LHSC, Add->getOperand(1), 2961 SCEV::FlagAnyWrap, Depth + 1), 2962 SCEV::FlagAnyWrap, Depth + 1); 2963 2964 ++Idx; 2965 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2966 // We found two constants, fold them together! 2967 ConstantInt *Fold = 2968 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2969 Ops[0] = getConstant(Fold); 2970 Ops.erase(Ops.begin()+1); // Erase the folded element 2971 if (Ops.size() == 1) return Ops[0]; 2972 LHSC = cast<SCEVConstant>(Ops[0]); 2973 } 2974 2975 // If we are left with a constant one being multiplied, strip it off. 2976 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2977 Ops.erase(Ops.begin()); 2978 --Idx; 2979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2980 // If we have a multiply of zero, it will always be zero. 2981 return Ops[0]; 2982 } else if (Ops[0]->isAllOnesValue()) { 2983 // If we have a mul by -1 of an add, try distributing the -1 among the 2984 // add operands. 2985 if (Ops.size() == 2) { 2986 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2987 SmallVector<const SCEV *, 4> NewOps; 2988 bool AnyFolded = false; 2989 for (const SCEV *AddOp : Add->operands()) { 2990 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2991 Depth + 1); 2992 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2993 NewOps.push_back(Mul); 2994 } 2995 if (AnyFolded) 2996 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2997 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2998 // Negation preserves a recurrence's no self-wrap property. 2999 SmallVector<const SCEV *, 4> Operands; 3000 for (const SCEV *AddRecOp : AddRec->operands()) 3001 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3002 Depth + 1)); 3003 3004 return getAddRecExpr(Operands, AddRec->getLoop(), 3005 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3006 } 3007 } 3008 } 3009 3010 if (Ops.size() == 1) 3011 return Ops[0]; 3012 } 3013 3014 // Skip over the add expression until we get to a multiply. 3015 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3016 ++Idx; 3017 3018 // If there are mul operands inline them all into this expression. 3019 if (Idx < Ops.size()) { 3020 bool DeletedMul = false; 3021 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3022 if (Ops.size() > MulOpsInlineThreshold) 3023 break; 3024 // If we have an mul, expand the mul operands onto the end of the 3025 // operands list. 3026 Ops.erase(Ops.begin()+Idx); 3027 Ops.append(Mul->op_begin(), Mul->op_end()); 3028 DeletedMul = true; 3029 } 3030 3031 // If we deleted at least one mul, we added operands to the end of the 3032 // list, and they are not necessarily sorted. Recurse to resort and 3033 // resimplify any operands we just acquired. 3034 if (DeletedMul) 3035 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3036 } 3037 3038 // If there are any add recurrences in the operands list, see if any other 3039 // added values are loop invariant. If so, we can fold them into the 3040 // recurrence. 3041 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3042 ++Idx; 3043 3044 // Scan over all recurrences, trying to fold loop invariants into them. 3045 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3046 // Scan all of the other operands to this mul and add them to the vector 3047 // if they are loop invariant w.r.t. the recurrence. 3048 SmallVector<const SCEV *, 8> LIOps; 3049 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3050 const Loop *AddRecLoop = AddRec->getLoop(); 3051 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3052 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3053 LIOps.push_back(Ops[i]); 3054 Ops.erase(Ops.begin()+i); 3055 --i; --e; 3056 } 3057 3058 // If we found some loop invariants, fold them into the recurrence. 3059 if (!LIOps.empty()) { 3060 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3061 SmallVector<const SCEV *, 4> NewOps; 3062 NewOps.reserve(AddRec->getNumOperands()); 3063 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3064 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3065 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3066 SCEV::FlagAnyWrap, Depth + 1)); 3067 3068 // Build the new addrec. Propagate the NUW and NSW flags if both the 3069 // outer mul and the inner addrec are guaranteed to have no overflow. 3070 // 3071 // No self-wrap cannot be guaranteed after changing the step size, but 3072 // will be inferred if either NUW or NSW is true. 3073 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3074 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3075 3076 // If all of the other operands were loop invariant, we are done. 3077 if (Ops.size() == 1) return NewRec; 3078 3079 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3080 for (unsigned i = 0;; ++i) 3081 if (Ops[i] == AddRec) { 3082 Ops[i] = NewRec; 3083 break; 3084 } 3085 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3086 } 3087 3088 // Okay, if there weren't any loop invariants to be folded, check to see 3089 // if there are multiple AddRec's with the same loop induction variable 3090 // being multiplied together. If so, we can fold them. 3091 3092 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3093 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3094 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3095 // ]]],+,...up to x=2n}. 3096 // Note that the arguments to choose() are always integers with values 3097 // known at compile time, never SCEV objects. 3098 // 3099 // The implementation avoids pointless extra computations when the two 3100 // addrec's are of different length (mathematically, it's equivalent to 3101 // an infinite stream of zeros on the right). 3102 bool OpsModified = false; 3103 for (unsigned OtherIdx = Idx+1; 3104 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3105 ++OtherIdx) { 3106 const SCEVAddRecExpr *OtherAddRec = 3107 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3108 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3109 continue; 3110 3111 // Limit max number of arguments to avoid creation of unreasonably big 3112 // SCEVAddRecs with very complex operands. 3113 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3114 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3115 continue; 3116 3117 bool Overflow = false; 3118 Type *Ty = AddRec->getType(); 3119 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3120 SmallVector<const SCEV*, 7> AddRecOps; 3121 for (int x = 0, xe = AddRec->getNumOperands() + 3122 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3123 SmallVector <const SCEV *, 7> SumOps; 3124 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3125 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3126 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3127 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3128 z < ze && !Overflow; ++z) { 3129 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3130 uint64_t Coeff; 3131 if (LargerThan64Bits) 3132 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3133 else 3134 Coeff = Coeff1*Coeff2; 3135 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3136 const SCEV *Term1 = AddRec->getOperand(y-z); 3137 const SCEV *Term2 = OtherAddRec->getOperand(z); 3138 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3139 SCEV::FlagAnyWrap, Depth + 1)); 3140 } 3141 } 3142 if (SumOps.empty()) 3143 SumOps.push_back(getZero(Ty)); 3144 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3145 } 3146 if (!Overflow) { 3147 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3148 SCEV::FlagAnyWrap); 3149 if (Ops.size() == 2) return NewAddRec; 3150 Ops[Idx] = NewAddRec; 3151 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3152 OpsModified = true; 3153 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3154 if (!AddRec) 3155 break; 3156 } 3157 } 3158 if (OpsModified) 3159 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3160 3161 // Otherwise couldn't fold anything into this recurrence. Move onto the 3162 // next one. 3163 } 3164 3165 // Okay, it looks like we really DO need an mul expr. Check to see if we 3166 // already have one, otherwise create a new one. 3167 return getOrCreateMulExpr(Ops, Flags); 3168 } 3169 3170 /// Represents an unsigned remainder expression based on unsigned division. 3171 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3172 const SCEV *RHS) { 3173 assert(getEffectiveSCEVType(LHS->getType()) == 3174 getEffectiveSCEVType(RHS->getType()) && 3175 "SCEVURemExpr operand types don't match!"); 3176 3177 // Short-circuit easy cases 3178 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3179 // If constant is one, the result is trivial 3180 if (RHSC->getValue()->isOne()) 3181 return getZero(LHS->getType()); // X urem 1 --> 0 3182 3183 // If constant is a power of two, fold into a zext(trunc(LHS)). 3184 if (RHSC->getAPInt().isPowerOf2()) { 3185 Type *FullTy = LHS->getType(); 3186 Type *TruncTy = 3187 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3188 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3189 } 3190 } 3191 3192 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3193 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3194 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3195 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3196 } 3197 3198 /// Get a canonical unsigned division expression, or something simpler if 3199 /// possible. 3200 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3201 const SCEV *RHS) { 3202 assert(getEffectiveSCEVType(LHS->getType()) == 3203 getEffectiveSCEVType(RHS->getType()) && 3204 "SCEVUDivExpr operand types don't match!"); 3205 3206 FoldingSetNodeID ID; 3207 ID.AddInteger(scUDivExpr); 3208 ID.AddPointer(LHS); 3209 ID.AddPointer(RHS); 3210 void *IP = nullptr; 3211 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3212 return S; 3213 3214 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3215 if (RHSC->getValue()->isOne()) 3216 return LHS; // X udiv 1 --> x 3217 // If the denominator is zero, the result of the udiv is undefined. Don't 3218 // try to analyze it, because the resolution chosen here may differ from 3219 // the resolution chosen in other parts of the compiler. 3220 if (!RHSC->getValue()->isZero()) { 3221 // Determine if the division can be folded into the operands of 3222 // its operands. 3223 // TODO: Generalize this to non-constants by using known-bits information. 3224 Type *Ty = LHS->getType(); 3225 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3226 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3227 // For non-power-of-two values, effectively round the value up to the 3228 // nearest power of two. 3229 if (!RHSC->getAPInt().isPowerOf2()) 3230 ++MaxShiftAmt; 3231 IntegerType *ExtTy = 3232 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3233 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3234 if (const SCEVConstant *Step = 3235 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3236 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3237 const APInt &StepInt = Step->getAPInt(); 3238 const APInt &DivInt = RHSC->getAPInt(); 3239 if (!StepInt.urem(DivInt) && 3240 getZeroExtendExpr(AR, ExtTy) == 3241 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3242 getZeroExtendExpr(Step, ExtTy), 3243 AR->getLoop(), SCEV::FlagAnyWrap)) { 3244 SmallVector<const SCEV *, 4> Operands; 3245 for (const SCEV *Op : AR->operands()) 3246 Operands.push_back(getUDivExpr(Op, RHS)); 3247 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3248 } 3249 /// Get a canonical UDivExpr for a recurrence. 3250 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3251 // We can currently only fold X%N if X is constant. 3252 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3253 if (StartC && !DivInt.urem(StepInt) && 3254 getZeroExtendExpr(AR, ExtTy) == 3255 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3256 getZeroExtendExpr(Step, ExtTy), 3257 AR->getLoop(), SCEV::FlagAnyWrap)) { 3258 const APInt &StartInt = StartC->getAPInt(); 3259 const APInt &StartRem = StartInt.urem(StepInt); 3260 if (StartRem != 0) { 3261 const SCEV *NewLHS = 3262 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3263 AR->getLoop(), SCEV::FlagNW); 3264 if (LHS != NewLHS) { 3265 LHS = NewLHS; 3266 3267 // Reset the ID to include the new LHS, and check if it is 3268 // already cached. 3269 ID.clear(); 3270 ID.AddInteger(scUDivExpr); 3271 ID.AddPointer(LHS); 3272 ID.AddPointer(RHS); 3273 IP = nullptr; 3274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3275 return S; 3276 } 3277 } 3278 } 3279 } 3280 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3281 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3282 SmallVector<const SCEV *, 4> Operands; 3283 for (const SCEV *Op : M->operands()) 3284 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3285 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3286 // Find an operand that's safely divisible. 3287 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3288 const SCEV *Op = M->getOperand(i); 3289 const SCEV *Div = getUDivExpr(Op, RHSC); 3290 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3291 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3292 M->op_end()); 3293 Operands[i] = Div; 3294 return getMulExpr(Operands); 3295 } 3296 } 3297 } 3298 3299 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3300 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3301 if (auto *DivisorConstant = 3302 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3303 bool Overflow = false; 3304 APInt NewRHS = 3305 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3306 if (Overflow) { 3307 return getConstant(RHSC->getType(), 0, false); 3308 } 3309 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3310 } 3311 } 3312 3313 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3314 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3315 SmallVector<const SCEV *, 4> Operands; 3316 for (const SCEV *Op : A->operands()) 3317 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3318 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3319 Operands.clear(); 3320 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3321 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3322 if (isa<SCEVUDivExpr>(Op) || 3323 getMulExpr(Op, RHS) != A->getOperand(i)) 3324 break; 3325 Operands.push_back(Op); 3326 } 3327 if (Operands.size() == A->getNumOperands()) 3328 return getAddExpr(Operands); 3329 } 3330 } 3331 3332 // Fold if both operands are constant. 3333 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3334 Constant *LHSCV = LHSC->getValue(); 3335 Constant *RHSCV = RHSC->getValue(); 3336 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3337 RHSCV))); 3338 } 3339 } 3340 } 3341 3342 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3343 LHS, RHS); 3344 UniqueSCEVs.InsertNode(S, IP); 3345 addToLoopUseLists(S); 3346 return S; 3347 } 3348 3349 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3350 APInt A = C1->getAPInt().abs(); 3351 APInt B = C2->getAPInt().abs(); 3352 uint32_t ABW = A.getBitWidth(); 3353 uint32_t BBW = B.getBitWidth(); 3354 3355 if (ABW > BBW) 3356 B = B.zext(ABW); 3357 else if (ABW < BBW) 3358 A = A.zext(BBW); 3359 3360 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3361 } 3362 3363 /// Get a canonical unsigned division expression, or something simpler if 3364 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3365 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3366 /// it's not exact because the udiv may be clearing bits. 3367 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3368 const SCEV *RHS) { 3369 // TODO: we could try to find factors in all sorts of things, but for now we 3370 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3371 // end of this file for inspiration. 3372 3373 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3374 if (!Mul || !Mul->hasNoUnsignedWrap()) 3375 return getUDivExpr(LHS, RHS); 3376 3377 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3378 // If the mulexpr multiplies by a constant, then that constant must be the 3379 // first element of the mulexpr. 3380 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3381 if (LHSCst == RHSCst) { 3382 SmallVector<const SCEV *, 2> Operands; 3383 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3384 return getMulExpr(Operands); 3385 } 3386 3387 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3388 // that there's a factor provided by one of the other terms. We need to 3389 // check. 3390 APInt Factor = gcd(LHSCst, RHSCst); 3391 if (!Factor.isIntN(1)) { 3392 LHSCst = 3393 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3394 RHSCst = 3395 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3396 SmallVector<const SCEV *, 2> Operands; 3397 Operands.push_back(LHSCst); 3398 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3399 LHS = getMulExpr(Operands); 3400 RHS = RHSCst; 3401 Mul = dyn_cast<SCEVMulExpr>(LHS); 3402 if (!Mul) 3403 return getUDivExactExpr(LHS, RHS); 3404 } 3405 } 3406 } 3407 3408 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3409 if (Mul->getOperand(i) == RHS) { 3410 SmallVector<const SCEV *, 2> Operands; 3411 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3412 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3413 return getMulExpr(Operands); 3414 } 3415 } 3416 3417 return getUDivExpr(LHS, RHS); 3418 } 3419 3420 /// Get an add recurrence expression for the specified loop. Simplify the 3421 /// expression as much as possible. 3422 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3423 const Loop *L, 3424 SCEV::NoWrapFlags Flags) { 3425 SmallVector<const SCEV *, 4> Operands; 3426 Operands.push_back(Start); 3427 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3428 if (StepChrec->getLoop() == L) { 3429 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3430 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3431 } 3432 3433 Operands.push_back(Step); 3434 return getAddRecExpr(Operands, L, Flags); 3435 } 3436 3437 /// Get an add recurrence expression for the specified loop. Simplify the 3438 /// expression as much as possible. 3439 const SCEV * 3440 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3441 const Loop *L, SCEV::NoWrapFlags Flags) { 3442 if (Operands.size() == 1) return Operands[0]; 3443 #ifndef NDEBUG 3444 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3445 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3446 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3447 "SCEVAddRecExpr operand types don't match!"); 3448 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3449 assert(isLoopInvariant(Operands[i], L) && 3450 "SCEVAddRecExpr operand is not loop-invariant!"); 3451 #endif 3452 3453 if (Operands.back()->isZero()) { 3454 Operands.pop_back(); 3455 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3456 } 3457 3458 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3459 // use that information to infer NUW and NSW flags. However, computing a 3460 // BE count requires calling getAddRecExpr, so we may not yet have a 3461 // meaningful BE count at this point (and if we don't, we'd be stuck 3462 // with a SCEVCouldNotCompute as the cached BE count). 3463 3464 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3465 3466 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3467 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3468 const Loop *NestedLoop = NestedAR->getLoop(); 3469 if (L->contains(NestedLoop) 3470 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3471 : (!NestedLoop->contains(L) && 3472 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3473 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3474 NestedAR->op_end()); 3475 Operands[0] = NestedAR->getStart(); 3476 // AddRecs require their operands be loop-invariant with respect to their 3477 // loops. Don't perform this transformation if it would break this 3478 // requirement. 3479 bool AllInvariant = all_of( 3480 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3481 3482 if (AllInvariant) { 3483 // Create a recurrence for the outer loop with the same step size. 3484 // 3485 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3486 // inner recurrence has the same property. 3487 SCEV::NoWrapFlags OuterFlags = 3488 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3489 3490 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3491 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3492 return isLoopInvariant(Op, NestedLoop); 3493 }); 3494 3495 if (AllInvariant) { 3496 // Ok, both add recurrences are valid after the transformation. 3497 // 3498 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3499 // the outer recurrence has the same property. 3500 SCEV::NoWrapFlags InnerFlags = 3501 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3502 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3503 } 3504 } 3505 // Reset Operands to its original state. 3506 Operands[0] = NestedAR; 3507 } 3508 } 3509 3510 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3511 // already have one, otherwise create a new one. 3512 return getOrCreateAddRecExpr(Operands, L, Flags); 3513 } 3514 3515 const SCEV * 3516 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3517 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3518 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3519 // getSCEV(Base)->getType() has the same address space as Base->getType() 3520 // because SCEV::getType() preserves the address space. 3521 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3522 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3523 // instruction to its SCEV, because the Instruction may be guarded by control 3524 // flow and the no-overflow bits may not be valid for the expression in any 3525 // context. This can be fixed similarly to how these flags are handled for 3526 // adds. 3527 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3528 : SCEV::FlagAnyWrap; 3529 3530 const SCEV *TotalOffset = getZero(IntIdxTy); 3531 // The array size is unimportant. The first thing we do on CurTy is getting 3532 // its element type. 3533 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3534 for (const SCEV *IndexExpr : IndexExprs) { 3535 // Compute the (potentially symbolic) offset in bytes for this index. 3536 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3537 // For a struct, add the member offset. 3538 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3539 unsigned FieldNo = Index->getZExtValue(); 3540 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3541 3542 // Add the field offset to the running total offset. 3543 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3544 3545 // Update CurTy to the type of the field at Index. 3546 CurTy = STy->getTypeAtIndex(Index); 3547 } else { 3548 // Update CurTy to its element type. 3549 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3550 // For an array, add the element offset, explicitly scaled. 3551 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3552 // Getelementptr indices are signed. 3553 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3554 3555 // Multiply the index by the element size to compute the element offset. 3556 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3557 3558 // Add the element offset to the running total offset. 3559 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3560 } 3561 } 3562 3563 // Add the total offset from all the GEP indices to the base. 3564 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3565 } 3566 3567 std::tuple<SCEV *, FoldingSetNodeID, void *> 3568 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3569 ArrayRef<const SCEV *> Ops) { 3570 FoldingSetNodeID ID; 3571 void *IP = nullptr; 3572 ID.AddInteger(SCEVType); 3573 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3574 ID.AddPointer(Ops[i]); 3575 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3576 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3577 } 3578 3579 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3580 SmallVectorImpl<const SCEV *> &Ops) { 3581 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3582 if (Ops.size() == 1) return Ops[0]; 3583 #ifndef NDEBUG 3584 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3585 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3586 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3587 "Operand types don't match!"); 3588 #endif 3589 3590 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3591 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3592 3593 // Sort by complexity, this groups all similar expression types together. 3594 GroupByComplexity(Ops, &LI, DT); 3595 3596 // Check if we have created the same expression before. 3597 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3598 return S; 3599 } 3600 3601 // If there are any constants, fold them together. 3602 unsigned Idx = 0; 3603 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3604 ++Idx; 3605 assert(Idx < Ops.size()); 3606 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3607 if (Kind == scSMaxExpr) 3608 return APIntOps::smax(LHS, RHS); 3609 else if (Kind == scSMinExpr) 3610 return APIntOps::smin(LHS, RHS); 3611 else if (Kind == scUMaxExpr) 3612 return APIntOps::umax(LHS, RHS); 3613 else if (Kind == scUMinExpr) 3614 return APIntOps::umin(LHS, RHS); 3615 llvm_unreachable("Unknown SCEV min/max opcode"); 3616 }; 3617 3618 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3619 // We found two constants, fold them together! 3620 ConstantInt *Fold = ConstantInt::get( 3621 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3622 Ops[0] = getConstant(Fold); 3623 Ops.erase(Ops.begin()+1); // Erase the folded element 3624 if (Ops.size() == 1) return Ops[0]; 3625 LHSC = cast<SCEVConstant>(Ops[0]); 3626 } 3627 3628 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3629 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3630 3631 if (IsMax ? IsMinV : IsMaxV) { 3632 // If we are left with a constant minimum(/maximum)-int, strip it off. 3633 Ops.erase(Ops.begin()); 3634 --Idx; 3635 } else if (IsMax ? IsMaxV : IsMinV) { 3636 // If we have a max(/min) with a constant maximum(/minimum)-int, 3637 // it will always be the extremum. 3638 return LHSC; 3639 } 3640 3641 if (Ops.size() == 1) return Ops[0]; 3642 } 3643 3644 // Find the first operation of the same kind 3645 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3646 ++Idx; 3647 3648 // Check to see if one of the operands is of the same kind. If so, expand its 3649 // operands onto our operand list, and recurse to simplify. 3650 if (Idx < Ops.size()) { 3651 bool DeletedAny = false; 3652 while (Ops[Idx]->getSCEVType() == Kind) { 3653 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3654 Ops.erase(Ops.begin()+Idx); 3655 Ops.append(SMME->op_begin(), SMME->op_end()); 3656 DeletedAny = true; 3657 } 3658 3659 if (DeletedAny) 3660 return getMinMaxExpr(Kind, Ops); 3661 } 3662 3663 // Okay, check to see if the same value occurs in the operand list twice. If 3664 // so, delete one. Since we sorted the list, these values are required to 3665 // be adjacent. 3666 llvm::CmpInst::Predicate GEPred = 3667 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3668 llvm::CmpInst::Predicate LEPred = 3669 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3670 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3671 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3672 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3673 if (Ops[i] == Ops[i + 1] || 3674 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3675 // X op Y op Y --> X op Y 3676 // X op Y --> X, if we know X, Y are ordered appropriately 3677 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3678 --i; 3679 --e; 3680 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3681 Ops[i + 1])) { 3682 // X op Y --> Y, if we know X, Y are ordered appropriately 3683 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3684 --i; 3685 --e; 3686 } 3687 } 3688 3689 if (Ops.size() == 1) return Ops[0]; 3690 3691 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3692 3693 // Okay, it looks like we really DO need an expr. Check to see if we 3694 // already have one, otherwise create a new one. 3695 const SCEV *ExistingSCEV; 3696 FoldingSetNodeID ID; 3697 void *IP; 3698 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3699 if (ExistingSCEV) 3700 return ExistingSCEV; 3701 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3702 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3703 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3704 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3705 3706 UniqueSCEVs.InsertNode(S, IP); 3707 addToLoopUseLists(S); 3708 return S; 3709 } 3710 3711 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3712 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3713 return getSMaxExpr(Ops); 3714 } 3715 3716 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3717 return getMinMaxExpr(scSMaxExpr, Ops); 3718 } 3719 3720 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3721 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3722 return getUMaxExpr(Ops); 3723 } 3724 3725 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3726 return getMinMaxExpr(scUMaxExpr, Ops); 3727 } 3728 3729 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3730 const SCEV *RHS) { 3731 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3732 return getSMinExpr(Ops); 3733 } 3734 3735 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3736 return getMinMaxExpr(scSMinExpr, Ops); 3737 } 3738 3739 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3740 const SCEV *RHS) { 3741 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3742 return getUMinExpr(Ops); 3743 } 3744 3745 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3746 return getMinMaxExpr(scUMinExpr, Ops); 3747 } 3748 3749 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3750 // We can bypass creating a target-independent 3751 // constant expression and then folding it back into a ConstantInt. 3752 // This is just a compile-time optimization. 3753 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3754 } 3755 3756 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3757 StructType *STy, 3758 unsigned FieldNo) { 3759 // We can bypass creating a target-independent 3760 // constant expression and then folding it back into a ConstantInt. 3761 // This is just a compile-time optimization. 3762 return getConstant( 3763 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3764 } 3765 3766 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3767 // Don't attempt to do anything other than create a SCEVUnknown object 3768 // here. createSCEV only calls getUnknown after checking for all other 3769 // interesting possibilities, and any other code that calls getUnknown 3770 // is doing so in order to hide a value from SCEV canonicalization. 3771 3772 FoldingSetNodeID ID; 3773 ID.AddInteger(scUnknown); 3774 ID.AddPointer(V); 3775 void *IP = nullptr; 3776 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3777 assert(cast<SCEVUnknown>(S)->getValue() == V && 3778 "Stale SCEVUnknown in uniquing map!"); 3779 return S; 3780 } 3781 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3782 FirstUnknown); 3783 FirstUnknown = cast<SCEVUnknown>(S); 3784 UniqueSCEVs.InsertNode(S, IP); 3785 return S; 3786 } 3787 3788 //===----------------------------------------------------------------------===// 3789 // Basic SCEV Analysis and PHI Idiom Recognition Code 3790 // 3791 3792 /// Test if values of the given type are analyzable within the SCEV 3793 /// framework. This primarily includes integer types, and it can optionally 3794 /// include pointer types if the ScalarEvolution class has access to 3795 /// target-specific information. 3796 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3797 // Integers and pointers are always SCEVable. 3798 return Ty->isIntOrPtrTy(); 3799 } 3800 3801 /// Return the size in bits of the specified type, for which isSCEVable must 3802 /// return true. 3803 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3804 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3805 if (Ty->isPointerTy()) 3806 return getDataLayout().getIndexTypeSizeInBits(Ty); 3807 return getDataLayout().getTypeSizeInBits(Ty); 3808 } 3809 3810 /// Return a type with the same bitwidth as the given type and which represents 3811 /// how SCEV will treat the given type, for which isSCEVable must return 3812 /// true. For pointer types, this is the pointer index sized integer type. 3813 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3814 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3815 3816 if (Ty->isIntegerTy()) 3817 return Ty; 3818 3819 // The only other support type is pointer. 3820 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3821 return getDataLayout().getIndexType(Ty); 3822 } 3823 3824 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3825 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3826 } 3827 3828 const SCEV *ScalarEvolution::getCouldNotCompute() { 3829 return CouldNotCompute.get(); 3830 } 3831 3832 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3833 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3834 auto *SU = dyn_cast<SCEVUnknown>(S); 3835 return SU && SU->getValue() == nullptr; 3836 }); 3837 3838 return !ContainsNulls; 3839 } 3840 3841 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3842 HasRecMapType::iterator I = HasRecMap.find(S); 3843 if (I != HasRecMap.end()) 3844 return I->second; 3845 3846 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3847 HasRecMap.insert({S, FoundAddRec}); 3848 return FoundAddRec; 3849 } 3850 3851 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3852 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3853 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3854 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3855 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3856 if (!Add) 3857 return {S, nullptr}; 3858 3859 if (Add->getNumOperands() != 2) 3860 return {S, nullptr}; 3861 3862 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3863 if (!ConstOp) 3864 return {S, nullptr}; 3865 3866 return {Add->getOperand(1), ConstOp->getValue()}; 3867 } 3868 3869 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3870 /// by the value and offset from any ValueOffsetPair in the set. 3871 SetVector<ScalarEvolution::ValueOffsetPair> * 3872 ScalarEvolution::getSCEVValues(const SCEV *S) { 3873 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3874 if (SI == ExprValueMap.end()) 3875 return nullptr; 3876 #ifndef NDEBUG 3877 if (VerifySCEVMap) { 3878 // Check there is no dangling Value in the set returned. 3879 for (const auto &VE : SI->second) 3880 assert(ValueExprMap.count(VE.first)); 3881 } 3882 #endif 3883 return &SI->second; 3884 } 3885 3886 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3887 /// cannot be used separately. eraseValueFromMap should be used to remove 3888 /// V from ValueExprMap and ExprValueMap at the same time. 3889 void ScalarEvolution::eraseValueFromMap(Value *V) { 3890 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3891 if (I != ValueExprMap.end()) { 3892 const SCEV *S = I->second; 3893 // Remove {V, 0} from the set of ExprValueMap[S] 3894 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3895 SV->remove({V, nullptr}); 3896 3897 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3898 const SCEV *Stripped; 3899 ConstantInt *Offset; 3900 std::tie(Stripped, Offset) = splitAddExpr(S); 3901 if (Offset != nullptr) { 3902 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3903 SV->remove({V, Offset}); 3904 } 3905 ValueExprMap.erase(V); 3906 } 3907 } 3908 3909 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3910 /// TODO: In reality it is better to check the poison recursively 3911 /// but this is better than nothing. 3912 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3913 if (auto *I = dyn_cast<Instruction>(V)) { 3914 if (isa<OverflowingBinaryOperator>(I)) { 3915 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3916 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3917 return true; 3918 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3919 return true; 3920 } 3921 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3922 return true; 3923 } 3924 return false; 3925 } 3926 3927 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3928 /// create a new one. 3929 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3930 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3931 3932 const SCEV *S = getExistingSCEV(V); 3933 if (S == nullptr) { 3934 S = createSCEV(V); 3935 // During PHI resolution, it is possible to create two SCEVs for the same 3936 // V, so it is needed to double check whether V->S is inserted into 3937 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3938 std::pair<ValueExprMapType::iterator, bool> Pair = 3939 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3940 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3941 ExprValueMap[S].insert({V, nullptr}); 3942 3943 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3944 // ExprValueMap. 3945 const SCEV *Stripped = S; 3946 ConstantInt *Offset = nullptr; 3947 std::tie(Stripped, Offset) = splitAddExpr(S); 3948 // If stripped is SCEVUnknown, don't bother to save 3949 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3950 // increase the complexity of the expansion code. 3951 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3952 // because it may generate add/sub instead of GEP in SCEV expansion. 3953 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3954 !isa<GetElementPtrInst>(V)) 3955 ExprValueMap[Stripped].insert({V, Offset}); 3956 } 3957 } 3958 return S; 3959 } 3960 3961 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3962 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3963 3964 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3965 if (I != ValueExprMap.end()) { 3966 const SCEV *S = I->second; 3967 if (checkValidity(S)) 3968 return S; 3969 eraseValueFromMap(V); 3970 forgetMemoizedResults(S); 3971 } 3972 return nullptr; 3973 } 3974 3975 /// Return a SCEV corresponding to -V = -1*V 3976 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3977 SCEV::NoWrapFlags Flags) { 3978 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3979 return getConstant( 3980 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3981 3982 Type *Ty = V->getType(); 3983 Ty = getEffectiveSCEVType(Ty); 3984 return getMulExpr( 3985 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3986 } 3987 3988 /// If Expr computes ~A, return A else return nullptr 3989 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3990 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3991 if (!Add || Add->getNumOperands() != 2 || 3992 !Add->getOperand(0)->isAllOnesValue()) 3993 return nullptr; 3994 3995 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3996 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3997 !AddRHS->getOperand(0)->isAllOnesValue()) 3998 return nullptr; 3999 4000 return AddRHS->getOperand(1); 4001 } 4002 4003 /// Return a SCEV corresponding to ~V = -1-V 4004 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4005 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4006 return getConstant( 4007 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4008 4009 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4010 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4011 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4012 SmallVector<const SCEV *, 2> MatchedOperands; 4013 for (const SCEV *Operand : MME->operands()) { 4014 const SCEV *Matched = MatchNotExpr(Operand); 4015 if (!Matched) 4016 return (const SCEV *)nullptr; 4017 MatchedOperands.push_back(Matched); 4018 } 4019 return getMinMaxExpr( 4020 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 4021 MatchedOperands); 4022 }; 4023 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4024 return Replaced; 4025 } 4026 4027 Type *Ty = V->getType(); 4028 Ty = getEffectiveSCEVType(Ty); 4029 const SCEV *AllOnes = 4030 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4031 return getMinusSCEV(AllOnes, V); 4032 } 4033 4034 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4035 SCEV::NoWrapFlags Flags, 4036 unsigned Depth) { 4037 // Fast path: X - X --> 0. 4038 if (LHS == RHS) 4039 return getZero(LHS->getType()); 4040 4041 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4042 // makes it so that we cannot make much use of NUW. 4043 auto AddFlags = SCEV::FlagAnyWrap; 4044 const bool RHSIsNotMinSigned = 4045 !getSignedRangeMin(RHS).isMinSignedValue(); 4046 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4047 // Let M be the minimum representable signed value. Then (-1)*RHS 4048 // signed-wraps if and only if RHS is M. That can happen even for 4049 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4050 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4051 // (-1)*RHS, we need to prove that RHS != M. 4052 // 4053 // If LHS is non-negative and we know that LHS - RHS does not 4054 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4055 // either by proving that RHS > M or that LHS >= 0. 4056 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4057 AddFlags = SCEV::FlagNSW; 4058 } 4059 } 4060 4061 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4062 // RHS is NSW and LHS >= 0. 4063 // 4064 // The difficulty here is that the NSW flag may have been proven 4065 // relative to a loop that is to be found in a recurrence in LHS and 4066 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4067 // larger scope than intended. 4068 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4069 4070 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4071 } 4072 4073 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4074 unsigned Depth) { 4075 Type *SrcTy = V->getType(); 4076 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4077 "Cannot truncate or zero extend with non-integer arguments!"); 4078 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4079 return V; // No conversion 4080 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4081 return getTruncateExpr(V, Ty, Depth); 4082 return getZeroExtendExpr(V, Ty, Depth); 4083 } 4084 4085 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4086 unsigned Depth) { 4087 Type *SrcTy = V->getType(); 4088 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4089 "Cannot truncate or zero extend with non-integer arguments!"); 4090 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4091 return V; // No conversion 4092 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4093 return getTruncateExpr(V, Ty, Depth); 4094 return getSignExtendExpr(V, Ty, Depth); 4095 } 4096 4097 const SCEV * 4098 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4099 Type *SrcTy = V->getType(); 4100 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4101 "Cannot noop or zero extend with non-integer arguments!"); 4102 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4103 "getNoopOrZeroExtend cannot truncate!"); 4104 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4105 return V; // No conversion 4106 return getZeroExtendExpr(V, Ty); 4107 } 4108 4109 const SCEV * 4110 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4111 Type *SrcTy = V->getType(); 4112 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4113 "Cannot noop or sign extend with non-integer arguments!"); 4114 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4115 "getNoopOrSignExtend cannot truncate!"); 4116 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4117 return V; // No conversion 4118 return getSignExtendExpr(V, Ty); 4119 } 4120 4121 const SCEV * 4122 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4123 Type *SrcTy = V->getType(); 4124 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4125 "Cannot noop or any extend with non-integer arguments!"); 4126 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4127 "getNoopOrAnyExtend cannot truncate!"); 4128 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4129 return V; // No conversion 4130 return getAnyExtendExpr(V, Ty); 4131 } 4132 4133 const SCEV * 4134 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4135 Type *SrcTy = V->getType(); 4136 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4137 "Cannot truncate or noop with non-integer arguments!"); 4138 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4139 "getTruncateOrNoop cannot extend!"); 4140 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4141 return V; // No conversion 4142 return getTruncateExpr(V, Ty); 4143 } 4144 4145 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4146 const SCEV *RHS) { 4147 const SCEV *PromotedLHS = LHS; 4148 const SCEV *PromotedRHS = RHS; 4149 4150 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4151 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4152 else 4153 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4154 4155 return getUMaxExpr(PromotedLHS, PromotedRHS); 4156 } 4157 4158 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4159 const SCEV *RHS) { 4160 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4161 return getUMinFromMismatchedTypes(Ops); 4162 } 4163 4164 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4165 SmallVectorImpl<const SCEV *> &Ops) { 4166 assert(!Ops.empty() && "At least one operand must be!"); 4167 // Trivial case. 4168 if (Ops.size() == 1) 4169 return Ops[0]; 4170 4171 // Find the max type first. 4172 Type *MaxType = nullptr; 4173 for (auto *S : Ops) 4174 if (MaxType) 4175 MaxType = getWiderType(MaxType, S->getType()); 4176 else 4177 MaxType = S->getType(); 4178 4179 // Extend all ops to max type. 4180 SmallVector<const SCEV *, 2> PromotedOps; 4181 for (auto *S : Ops) 4182 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4183 4184 // Generate umin. 4185 return getUMinExpr(PromotedOps); 4186 } 4187 4188 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4189 // A pointer operand may evaluate to a nonpointer expression, such as null. 4190 if (!V->getType()->isPointerTy()) 4191 return V; 4192 4193 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4194 return getPointerBase(Cast->getOperand()); 4195 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4196 const SCEV *PtrOp = nullptr; 4197 for (const SCEV *NAryOp : NAry->operands()) { 4198 if (NAryOp->getType()->isPointerTy()) { 4199 // Cannot find the base of an expression with multiple pointer operands. 4200 if (PtrOp) 4201 return V; 4202 PtrOp = NAryOp; 4203 } 4204 } 4205 if (!PtrOp) 4206 return V; 4207 return getPointerBase(PtrOp); 4208 } 4209 return V; 4210 } 4211 4212 /// Push users of the given Instruction onto the given Worklist. 4213 static void 4214 PushDefUseChildren(Instruction *I, 4215 SmallVectorImpl<Instruction *> &Worklist) { 4216 // Push the def-use children onto the Worklist stack. 4217 for (User *U : I->users()) 4218 Worklist.push_back(cast<Instruction>(U)); 4219 } 4220 4221 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4222 SmallVector<Instruction *, 16> Worklist; 4223 PushDefUseChildren(PN, Worklist); 4224 4225 SmallPtrSet<Instruction *, 8> Visited; 4226 Visited.insert(PN); 4227 while (!Worklist.empty()) { 4228 Instruction *I = Worklist.pop_back_val(); 4229 if (!Visited.insert(I).second) 4230 continue; 4231 4232 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4233 if (It != ValueExprMap.end()) { 4234 const SCEV *Old = It->second; 4235 4236 // Short-circuit the def-use traversal if the symbolic name 4237 // ceases to appear in expressions. 4238 if (Old != SymName && !hasOperand(Old, SymName)) 4239 continue; 4240 4241 // SCEVUnknown for a PHI either means that it has an unrecognized 4242 // structure, it's a PHI that's in the progress of being computed 4243 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4244 // additional loop trip count information isn't going to change anything. 4245 // In the second case, createNodeForPHI will perform the necessary 4246 // updates on its own when it gets to that point. In the third, we do 4247 // want to forget the SCEVUnknown. 4248 if (!isa<PHINode>(I) || 4249 !isa<SCEVUnknown>(Old) || 4250 (I != PN && Old == SymName)) { 4251 eraseValueFromMap(It->first); 4252 forgetMemoizedResults(Old); 4253 } 4254 } 4255 4256 PushDefUseChildren(I, Worklist); 4257 } 4258 } 4259 4260 namespace { 4261 4262 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4263 /// expression in case its Loop is L. If it is not L then 4264 /// if IgnoreOtherLoops is true then use AddRec itself 4265 /// otherwise rewrite cannot be done. 4266 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4267 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4268 public: 4269 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4270 bool IgnoreOtherLoops = true) { 4271 SCEVInitRewriter Rewriter(L, SE); 4272 const SCEV *Result = Rewriter.visit(S); 4273 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4274 return SE.getCouldNotCompute(); 4275 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4276 ? SE.getCouldNotCompute() 4277 : Result; 4278 } 4279 4280 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4281 if (!SE.isLoopInvariant(Expr, L)) 4282 SeenLoopVariantSCEVUnknown = true; 4283 return Expr; 4284 } 4285 4286 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4287 // Only re-write AddRecExprs for this loop. 4288 if (Expr->getLoop() == L) 4289 return Expr->getStart(); 4290 SeenOtherLoops = true; 4291 return Expr; 4292 } 4293 4294 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4295 4296 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4297 4298 private: 4299 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4300 : SCEVRewriteVisitor(SE), L(L) {} 4301 4302 const Loop *L; 4303 bool SeenLoopVariantSCEVUnknown = false; 4304 bool SeenOtherLoops = false; 4305 }; 4306 4307 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4308 /// increment expression in case its Loop is L. If it is not L then 4309 /// use AddRec itself. 4310 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4311 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4312 public: 4313 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4314 SCEVPostIncRewriter Rewriter(L, SE); 4315 const SCEV *Result = Rewriter.visit(S); 4316 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4317 ? SE.getCouldNotCompute() 4318 : Result; 4319 } 4320 4321 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4322 if (!SE.isLoopInvariant(Expr, L)) 4323 SeenLoopVariantSCEVUnknown = true; 4324 return Expr; 4325 } 4326 4327 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4328 // Only re-write AddRecExprs for this loop. 4329 if (Expr->getLoop() == L) 4330 return Expr->getPostIncExpr(SE); 4331 SeenOtherLoops = true; 4332 return Expr; 4333 } 4334 4335 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4336 4337 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4338 4339 private: 4340 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4341 : SCEVRewriteVisitor(SE), L(L) {} 4342 4343 const Loop *L; 4344 bool SeenLoopVariantSCEVUnknown = false; 4345 bool SeenOtherLoops = false; 4346 }; 4347 4348 /// This class evaluates the compare condition by matching it against the 4349 /// condition of loop latch. If there is a match we assume a true value 4350 /// for the condition while building SCEV nodes. 4351 class SCEVBackedgeConditionFolder 4352 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4353 public: 4354 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4355 ScalarEvolution &SE) { 4356 bool IsPosBECond = false; 4357 Value *BECond = nullptr; 4358 if (BasicBlock *Latch = L->getLoopLatch()) { 4359 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4360 if (BI && BI->isConditional()) { 4361 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4362 "Both outgoing branches should not target same header!"); 4363 BECond = BI->getCondition(); 4364 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4365 } else { 4366 return S; 4367 } 4368 } 4369 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4370 return Rewriter.visit(S); 4371 } 4372 4373 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4374 const SCEV *Result = Expr; 4375 bool InvariantF = SE.isLoopInvariant(Expr, L); 4376 4377 if (!InvariantF) { 4378 Instruction *I = cast<Instruction>(Expr->getValue()); 4379 switch (I->getOpcode()) { 4380 case Instruction::Select: { 4381 SelectInst *SI = cast<SelectInst>(I); 4382 Optional<const SCEV *> Res = 4383 compareWithBackedgeCondition(SI->getCondition()); 4384 if (Res.hasValue()) { 4385 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4386 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4387 } 4388 break; 4389 } 4390 default: { 4391 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4392 if (Res.hasValue()) 4393 Result = Res.getValue(); 4394 break; 4395 } 4396 } 4397 } 4398 return Result; 4399 } 4400 4401 private: 4402 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4403 bool IsPosBECond, ScalarEvolution &SE) 4404 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4405 IsPositiveBECond(IsPosBECond) {} 4406 4407 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4408 4409 const Loop *L; 4410 /// Loop back condition. 4411 Value *BackedgeCond = nullptr; 4412 /// Set to true if loop back is on positive branch condition. 4413 bool IsPositiveBECond; 4414 }; 4415 4416 Optional<const SCEV *> 4417 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4418 4419 // If value matches the backedge condition for loop latch, 4420 // then return a constant evolution node based on loopback 4421 // branch taken. 4422 if (BackedgeCond == IC) 4423 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4424 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4425 return None; 4426 } 4427 4428 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4429 public: 4430 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4431 ScalarEvolution &SE) { 4432 SCEVShiftRewriter Rewriter(L, SE); 4433 const SCEV *Result = Rewriter.visit(S); 4434 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4435 } 4436 4437 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4438 // Only allow AddRecExprs for this loop. 4439 if (!SE.isLoopInvariant(Expr, L)) 4440 Valid = false; 4441 return Expr; 4442 } 4443 4444 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4445 if (Expr->getLoop() == L && Expr->isAffine()) 4446 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4447 Valid = false; 4448 return Expr; 4449 } 4450 4451 bool isValid() { return Valid; } 4452 4453 private: 4454 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4455 : SCEVRewriteVisitor(SE), L(L) {} 4456 4457 const Loop *L; 4458 bool Valid = true; 4459 }; 4460 4461 } // end anonymous namespace 4462 4463 SCEV::NoWrapFlags 4464 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4465 if (!AR->isAffine()) 4466 return SCEV::FlagAnyWrap; 4467 4468 using OBO = OverflowingBinaryOperator; 4469 4470 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4471 4472 if (!AR->hasNoSignedWrap()) { 4473 ConstantRange AddRecRange = getSignedRange(AR); 4474 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4475 4476 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4477 Instruction::Add, IncRange, OBO::NoSignedWrap); 4478 if (NSWRegion.contains(AddRecRange)) 4479 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4480 } 4481 4482 if (!AR->hasNoUnsignedWrap()) { 4483 ConstantRange AddRecRange = getUnsignedRange(AR); 4484 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4485 4486 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4487 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4488 if (NUWRegion.contains(AddRecRange)) 4489 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4490 } 4491 4492 return Result; 4493 } 4494 4495 namespace { 4496 4497 /// Represents an abstract binary operation. This may exist as a 4498 /// normal instruction or constant expression, or may have been 4499 /// derived from an expression tree. 4500 struct BinaryOp { 4501 unsigned Opcode; 4502 Value *LHS; 4503 Value *RHS; 4504 bool IsNSW = false; 4505 bool IsNUW = false; 4506 4507 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4508 /// constant expression. 4509 Operator *Op = nullptr; 4510 4511 explicit BinaryOp(Operator *Op) 4512 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4513 Op(Op) { 4514 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4515 IsNSW = OBO->hasNoSignedWrap(); 4516 IsNUW = OBO->hasNoUnsignedWrap(); 4517 } 4518 } 4519 4520 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4521 bool IsNUW = false) 4522 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4523 }; 4524 4525 } // end anonymous namespace 4526 4527 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4528 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4529 auto *Op = dyn_cast<Operator>(V); 4530 if (!Op) 4531 return None; 4532 4533 // Implementation detail: all the cleverness here should happen without 4534 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4535 // SCEV expressions when possible, and we should not break that. 4536 4537 switch (Op->getOpcode()) { 4538 case Instruction::Add: 4539 case Instruction::Sub: 4540 case Instruction::Mul: 4541 case Instruction::UDiv: 4542 case Instruction::URem: 4543 case Instruction::And: 4544 case Instruction::Or: 4545 case Instruction::AShr: 4546 case Instruction::Shl: 4547 return BinaryOp(Op); 4548 4549 case Instruction::Xor: 4550 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4551 // If the RHS of the xor is a signmask, then this is just an add. 4552 // Instcombine turns add of signmask into xor as a strength reduction step. 4553 if (RHSC->getValue().isSignMask()) 4554 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4555 return BinaryOp(Op); 4556 4557 case Instruction::LShr: 4558 // Turn logical shift right of a constant into a unsigned divide. 4559 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4560 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4561 4562 // If the shift count is not less than the bitwidth, the result of 4563 // the shift is undefined. Don't try to analyze it, because the 4564 // resolution chosen here may differ from the resolution chosen in 4565 // other parts of the compiler. 4566 if (SA->getValue().ult(BitWidth)) { 4567 Constant *X = 4568 ConstantInt::get(SA->getContext(), 4569 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4570 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4571 } 4572 } 4573 return BinaryOp(Op); 4574 4575 case Instruction::ExtractValue: { 4576 auto *EVI = cast<ExtractValueInst>(Op); 4577 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4578 break; 4579 4580 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4581 if (!WO) 4582 break; 4583 4584 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4585 bool Signed = WO->isSigned(); 4586 // TODO: Should add nuw/nsw flags for mul as well. 4587 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4588 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4589 4590 // Now that we know that all uses of the arithmetic-result component of 4591 // CI are guarded by the overflow check, we can go ahead and pretend 4592 // that the arithmetic is non-overflowing. 4593 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4594 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4595 } 4596 4597 default: 4598 break; 4599 } 4600 4601 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4602 // semantics as a Sub, return a binary sub expression. 4603 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4604 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4605 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4606 4607 return None; 4608 } 4609 4610 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4611 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4612 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4613 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4614 /// follows one of the following patterns: 4615 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4616 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4617 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4618 /// we return the type of the truncation operation, and indicate whether the 4619 /// truncated type should be treated as signed/unsigned by setting 4620 /// \p Signed to true/false, respectively. 4621 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4622 bool &Signed, ScalarEvolution &SE) { 4623 // The case where Op == SymbolicPHI (that is, with no type conversions on 4624 // the way) is handled by the regular add recurrence creating logic and 4625 // would have already been triggered in createAddRecForPHI. Reaching it here 4626 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4627 // because one of the other operands of the SCEVAddExpr updating this PHI is 4628 // not invariant). 4629 // 4630 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4631 // this case predicates that allow us to prove that Op == SymbolicPHI will 4632 // be added. 4633 if (Op == SymbolicPHI) 4634 return nullptr; 4635 4636 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4637 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4638 if (SourceBits != NewBits) 4639 return nullptr; 4640 4641 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4642 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4643 if (!SExt && !ZExt) 4644 return nullptr; 4645 const SCEVTruncateExpr *Trunc = 4646 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4647 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4648 if (!Trunc) 4649 return nullptr; 4650 const SCEV *X = Trunc->getOperand(); 4651 if (X != SymbolicPHI) 4652 return nullptr; 4653 Signed = SExt != nullptr; 4654 return Trunc->getType(); 4655 } 4656 4657 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4658 if (!PN->getType()->isIntegerTy()) 4659 return nullptr; 4660 const Loop *L = LI.getLoopFor(PN->getParent()); 4661 if (!L || L->getHeader() != PN->getParent()) 4662 return nullptr; 4663 return L; 4664 } 4665 4666 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4667 // computation that updates the phi follows the following pattern: 4668 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4669 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4670 // If so, try to see if it can be rewritten as an AddRecExpr under some 4671 // Predicates. If successful, return them as a pair. Also cache the results 4672 // of the analysis. 4673 // 4674 // Example usage scenario: 4675 // Say the Rewriter is called for the following SCEV: 4676 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4677 // where: 4678 // %X = phi i64 (%Start, %BEValue) 4679 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4680 // and call this function with %SymbolicPHI = %X. 4681 // 4682 // The analysis will find that the value coming around the backedge has 4683 // the following SCEV: 4684 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4685 // Upon concluding that this matches the desired pattern, the function 4686 // will return the pair {NewAddRec, SmallPredsVec} where: 4687 // NewAddRec = {%Start,+,%Step} 4688 // SmallPredsVec = {P1, P2, P3} as follows: 4689 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4690 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4691 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4692 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4693 // under the predicates {P1,P2,P3}. 4694 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4695 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4696 // 4697 // TODO's: 4698 // 4699 // 1) Extend the Induction descriptor to also support inductions that involve 4700 // casts: When needed (namely, when we are called in the context of the 4701 // vectorizer induction analysis), a Set of cast instructions will be 4702 // populated by this method, and provided back to isInductionPHI. This is 4703 // needed to allow the vectorizer to properly record them to be ignored by 4704 // the cost model and to avoid vectorizing them (otherwise these casts, 4705 // which are redundant under the runtime overflow checks, will be 4706 // vectorized, which can be costly). 4707 // 4708 // 2) Support additional induction/PHISCEV patterns: We also want to support 4709 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4710 // after the induction update operation (the induction increment): 4711 // 4712 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4713 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4714 // 4715 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4716 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4717 // 4718 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4719 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4720 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4721 SmallVector<const SCEVPredicate *, 3> Predicates; 4722 4723 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4724 // return an AddRec expression under some predicate. 4725 4726 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4727 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4728 assert(L && "Expecting an integer loop header phi"); 4729 4730 // The loop may have multiple entrances or multiple exits; we can analyze 4731 // this phi as an addrec if it has a unique entry value and a unique 4732 // backedge value. 4733 Value *BEValueV = nullptr, *StartValueV = nullptr; 4734 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4735 Value *V = PN->getIncomingValue(i); 4736 if (L->contains(PN->getIncomingBlock(i))) { 4737 if (!BEValueV) { 4738 BEValueV = V; 4739 } else if (BEValueV != V) { 4740 BEValueV = nullptr; 4741 break; 4742 } 4743 } else if (!StartValueV) { 4744 StartValueV = V; 4745 } else if (StartValueV != V) { 4746 StartValueV = nullptr; 4747 break; 4748 } 4749 } 4750 if (!BEValueV || !StartValueV) 4751 return None; 4752 4753 const SCEV *BEValue = getSCEV(BEValueV); 4754 4755 // If the value coming around the backedge is an add with the symbolic 4756 // value we just inserted, possibly with casts that we can ignore under 4757 // an appropriate runtime guard, then we found a simple induction variable! 4758 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4759 if (!Add) 4760 return None; 4761 4762 // If there is a single occurrence of the symbolic value, possibly 4763 // casted, replace it with a recurrence. 4764 unsigned FoundIndex = Add->getNumOperands(); 4765 Type *TruncTy = nullptr; 4766 bool Signed; 4767 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4768 if ((TruncTy = 4769 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4770 if (FoundIndex == e) { 4771 FoundIndex = i; 4772 break; 4773 } 4774 4775 if (FoundIndex == Add->getNumOperands()) 4776 return None; 4777 4778 // Create an add with everything but the specified operand. 4779 SmallVector<const SCEV *, 8> Ops; 4780 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4781 if (i != FoundIndex) 4782 Ops.push_back(Add->getOperand(i)); 4783 const SCEV *Accum = getAddExpr(Ops); 4784 4785 // The runtime checks will not be valid if the step amount is 4786 // varying inside the loop. 4787 if (!isLoopInvariant(Accum, L)) 4788 return None; 4789 4790 // *** Part2: Create the predicates 4791 4792 // Analysis was successful: we have a phi-with-cast pattern for which we 4793 // can return an AddRec expression under the following predicates: 4794 // 4795 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4796 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4797 // P2: An Equal predicate that guarantees that 4798 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4799 // P3: An Equal predicate that guarantees that 4800 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4801 // 4802 // As we next prove, the above predicates guarantee that: 4803 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4804 // 4805 // 4806 // More formally, we want to prove that: 4807 // Expr(i+1) = Start + (i+1) * Accum 4808 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4809 // 4810 // Given that: 4811 // 1) Expr(0) = Start 4812 // 2) Expr(1) = Start + Accum 4813 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4814 // 3) Induction hypothesis (step i): 4815 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4816 // 4817 // Proof: 4818 // Expr(i+1) = 4819 // = Start + (i+1)*Accum 4820 // = (Start + i*Accum) + Accum 4821 // = Expr(i) + Accum 4822 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4823 // :: from step i 4824 // 4825 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4826 // 4827 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4828 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4829 // + Accum :: from P3 4830 // 4831 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4832 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4833 // 4834 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4835 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4836 // 4837 // By induction, the same applies to all iterations 1<=i<n: 4838 // 4839 4840 // Create a truncated addrec for which we will add a no overflow check (P1). 4841 const SCEV *StartVal = getSCEV(StartValueV); 4842 const SCEV *PHISCEV = 4843 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4844 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4845 4846 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4847 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4848 // will be constant. 4849 // 4850 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4851 // add P1. 4852 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4853 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4854 Signed ? SCEVWrapPredicate::IncrementNSSW 4855 : SCEVWrapPredicate::IncrementNUSW; 4856 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4857 Predicates.push_back(AddRecPred); 4858 } 4859 4860 // Create the Equal Predicates P2,P3: 4861 4862 // It is possible that the predicates P2 and/or P3 are computable at 4863 // compile time due to StartVal and/or Accum being constants. 4864 // If either one is, then we can check that now and escape if either P2 4865 // or P3 is false. 4866 4867 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4868 // for each of StartVal and Accum 4869 auto getExtendedExpr = [&](const SCEV *Expr, 4870 bool CreateSignExtend) -> const SCEV * { 4871 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4872 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4873 const SCEV *ExtendedExpr = 4874 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4875 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4876 return ExtendedExpr; 4877 }; 4878 4879 // Given: 4880 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4881 // = getExtendedExpr(Expr) 4882 // Determine whether the predicate P: Expr == ExtendedExpr 4883 // is known to be false at compile time 4884 auto PredIsKnownFalse = [&](const SCEV *Expr, 4885 const SCEV *ExtendedExpr) -> bool { 4886 return Expr != ExtendedExpr && 4887 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4888 }; 4889 4890 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4891 if (PredIsKnownFalse(StartVal, StartExtended)) { 4892 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4893 return None; 4894 } 4895 4896 // The Step is always Signed (because the overflow checks are either 4897 // NSSW or NUSW) 4898 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4899 if (PredIsKnownFalse(Accum, AccumExtended)) { 4900 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4901 return None; 4902 } 4903 4904 auto AppendPredicate = [&](const SCEV *Expr, 4905 const SCEV *ExtendedExpr) -> void { 4906 if (Expr != ExtendedExpr && 4907 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4908 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4909 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4910 Predicates.push_back(Pred); 4911 } 4912 }; 4913 4914 AppendPredicate(StartVal, StartExtended); 4915 AppendPredicate(Accum, AccumExtended); 4916 4917 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4918 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4919 // into NewAR if it will also add the runtime overflow checks specified in 4920 // Predicates. 4921 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4922 4923 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4924 std::make_pair(NewAR, Predicates); 4925 // Remember the result of the analysis for this SCEV at this locayyytion. 4926 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4927 return PredRewrite; 4928 } 4929 4930 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4931 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4932 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4933 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4934 if (!L) 4935 return None; 4936 4937 // Check to see if we already analyzed this PHI. 4938 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4939 if (I != PredicatedSCEVRewrites.end()) { 4940 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4941 I->second; 4942 // Analysis was done before and failed to create an AddRec: 4943 if (Rewrite.first == SymbolicPHI) 4944 return None; 4945 // Analysis was done before and succeeded to create an AddRec under 4946 // a predicate: 4947 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4948 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4949 return Rewrite; 4950 } 4951 4952 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4953 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4954 4955 // Record in the cache that the analysis failed 4956 if (!Rewrite) { 4957 SmallVector<const SCEVPredicate *, 3> Predicates; 4958 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4959 return None; 4960 } 4961 4962 return Rewrite; 4963 } 4964 4965 // FIXME: This utility is currently required because the Rewriter currently 4966 // does not rewrite this expression: 4967 // {0, +, (sext ix (trunc iy to ix) to iy)} 4968 // into {0, +, %step}, 4969 // even when the following Equal predicate exists: 4970 // "%step == (sext ix (trunc iy to ix) to iy)". 4971 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4972 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4973 if (AR1 == AR2) 4974 return true; 4975 4976 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4977 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4978 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4979 return false; 4980 return true; 4981 }; 4982 4983 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4984 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4985 return false; 4986 return true; 4987 } 4988 4989 /// A helper function for createAddRecFromPHI to handle simple cases. 4990 /// 4991 /// This function tries to find an AddRec expression for the simplest (yet most 4992 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4993 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4994 /// technique for finding the AddRec expression. 4995 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4996 Value *BEValueV, 4997 Value *StartValueV) { 4998 const Loop *L = LI.getLoopFor(PN->getParent()); 4999 assert(L && L->getHeader() == PN->getParent()); 5000 assert(BEValueV && StartValueV); 5001 5002 auto BO = MatchBinaryOp(BEValueV, DT); 5003 if (!BO) 5004 return nullptr; 5005 5006 if (BO->Opcode != Instruction::Add) 5007 return nullptr; 5008 5009 const SCEV *Accum = nullptr; 5010 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5011 Accum = getSCEV(BO->RHS); 5012 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5013 Accum = getSCEV(BO->LHS); 5014 5015 if (!Accum) 5016 return nullptr; 5017 5018 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5019 if (BO->IsNUW) 5020 Flags = setFlags(Flags, SCEV::FlagNUW); 5021 if (BO->IsNSW) 5022 Flags = setFlags(Flags, SCEV::FlagNSW); 5023 5024 const SCEV *StartVal = getSCEV(StartValueV); 5025 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5026 5027 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5028 5029 // We can add Flags to the post-inc expression only if we 5030 // know that it is *undefined behavior* for BEValueV to 5031 // overflow. 5032 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5033 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5034 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5035 5036 return PHISCEV; 5037 } 5038 5039 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5040 const Loop *L = LI.getLoopFor(PN->getParent()); 5041 if (!L || L->getHeader() != PN->getParent()) 5042 return nullptr; 5043 5044 // The loop may have multiple entrances or multiple exits; we can analyze 5045 // this phi as an addrec if it has a unique entry value and a unique 5046 // backedge value. 5047 Value *BEValueV = nullptr, *StartValueV = nullptr; 5048 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5049 Value *V = PN->getIncomingValue(i); 5050 if (L->contains(PN->getIncomingBlock(i))) { 5051 if (!BEValueV) { 5052 BEValueV = V; 5053 } else if (BEValueV != V) { 5054 BEValueV = nullptr; 5055 break; 5056 } 5057 } else if (!StartValueV) { 5058 StartValueV = V; 5059 } else if (StartValueV != V) { 5060 StartValueV = nullptr; 5061 break; 5062 } 5063 } 5064 if (!BEValueV || !StartValueV) 5065 return nullptr; 5066 5067 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5068 "PHI node already processed?"); 5069 5070 // First, try to find AddRec expression without creating a fictituos symbolic 5071 // value for PN. 5072 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5073 return S; 5074 5075 // Handle PHI node value symbolically. 5076 const SCEV *SymbolicName = getUnknown(PN); 5077 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5078 5079 // Using this symbolic name for the PHI, analyze the value coming around 5080 // the back-edge. 5081 const SCEV *BEValue = getSCEV(BEValueV); 5082 5083 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5084 // has a special value for the first iteration of the loop. 5085 5086 // If the value coming around the backedge is an add with the symbolic 5087 // value we just inserted, then we found a simple induction variable! 5088 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5089 // If there is a single occurrence of the symbolic value, replace it 5090 // with a recurrence. 5091 unsigned FoundIndex = Add->getNumOperands(); 5092 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5093 if (Add->getOperand(i) == SymbolicName) 5094 if (FoundIndex == e) { 5095 FoundIndex = i; 5096 break; 5097 } 5098 5099 if (FoundIndex != Add->getNumOperands()) { 5100 // Create an add with everything but the specified operand. 5101 SmallVector<const SCEV *, 8> Ops; 5102 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5103 if (i != FoundIndex) 5104 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5105 L, *this)); 5106 const SCEV *Accum = getAddExpr(Ops); 5107 5108 // This is not a valid addrec if the step amount is varying each 5109 // loop iteration, but is not itself an addrec in this loop. 5110 if (isLoopInvariant(Accum, L) || 5111 (isa<SCEVAddRecExpr>(Accum) && 5112 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5113 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5114 5115 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5116 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5117 if (BO->IsNUW) 5118 Flags = setFlags(Flags, SCEV::FlagNUW); 5119 if (BO->IsNSW) 5120 Flags = setFlags(Flags, SCEV::FlagNSW); 5121 } 5122 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5123 // If the increment is an inbounds GEP, then we know the address 5124 // space cannot be wrapped around. We cannot make any guarantee 5125 // about signed or unsigned overflow because pointers are 5126 // unsigned but we may have a negative index from the base 5127 // pointer. We can guarantee that no unsigned wrap occurs if the 5128 // indices form a positive value. 5129 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5130 Flags = setFlags(Flags, SCEV::FlagNW); 5131 5132 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5133 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5134 Flags = setFlags(Flags, SCEV::FlagNUW); 5135 } 5136 5137 // We cannot transfer nuw and nsw flags from subtraction 5138 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5139 // for instance. 5140 } 5141 5142 const SCEV *StartVal = getSCEV(StartValueV); 5143 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5144 5145 // Okay, for the entire analysis of this edge we assumed the PHI 5146 // to be symbolic. We now need to go back and purge all of the 5147 // entries for the scalars that use the symbolic expression. 5148 forgetSymbolicName(PN, SymbolicName); 5149 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5150 5151 // We can add Flags to the post-inc expression only if we 5152 // know that it is *undefined behavior* for BEValueV to 5153 // overflow. 5154 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5155 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5156 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5157 5158 return PHISCEV; 5159 } 5160 } 5161 } else { 5162 // Otherwise, this could be a loop like this: 5163 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5164 // In this case, j = {1,+,1} and BEValue is j. 5165 // Because the other in-value of i (0) fits the evolution of BEValue 5166 // i really is an addrec evolution. 5167 // 5168 // We can generalize this saying that i is the shifted value of BEValue 5169 // by one iteration: 5170 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5171 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5172 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5173 if (Shifted != getCouldNotCompute() && 5174 Start != getCouldNotCompute()) { 5175 const SCEV *StartVal = getSCEV(StartValueV); 5176 if (Start == StartVal) { 5177 // Okay, for the entire analysis of this edge we assumed the PHI 5178 // to be symbolic. We now need to go back and purge all of the 5179 // entries for the scalars that use the symbolic expression. 5180 forgetSymbolicName(PN, SymbolicName); 5181 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5182 return Shifted; 5183 } 5184 } 5185 } 5186 5187 // Remove the temporary PHI node SCEV that has been inserted while intending 5188 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5189 // as it will prevent later (possibly simpler) SCEV expressions to be added 5190 // to the ValueExprMap. 5191 eraseValueFromMap(PN); 5192 5193 return nullptr; 5194 } 5195 5196 // Checks if the SCEV S is available at BB. S is considered available at BB 5197 // if S can be materialized at BB without introducing a fault. 5198 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5199 BasicBlock *BB) { 5200 struct CheckAvailable { 5201 bool TraversalDone = false; 5202 bool Available = true; 5203 5204 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5205 BasicBlock *BB = nullptr; 5206 DominatorTree &DT; 5207 5208 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5209 : L(L), BB(BB), DT(DT) {} 5210 5211 bool setUnavailable() { 5212 TraversalDone = true; 5213 Available = false; 5214 return false; 5215 } 5216 5217 bool follow(const SCEV *S) { 5218 switch (S->getSCEVType()) { 5219 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5220 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5221 case scUMinExpr: 5222 case scSMinExpr: 5223 // These expressions are available if their operand(s) is/are. 5224 return true; 5225 5226 case scAddRecExpr: { 5227 // We allow add recurrences that are on the loop BB is in, or some 5228 // outer loop. This guarantees availability because the value of the 5229 // add recurrence at BB is simply the "current" value of the induction 5230 // variable. We can relax this in the future; for instance an add 5231 // recurrence on a sibling dominating loop is also available at BB. 5232 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5233 if (L && (ARLoop == L || ARLoop->contains(L))) 5234 return true; 5235 5236 return setUnavailable(); 5237 } 5238 5239 case scUnknown: { 5240 // For SCEVUnknown, we check for simple dominance. 5241 const auto *SU = cast<SCEVUnknown>(S); 5242 Value *V = SU->getValue(); 5243 5244 if (isa<Argument>(V)) 5245 return false; 5246 5247 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5248 return false; 5249 5250 return setUnavailable(); 5251 } 5252 5253 case scUDivExpr: 5254 case scCouldNotCompute: 5255 // We do not try to smart about these at all. 5256 return setUnavailable(); 5257 } 5258 llvm_unreachable("switch should be fully covered!"); 5259 } 5260 5261 bool isDone() { return TraversalDone; } 5262 }; 5263 5264 CheckAvailable CA(L, BB, DT); 5265 SCEVTraversal<CheckAvailable> ST(CA); 5266 5267 ST.visitAll(S); 5268 return CA.Available; 5269 } 5270 5271 // Try to match a control flow sequence that branches out at BI and merges back 5272 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5273 // match. 5274 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5275 Value *&C, Value *&LHS, Value *&RHS) { 5276 C = BI->getCondition(); 5277 5278 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5279 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5280 5281 if (!LeftEdge.isSingleEdge()) 5282 return false; 5283 5284 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5285 5286 Use &LeftUse = Merge->getOperandUse(0); 5287 Use &RightUse = Merge->getOperandUse(1); 5288 5289 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5290 LHS = LeftUse; 5291 RHS = RightUse; 5292 return true; 5293 } 5294 5295 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5296 LHS = RightUse; 5297 RHS = LeftUse; 5298 return true; 5299 } 5300 5301 return false; 5302 } 5303 5304 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5305 auto IsReachable = 5306 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5307 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5308 const Loop *L = LI.getLoopFor(PN->getParent()); 5309 5310 // We don't want to break LCSSA, even in a SCEV expression tree. 5311 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5312 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5313 return nullptr; 5314 5315 // Try to match 5316 // 5317 // br %cond, label %left, label %right 5318 // left: 5319 // br label %merge 5320 // right: 5321 // br label %merge 5322 // merge: 5323 // V = phi [ %x, %left ], [ %y, %right ] 5324 // 5325 // as "select %cond, %x, %y" 5326 5327 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5328 assert(IDom && "At least the entry block should dominate PN"); 5329 5330 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5331 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5332 5333 if (BI && BI->isConditional() && 5334 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5335 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5336 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5337 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5338 } 5339 5340 return nullptr; 5341 } 5342 5343 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5344 if (const SCEV *S = createAddRecFromPHI(PN)) 5345 return S; 5346 5347 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5348 return S; 5349 5350 // If the PHI has a single incoming value, follow that value, unless the 5351 // PHI's incoming blocks are in a different loop, in which case doing so 5352 // risks breaking LCSSA form. Instcombine would normally zap these, but 5353 // it doesn't have DominatorTree information, so it may miss cases. 5354 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5355 if (LI.replacementPreservesLCSSAForm(PN, V)) 5356 return getSCEV(V); 5357 5358 // If it's not a loop phi, we can't handle it yet. 5359 return getUnknown(PN); 5360 } 5361 5362 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5363 Value *Cond, 5364 Value *TrueVal, 5365 Value *FalseVal) { 5366 // Handle "constant" branch or select. This can occur for instance when a 5367 // loop pass transforms an inner loop and moves on to process the outer loop. 5368 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5369 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5370 5371 // Try to match some simple smax or umax patterns. 5372 auto *ICI = dyn_cast<ICmpInst>(Cond); 5373 if (!ICI) 5374 return getUnknown(I); 5375 5376 Value *LHS = ICI->getOperand(0); 5377 Value *RHS = ICI->getOperand(1); 5378 5379 switch (ICI->getPredicate()) { 5380 case ICmpInst::ICMP_SLT: 5381 case ICmpInst::ICMP_SLE: 5382 std::swap(LHS, RHS); 5383 LLVM_FALLTHROUGH; 5384 case ICmpInst::ICMP_SGT: 5385 case ICmpInst::ICMP_SGE: 5386 // a >s b ? a+x : b+x -> smax(a, b)+x 5387 // a >s b ? b+x : a+x -> smin(a, b)+x 5388 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5389 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5390 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5391 const SCEV *LA = getSCEV(TrueVal); 5392 const SCEV *RA = getSCEV(FalseVal); 5393 const SCEV *LDiff = getMinusSCEV(LA, LS); 5394 const SCEV *RDiff = getMinusSCEV(RA, RS); 5395 if (LDiff == RDiff) 5396 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5397 LDiff = getMinusSCEV(LA, RS); 5398 RDiff = getMinusSCEV(RA, LS); 5399 if (LDiff == RDiff) 5400 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5401 } 5402 break; 5403 case ICmpInst::ICMP_ULT: 5404 case ICmpInst::ICMP_ULE: 5405 std::swap(LHS, RHS); 5406 LLVM_FALLTHROUGH; 5407 case ICmpInst::ICMP_UGT: 5408 case ICmpInst::ICMP_UGE: 5409 // a >u b ? a+x : b+x -> umax(a, b)+x 5410 // a >u b ? b+x : a+x -> umin(a, b)+x 5411 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5412 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5413 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5414 const SCEV *LA = getSCEV(TrueVal); 5415 const SCEV *RA = getSCEV(FalseVal); 5416 const SCEV *LDiff = getMinusSCEV(LA, LS); 5417 const SCEV *RDiff = getMinusSCEV(RA, RS); 5418 if (LDiff == RDiff) 5419 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5420 LDiff = getMinusSCEV(LA, RS); 5421 RDiff = getMinusSCEV(RA, LS); 5422 if (LDiff == RDiff) 5423 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5424 } 5425 break; 5426 case ICmpInst::ICMP_NE: 5427 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5428 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5429 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5430 const SCEV *One = getOne(I->getType()); 5431 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5432 const SCEV *LA = getSCEV(TrueVal); 5433 const SCEV *RA = getSCEV(FalseVal); 5434 const SCEV *LDiff = getMinusSCEV(LA, LS); 5435 const SCEV *RDiff = getMinusSCEV(RA, One); 5436 if (LDiff == RDiff) 5437 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5438 } 5439 break; 5440 case ICmpInst::ICMP_EQ: 5441 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5442 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5443 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5444 const SCEV *One = getOne(I->getType()); 5445 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5446 const SCEV *LA = getSCEV(TrueVal); 5447 const SCEV *RA = getSCEV(FalseVal); 5448 const SCEV *LDiff = getMinusSCEV(LA, One); 5449 const SCEV *RDiff = getMinusSCEV(RA, LS); 5450 if (LDiff == RDiff) 5451 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5452 } 5453 break; 5454 default: 5455 break; 5456 } 5457 5458 return getUnknown(I); 5459 } 5460 5461 /// Expand GEP instructions into add and multiply operations. This allows them 5462 /// to be analyzed by regular SCEV code. 5463 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5464 // Don't attempt to analyze GEPs over unsized objects. 5465 if (!GEP->getSourceElementType()->isSized()) 5466 return getUnknown(GEP); 5467 5468 SmallVector<const SCEV *, 4> IndexExprs; 5469 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5470 IndexExprs.push_back(getSCEV(*Index)); 5471 return getGEPExpr(GEP, IndexExprs); 5472 } 5473 5474 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5475 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5476 return C->getAPInt().countTrailingZeros(); 5477 5478 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5479 return std::min(GetMinTrailingZeros(T->getOperand()), 5480 (uint32_t)getTypeSizeInBits(T->getType())); 5481 5482 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5483 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5484 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5485 ? getTypeSizeInBits(E->getType()) 5486 : OpRes; 5487 } 5488 5489 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5490 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5491 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5492 ? getTypeSizeInBits(E->getType()) 5493 : OpRes; 5494 } 5495 5496 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5497 // The result is the min of all operands results. 5498 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5499 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5500 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5501 return MinOpRes; 5502 } 5503 5504 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5505 // The result is the sum of all operands results. 5506 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5507 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5508 for (unsigned i = 1, e = M->getNumOperands(); 5509 SumOpRes != BitWidth && i != e; ++i) 5510 SumOpRes = 5511 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5512 return SumOpRes; 5513 } 5514 5515 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5516 // The result is the min of all operands results. 5517 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5518 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5519 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5520 return MinOpRes; 5521 } 5522 5523 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5524 // The result is the min of all operands results. 5525 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5526 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5527 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5528 return MinOpRes; 5529 } 5530 5531 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5532 // The result is the min of all operands results. 5533 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5534 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5535 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5536 return MinOpRes; 5537 } 5538 5539 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5540 // For a SCEVUnknown, ask ValueTracking. 5541 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5542 return Known.countMinTrailingZeros(); 5543 } 5544 5545 // SCEVUDivExpr 5546 return 0; 5547 } 5548 5549 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5550 auto I = MinTrailingZerosCache.find(S); 5551 if (I != MinTrailingZerosCache.end()) 5552 return I->second; 5553 5554 uint32_t Result = GetMinTrailingZerosImpl(S); 5555 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5556 assert(InsertPair.second && "Should insert a new key"); 5557 return InsertPair.first->second; 5558 } 5559 5560 /// Helper method to assign a range to V from metadata present in the IR. 5561 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5562 if (Instruction *I = dyn_cast<Instruction>(V)) 5563 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5564 return getConstantRangeFromMetadata(*MD); 5565 5566 return None; 5567 } 5568 5569 /// Determine the range for a particular SCEV. If SignHint is 5570 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5571 /// with a "cleaner" unsigned (resp. signed) representation. 5572 const ConstantRange & 5573 ScalarEvolution::getRangeRef(const SCEV *S, 5574 ScalarEvolution::RangeSignHint SignHint) { 5575 DenseMap<const SCEV *, ConstantRange> &Cache = 5576 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5577 : SignedRanges; 5578 ConstantRange::PreferredRangeType RangeType = 5579 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5580 ? ConstantRange::Unsigned : ConstantRange::Signed; 5581 5582 // See if we've computed this range already. 5583 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5584 if (I != Cache.end()) 5585 return I->second; 5586 5587 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5588 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5589 5590 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5591 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5592 using OBO = OverflowingBinaryOperator; 5593 5594 // If the value has known zeros, the maximum value will have those known zeros 5595 // as well. 5596 uint32_t TZ = GetMinTrailingZeros(S); 5597 if (TZ != 0) { 5598 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5599 ConservativeResult = 5600 ConstantRange(APInt::getMinValue(BitWidth), 5601 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5602 else 5603 ConservativeResult = ConstantRange( 5604 APInt::getSignedMinValue(BitWidth), 5605 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5606 } 5607 5608 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5609 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5610 unsigned WrapType = OBO::AnyWrap; 5611 if (Add->hasNoSignedWrap()) 5612 WrapType |= OBO::NoSignedWrap; 5613 if (Add->hasNoUnsignedWrap()) 5614 WrapType |= OBO::NoUnsignedWrap; 5615 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5616 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5617 WrapType, RangeType); 5618 return setRange(Add, SignHint, 5619 ConservativeResult.intersectWith(X, RangeType)); 5620 } 5621 5622 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5623 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5624 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5625 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5626 return setRange(Mul, SignHint, 5627 ConservativeResult.intersectWith(X, RangeType)); 5628 } 5629 5630 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5631 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5632 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5633 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5634 return setRange(SMax, SignHint, 5635 ConservativeResult.intersectWith(X, RangeType)); 5636 } 5637 5638 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5639 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5640 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5641 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5642 return setRange(UMax, SignHint, 5643 ConservativeResult.intersectWith(X, RangeType)); 5644 } 5645 5646 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5647 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5648 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5649 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5650 return setRange(SMin, SignHint, 5651 ConservativeResult.intersectWith(X, RangeType)); 5652 } 5653 5654 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5655 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5656 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5657 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5658 return setRange(UMin, SignHint, 5659 ConservativeResult.intersectWith(X, RangeType)); 5660 } 5661 5662 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5663 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5664 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5665 return setRange(UDiv, SignHint, 5666 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5667 } 5668 5669 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5670 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5671 return setRange(ZExt, SignHint, 5672 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5673 RangeType)); 5674 } 5675 5676 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5677 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5678 return setRange(SExt, SignHint, 5679 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5680 RangeType)); 5681 } 5682 5683 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5684 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5685 return setRange(Trunc, SignHint, 5686 ConservativeResult.intersectWith(X.truncate(BitWidth), 5687 RangeType)); 5688 } 5689 5690 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5691 // If there's no unsigned wrap, the value will never be less than its 5692 // initial value. 5693 if (AddRec->hasNoUnsignedWrap()) { 5694 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5695 if (!UnsignedMinValue.isNullValue()) 5696 ConservativeResult = ConservativeResult.intersectWith( 5697 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5698 } 5699 5700 // If there's no signed wrap, and all the operands except initial value have 5701 // the same sign or zero, the value won't ever be: 5702 // 1: smaller than initial value if operands are non negative, 5703 // 2: bigger than initial value if operands are non positive. 5704 // For both cases, value can not cross signed min/max boundary. 5705 if (AddRec->hasNoSignedWrap()) { 5706 bool AllNonNeg = true; 5707 bool AllNonPos = true; 5708 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5709 if (!isKnownNonNegative(AddRec->getOperand(i))) 5710 AllNonNeg = false; 5711 if (!isKnownNonPositive(AddRec->getOperand(i))) 5712 AllNonPos = false; 5713 } 5714 if (AllNonNeg) 5715 ConservativeResult = ConservativeResult.intersectWith( 5716 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5717 APInt::getSignedMinValue(BitWidth)), 5718 RangeType); 5719 else if (AllNonPos) 5720 ConservativeResult = ConservativeResult.intersectWith( 5721 ConstantRange::getNonEmpty( 5722 APInt::getSignedMinValue(BitWidth), 5723 getSignedRangeMax(AddRec->getStart()) + 1), 5724 RangeType); 5725 } 5726 5727 // TODO: non-affine addrec 5728 if (AddRec->isAffine()) { 5729 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5730 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5731 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5732 auto RangeFromAffine = getRangeForAffineAR( 5733 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5734 BitWidth); 5735 if (!RangeFromAffine.isFullSet()) 5736 ConservativeResult = 5737 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5738 5739 auto RangeFromFactoring = getRangeViaFactoring( 5740 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5741 BitWidth); 5742 if (!RangeFromFactoring.isFullSet()) 5743 ConservativeResult = 5744 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5745 } 5746 } 5747 5748 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5749 } 5750 5751 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5752 // Check if the IR explicitly contains !range metadata. 5753 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5754 if (MDRange.hasValue()) 5755 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5756 RangeType); 5757 5758 // Split here to avoid paying the compile-time cost of calling both 5759 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5760 // if needed. 5761 const DataLayout &DL = getDataLayout(); 5762 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5763 // For a SCEVUnknown, ask ValueTracking. 5764 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5765 if (Known.getBitWidth() != BitWidth) 5766 Known = Known.zextOrTrunc(BitWidth); 5767 // If Known does not result in full-set, intersect with it. 5768 if (Known.getMinValue() != Known.getMaxValue() + 1) 5769 ConservativeResult = ConservativeResult.intersectWith( 5770 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5771 RangeType); 5772 } else { 5773 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5774 "generalize as needed!"); 5775 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5776 // If the pointer size is larger than the index size type, this can cause 5777 // NS to be larger than BitWidth. So compensate for this. 5778 if (U->getType()->isPointerTy()) { 5779 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5780 int ptrIdxDiff = ptrSize - BitWidth; 5781 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5782 NS -= ptrIdxDiff; 5783 } 5784 5785 if (NS > 1) 5786 ConservativeResult = ConservativeResult.intersectWith( 5787 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5788 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5789 RangeType); 5790 } 5791 5792 // A range of Phi is a subset of union of all ranges of its input. 5793 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5794 // Make sure that we do not run over cycled Phis. 5795 if (PendingPhiRanges.insert(Phi).second) { 5796 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5797 for (auto &Op : Phi->operands()) { 5798 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5799 RangeFromOps = RangeFromOps.unionWith(OpRange); 5800 // No point to continue if we already have a full set. 5801 if (RangeFromOps.isFullSet()) 5802 break; 5803 } 5804 ConservativeResult = 5805 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5806 bool Erased = PendingPhiRanges.erase(Phi); 5807 assert(Erased && "Failed to erase Phi properly?"); 5808 (void) Erased; 5809 } 5810 } 5811 5812 return setRange(U, SignHint, std::move(ConservativeResult)); 5813 } 5814 5815 return setRange(S, SignHint, std::move(ConservativeResult)); 5816 } 5817 5818 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5819 // values that the expression can take. Initially, the expression has a value 5820 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5821 // argument defines if we treat Step as signed or unsigned. 5822 static ConstantRange getRangeForAffineARHelper(APInt Step, 5823 const ConstantRange &StartRange, 5824 const APInt &MaxBECount, 5825 unsigned BitWidth, bool Signed) { 5826 // If either Step or MaxBECount is 0, then the expression won't change, and we 5827 // just need to return the initial range. 5828 if (Step == 0 || MaxBECount == 0) 5829 return StartRange; 5830 5831 // If we don't know anything about the initial value (i.e. StartRange is 5832 // FullRange), then we don't know anything about the final range either. 5833 // Return FullRange. 5834 if (StartRange.isFullSet()) 5835 return ConstantRange::getFull(BitWidth); 5836 5837 // If Step is signed and negative, then we use its absolute value, but we also 5838 // note that we're moving in the opposite direction. 5839 bool Descending = Signed && Step.isNegative(); 5840 5841 if (Signed) 5842 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5843 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5844 // This equations hold true due to the well-defined wrap-around behavior of 5845 // APInt. 5846 Step = Step.abs(); 5847 5848 // Check if Offset is more than full span of BitWidth. If it is, the 5849 // expression is guaranteed to overflow. 5850 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5851 return ConstantRange::getFull(BitWidth); 5852 5853 // Offset is by how much the expression can change. Checks above guarantee no 5854 // overflow here. 5855 APInt Offset = Step * MaxBECount; 5856 5857 // Minimum value of the final range will match the minimal value of StartRange 5858 // if the expression is increasing and will be decreased by Offset otherwise. 5859 // Maximum value of the final range will match the maximal value of StartRange 5860 // if the expression is decreasing and will be increased by Offset otherwise. 5861 APInt StartLower = StartRange.getLower(); 5862 APInt StartUpper = StartRange.getUpper() - 1; 5863 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5864 : (StartUpper + std::move(Offset)); 5865 5866 // It's possible that the new minimum/maximum value will fall into the initial 5867 // range (due to wrap around). This means that the expression can take any 5868 // value in this bitwidth, and we have to return full range. 5869 if (StartRange.contains(MovedBoundary)) 5870 return ConstantRange::getFull(BitWidth); 5871 5872 APInt NewLower = 5873 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5874 APInt NewUpper = 5875 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5876 NewUpper += 1; 5877 5878 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5879 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5880 } 5881 5882 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5883 const SCEV *Step, 5884 const SCEV *MaxBECount, 5885 unsigned BitWidth) { 5886 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5887 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5888 "Precondition!"); 5889 5890 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5891 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5892 5893 // First, consider step signed. 5894 ConstantRange StartSRange = getSignedRange(Start); 5895 ConstantRange StepSRange = getSignedRange(Step); 5896 5897 // If Step can be both positive and negative, we need to find ranges for the 5898 // maximum absolute step values in both directions and union them. 5899 ConstantRange SR = 5900 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5901 MaxBECountValue, BitWidth, /* Signed = */ true); 5902 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5903 StartSRange, MaxBECountValue, 5904 BitWidth, /* Signed = */ true)); 5905 5906 // Next, consider step unsigned. 5907 ConstantRange UR = getRangeForAffineARHelper( 5908 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5909 MaxBECountValue, BitWidth, /* Signed = */ false); 5910 5911 // Finally, intersect signed and unsigned ranges. 5912 return SR.intersectWith(UR, ConstantRange::Smallest); 5913 } 5914 5915 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5916 const SCEV *Step, 5917 const SCEV *MaxBECount, 5918 unsigned BitWidth) { 5919 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5920 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5921 5922 struct SelectPattern { 5923 Value *Condition = nullptr; 5924 APInt TrueValue; 5925 APInt FalseValue; 5926 5927 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5928 const SCEV *S) { 5929 Optional<unsigned> CastOp; 5930 APInt Offset(BitWidth, 0); 5931 5932 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5933 "Should be!"); 5934 5935 // Peel off a constant offset: 5936 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5937 // In the future we could consider being smarter here and handle 5938 // {Start+Step,+,Step} too. 5939 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5940 return; 5941 5942 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5943 S = SA->getOperand(1); 5944 } 5945 5946 // Peel off a cast operation 5947 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5948 CastOp = SCast->getSCEVType(); 5949 S = SCast->getOperand(); 5950 } 5951 5952 using namespace llvm::PatternMatch; 5953 5954 auto *SU = dyn_cast<SCEVUnknown>(S); 5955 const APInt *TrueVal, *FalseVal; 5956 if (!SU || 5957 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5958 m_APInt(FalseVal)))) { 5959 Condition = nullptr; 5960 return; 5961 } 5962 5963 TrueValue = *TrueVal; 5964 FalseValue = *FalseVal; 5965 5966 // Re-apply the cast we peeled off earlier 5967 if (CastOp.hasValue()) 5968 switch (*CastOp) { 5969 default: 5970 llvm_unreachable("Unknown SCEV cast type!"); 5971 5972 case scTruncate: 5973 TrueValue = TrueValue.trunc(BitWidth); 5974 FalseValue = FalseValue.trunc(BitWidth); 5975 break; 5976 case scZeroExtend: 5977 TrueValue = TrueValue.zext(BitWidth); 5978 FalseValue = FalseValue.zext(BitWidth); 5979 break; 5980 case scSignExtend: 5981 TrueValue = TrueValue.sext(BitWidth); 5982 FalseValue = FalseValue.sext(BitWidth); 5983 break; 5984 } 5985 5986 // Re-apply the constant offset we peeled off earlier 5987 TrueValue += Offset; 5988 FalseValue += Offset; 5989 } 5990 5991 bool isRecognized() { return Condition != nullptr; } 5992 }; 5993 5994 SelectPattern StartPattern(*this, BitWidth, Start); 5995 if (!StartPattern.isRecognized()) 5996 return ConstantRange::getFull(BitWidth); 5997 5998 SelectPattern StepPattern(*this, BitWidth, Step); 5999 if (!StepPattern.isRecognized()) 6000 return ConstantRange::getFull(BitWidth); 6001 6002 if (StartPattern.Condition != StepPattern.Condition) { 6003 // We don't handle this case today; but we could, by considering four 6004 // possibilities below instead of two. I'm not sure if there are cases where 6005 // that will help over what getRange already does, though. 6006 return ConstantRange::getFull(BitWidth); 6007 } 6008 6009 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6010 // construct arbitrary general SCEV expressions here. This function is called 6011 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6012 // say) can end up caching a suboptimal value. 6013 6014 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6015 // C2352 and C2512 (otherwise it isn't needed). 6016 6017 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6018 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6019 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6020 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6021 6022 ConstantRange TrueRange = 6023 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6024 ConstantRange FalseRange = 6025 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6026 6027 return TrueRange.unionWith(FalseRange); 6028 } 6029 6030 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6031 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6032 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6033 6034 // Return early if there are no flags to propagate to the SCEV. 6035 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6036 if (BinOp->hasNoUnsignedWrap()) 6037 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6038 if (BinOp->hasNoSignedWrap()) 6039 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6040 if (Flags == SCEV::FlagAnyWrap) 6041 return SCEV::FlagAnyWrap; 6042 6043 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6044 } 6045 6046 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6047 // Here we check that I is in the header of the innermost loop containing I, 6048 // since we only deal with instructions in the loop header. The actual loop we 6049 // need to check later will come from an add recurrence, but getting that 6050 // requires computing the SCEV of the operands, which can be expensive. This 6051 // check we can do cheaply to rule out some cases early. 6052 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6053 if (InnermostContainingLoop == nullptr || 6054 InnermostContainingLoop->getHeader() != I->getParent()) 6055 return false; 6056 6057 // Only proceed if we can prove that I does not yield poison. 6058 if (!programUndefinedIfFullPoison(I)) 6059 return false; 6060 6061 // At this point we know that if I is executed, then it does not wrap 6062 // according to at least one of NSW or NUW. If I is not executed, then we do 6063 // not know if the calculation that I represents would wrap. Multiple 6064 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6065 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6066 // derived from other instructions that map to the same SCEV. We cannot make 6067 // that guarantee for cases where I is not executed. So we need to find the 6068 // loop that I is considered in relation to and prove that I is executed for 6069 // every iteration of that loop. That implies that the value that I 6070 // calculates does not wrap anywhere in the loop, so then we can apply the 6071 // flags to the SCEV. 6072 // 6073 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6074 // from different loops, so that we know which loop to prove that I is 6075 // executed in. 6076 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6077 // I could be an extractvalue from a call to an overflow intrinsic. 6078 // TODO: We can do better here in some cases. 6079 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6080 return false; 6081 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6082 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6083 bool AllOtherOpsLoopInvariant = true; 6084 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6085 ++OtherOpIndex) { 6086 if (OtherOpIndex != OpIndex) { 6087 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6088 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6089 AllOtherOpsLoopInvariant = false; 6090 break; 6091 } 6092 } 6093 } 6094 if (AllOtherOpsLoopInvariant && 6095 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6096 return true; 6097 } 6098 } 6099 return false; 6100 } 6101 6102 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6103 // If we know that \c I can never be poison period, then that's enough. 6104 if (isSCEVExprNeverPoison(I)) 6105 return true; 6106 6107 // For an add recurrence specifically, we assume that infinite loops without 6108 // side effects are undefined behavior, and then reason as follows: 6109 // 6110 // If the add recurrence is poison in any iteration, it is poison on all 6111 // future iterations (since incrementing poison yields poison). If the result 6112 // of the add recurrence is fed into the loop latch condition and the loop 6113 // does not contain any throws or exiting blocks other than the latch, we now 6114 // have the ability to "choose" whether the backedge is taken or not (by 6115 // choosing a sufficiently evil value for the poison feeding into the branch) 6116 // for every iteration including and after the one in which \p I first became 6117 // poison. There are two possibilities (let's call the iteration in which \p 6118 // I first became poison as K): 6119 // 6120 // 1. In the set of iterations including and after K, the loop body executes 6121 // no side effects. In this case executing the backege an infinte number 6122 // of times will yield undefined behavior. 6123 // 6124 // 2. In the set of iterations including and after K, the loop body executes 6125 // at least one side effect. In this case, that specific instance of side 6126 // effect is control dependent on poison, which also yields undefined 6127 // behavior. 6128 6129 auto *ExitingBB = L->getExitingBlock(); 6130 auto *LatchBB = L->getLoopLatch(); 6131 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6132 return false; 6133 6134 SmallPtrSet<const Instruction *, 16> Pushed; 6135 SmallVector<const Instruction *, 8> PoisonStack; 6136 6137 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6138 // things that are known to be fully poison under that assumption go on the 6139 // PoisonStack. 6140 Pushed.insert(I); 6141 PoisonStack.push_back(I); 6142 6143 bool LatchControlDependentOnPoison = false; 6144 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6145 const Instruction *Poison = PoisonStack.pop_back_val(); 6146 6147 for (auto *PoisonUser : Poison->users()) { 6148 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6149 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6150 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6151 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6152 assert(BI->isConditional() && "Only possibility!"); 6153 if (BI->getParent() == LatchBB) { 6154 LatchControlDependentOnPoison = true; 6155 break; 6156 } 6157 } 6158 } 6159 } 6160 6161 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6162 } 6163 6164 ScalarEvolution::LoopProperties 6165 ScalarEvolution::getLoopProperties(const Loop *L) { 6166 using LoopProperties = ScalarEvolution::LoopProperties; 6167 6168 auto Itr = LoopPropertiesCache.find(L); 6169 if (Itr == LoopPropertiesCache.end()) { 6170 auto HasSideEffects = [](Instruction *I) { 6171 if (auto *SI = dyn_cast<StoreInst>(I)) 6172 return !SI->isSimple(); 6173 6174 return I->mayHaveSideEffects(); 6175 }; 6176 6177 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6178 /*HasNoSideEffects*/ true}; 6179 6180 for (auto *BB : L->getBlocks()) 6181 for (auto &I : *BB) { 6182 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6183 LP.HasNoAbnormalExits = false; 6184 if (HasSideEffects(&I)) 6185 LP.HasNoSideEffects = false; 6186 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6187 break; // We're already as pessimistic as we can get. 6188 } 6189 6190 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6191 assert(InsertPair.second && "We just checked!"); 6192 Itr = InsertPair.first; 6193 } 6194 6195 return Itr->second; 6196 } 6197 6198 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6199 if (!isSCEVable(V->getType())) 6200 return getUnknown(V); 6201 6202 if (Instruction *I = dyn_cast<Instruction>(V)) { 6203 // Don't attempt to analyze instructions in blocks that aren't 6204 // reachable. Such instructions don't matter, and they aren't required 6205 // to obey basic rules for definitions dominating uses which this 6206 // analysis depends on. 6207 if (!DT.isReachableFromEntry(I->getParent())) 6208 return getUnknown(UndefValue::get(V->getType())); 6209 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6210 return getConstant(CI); 6211 else if (isa<ConstantPointerNull>(V)) 6212 return getZero(V->getType()); 6213 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6214 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6215 else if (!isa<ConstantExpr>(V)) 6216 return getUnknown(V); 6217 6218 Operator *U = cast<Operator>(V); 6219 if (auto BO = MatchBinaryOp(U, DT)) { 6220 switch (BO->Opcode) { 6221 case Instruction::Add: { 6222 // The simple thing to do would be to just call getSCEV on both operands 6223 // and call getAddExpr with the result. However if we're looking at a 6224 // bunch of things all added together, this can be quite inefficient, 6225 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6226 // Instead, gather up all the operands and make a single getAddExpr call. 6227 // LLVM IR canonical form means we need only traverse the left operands. 6228 SmallVector<const SCEV *, 4> AddOps; 6229 do { 6230 if (BO->Op) { 6231 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6232 AddOps.push_back(OpSCEV); 6233 break; 6234 } 6235 6236 // If a NUW or NSW flag can be applied to the SCEV for this 6237 // addition, then compute the SCEV for this addition by itself 6238 // with a separate call to getAddExpr. We need to do that 6239 // instead of pushing the operands of the addition onto AddOps, 6240 // since the flags are only known to apply to this particular 6241 // addition - they may not apply to other additions that can be 6242 // formed with operands from AddOps. 6243 const SCEV *RHS = getSCEV(BO->RHS); 6244 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6245 if (Flags != SCEV::FlagAnyWrap) { 6246 const SCEV *LHS = getSCEV(BO->LHS); 6247 if (BO->Opcode == Instruction::Sub) 6248 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6249 else 6250 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6251 break; 6252 } 6253 } 6254 6255 if (BO->Opcode == Instruction::Sub) 6256 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6257 else 6258 AddOps.push_back(getSCEV(BO->RHS)); 6259 6260 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6261 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6262 NewBO->Opcode != Instruction::Sub)) { 6263 AddOps.push_back(getSCEV(BO->LHS)); 6264 break; 6265 } 6266 BO = NewBO; 6267 } while (true); 6268 6269 return getAddExpr(AddOps); 6270 } 6271 6272 case Instruction::Mul: { 6273 SmallVector<const SCEV *, 4> MulOps; 6274 do { 6275 if (BO->Op) { 6276 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6277 MulOps.push_back(OpSCEV); 6278 break; 6279 } 6280 6281 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6282 if (Flags != SCEV::FlagAnyWrap) { 6283 MulOps.push_back( 6284 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6285 break; 6286 } 6287 } 6288 6289 MulOps.push_back(getSCEV(BO->RHS)); 6290 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6291 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6292 MulOps.push_back(getSCEV(BO->LHS)); 6293 break; 6294 } 6295 BO = NewBO; 6296 } while (true); 6297 6298 return getMulExpr(MulOps); 6299 } 6300 case Instruction::UDiv: 6301 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6302 case Instruction::URem: 6303 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6304 case Instruction::Sub: { 6305 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6306 if (BO->Op) 6307 Flags = getNoWrapFlagsFromUB(BO->Op); 6308 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6309 } 6310 case Instruction::And: 6311 // For an expression like x&255 that merely masks off the high bits, 6312 // use zext(trunc(x)) as the SCEV expression. 6313 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6314 if (CI->isZero()) 6315 return getSCEV(BO->RHS); 6316 if (CI->isMinusOne()) 6317 return getSCEV(BO->LHS); 6318 const APInt &A = CI->getValue(); 6319 6320 // Instcombine's ShrinkDemandedConstant may strip bits out of 6321 // constants, obscuring what would otherwise be a low-bits mask. 6322 // Use computeKnownBits to compute what ShrinkDemandedConstant 6323 // knew about to reconstruct a low-bits mask value. 6324 unsigned LZ = A.countLeadingZeros(); 6325 unsigned TZ = A.countTrailingZeros(); 6326 unsigned BitWidth = A.getBitWidth(); 6327 KnownBits Known(BitWidth); 6328 computeKnownBits(BO->LHS, Known, getDataLayout(), 6329 0, &AC, nullptr, &DT); 6330 6331 APInt EffectiveMask = 6332 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6333 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6334 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6335 const SCEV *LHS = getSCEV(BO->LHS); 6336 const SCEV *ShiftedLHS = nullptr; 6337 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6338 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6339 // For an expression like (x * 8) & 8, simplify the multiply. 6340 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6341 unsigned GCD = std::min(MulZeros, TZ); 6342 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6343 SmallVector<const SCEV*, 4> MulOps; 6344 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6345 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6346 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6347 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6348 } 6349 } 6350 if (!ShiftedLHS) 6351 ShiftedLHS = getUDivExpr(LHS, MulCount); 6352 return getMulExpr( 6353 getZeroExtendExpr( 6354 getTruncateExpr(ShiftedLHS, 6355 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6356 BO->LHS->getType()), 6357 MulCount); 6358 } 6359 } 6360 break; 6361 6362 case Instruction::Or: 6363 // If the RHS of the Or is a constant, we may have something like: 6364 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6365 // optimizations will transparently handle this case. 6366 // 6367 // In order for this transformation to be safe, the LHS must be of the 6368 // form X*(2^n) and the Or constant must be less than 2^n. 6369 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6370 const SCEV *LHS = getSCEV(BO->LHS); 6371 const APInt &CIVal = CI->getValue(); 6372 if (GetMinTrailingZeros(LHS) >= 6373 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6374 // Build a plain add SCEV. 6375 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6376 // If the LHS of the add was an addrec and it has no-wrap flags, 6377 // transfer the no-wrap flags, since an or won't introduce a wrap. 6378 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6379 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6380 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6381 OldAR->getNoWrapFlags()); 6382 } 6383 return S; 6384 } 6385 } 6386 break; 6387 6388 case Instruction::Xor: 6389 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6390 // If the RHS of xor is -1, then this is a not operation. 6391 if (CI->isMinusOne()) 6392 return getNotSCEV(getSCEV(BO->LHS)); 6393 6394 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6395 // This is a variant of the check for xor with -1, and it handles 6396 // the case where instcombine has trimmed non-demanded bits out 6397 // of an xor with -1. 6398 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6399 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6400 if (LBO->getOpcode() == Instruction::And && 6401 LCI->getValue() == CI->getValue()) 6402 if (const SCEVZeroExtendExpr *Z = 6403 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6404 Type *UTy = BO->LHS->getType(); 6405 const SCEV *Z0 = Z->getOperand(); 6406 Type *Z0Ty = Z0->getType(); 6407 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6408 6409 // If C is a low-bits mask, the zero extend is serving to 6410 // mask off the high bits. Complement the operand and 6411 // re-apply the zext. 6412 if (CI->getValue().isMask(Z0TySize)) 6413 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6414 6415 // If C is a single bit, it may be in the sign-bit position 6416 // before the zero-extend. In this case, represent the xor 6417 // using an add, which is equivalent, and re-apply the zext. 6418 APInt Trunc = CI->getValue().trunc(Z0TySize); 6419 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6420 Trunc.isSignMask()) 6421 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6422 UTy); 6423 } 6424 } 6425 break; 6426 6427 case Instruction::Shl: 6428 // Turn shift left of a constant amount into a multiply. 6429 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6430 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6431 6432 // If the shift count is not less than the bitwidth, the result of 6433 // the shift is undefined. Don't try to analyze it, because the 6434 // resolution chosen here may differ from the resolution chosen in 6435 // other parts of the compiler. 6436 if (SA->getValue().uge(BitWidth)) 6437 break; 6438 6439 // It is currently not resolved how to interpret NSW for left 6440 // shift by BitWidth - 1, so we avoid applying flags in that 6441 // case. Remove this check (or this comment) once the situation 6442 // is resolved. See 6443 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6444 // and http://reviews.llvm.org/D8890 . 6445 auto Flags = SCEV::FlagAnyWrap; 6446 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6447 Flags = getNoWrapFlagsFromUB(BO->Op); 6448 6449 Constant *X = ConstantInt::get( 6450 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6451 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6452 } 6453 break; 6454 6455 case Instruction::AShr: { 6456 // AShr X, C, where C is a constant. 6457 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6458 if (!CI) 6459 break; 6460 6461 Type *OuterTy = BO->LHS->getType(); 6462 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6463 // If the shift count is not less than the bitwidth, the result of 6464 // the shift is undefined. Don't try to analyze it, because the 6465 // resolution chosen here may differ from the resolution chosen in 6466 // other parts of the compiler. 6467 if (CI->getValue().uge(BitWidth)) 6468 break; 6469 6470 if (CI->isZero()) 6471 return getSCEV(BO->LHS); // shift by zero --> noop 6472 6473 uint64_t AShrAmt = CI->getZExtValue(); 6474 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6475 6476 Operator *L = dyn_cast<Operator>(BO->LHS); 6477 if (L && L->getOpcode() == Instruction::Shl) { 6478 // X = Shl A, n 6479 // Y = AShr X, m 6480 // Both n and m are constant. 6481 6482 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6483 if (L->getOperand(1) == BO->RHS) 6484 // For a two-shift sext-inreg, i.e. n = m, 6485 // use sext(trunc(x)) as the SCEV expression. 6486 return getSignExtendExpr( 6487 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6488 6489 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6490 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6491 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6492 if (ShlAmt > AShrAmt) { 6493 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6494 // expression. We already checked that ShlAmt < BitWidth, so 6495 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6496 // ShlAmt - AShrAmt < Amt. 6497 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6498 ShlAmt - AShrAmt); 6499 return getSignExtendExpr( 6500 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6501 getConstant(Mul)), OuterTy); 6502 } 6503 } 6504 } 6505 break; 6506 } 6507 } 6508 } 6509 6510 switch (U->getOpcode()) { 6511 case Instruction::Trunc: 6512 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6513 6514 case Instruction::ZExt: 6515 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6516 6517 case Instruction::SExt: 6518 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6519 // The NSW flag of a subtract does not always survive the conversion to 6520 // A + (-1)*B. By pushing sign extension onto its operands we are much 6521 // more likely to preserve NSW and allow later AddRec optimisations. 6522 // 6523 // NOTE: This is effectively duplicating this logic from getSignExtend: 6524 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6525 // but by that point the NSW information has potentially been lost. 6526 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6527 Type *Ty = U->getType(); 6528 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6529 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6530 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6531 } 6532 } 6533 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6534 6535 case Instruction::BitCast: 6536 // BitCasts are no-op casts so we just eliminate the cast. 6537 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6538 return getSCEV(U->getOperand(0)); 6539 break; 6540 6541 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6542 // lead to pointer expressions which cannot safely be expanded to GEPs, 6543 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6544 // simplifying integer expressions. 6545 6546 case Instruction::GetElementPtr: 6547 return createNodeForGEP(cast<GEPOperator>(U)); 6548 6549 case Instruction::PHI: 6550 return createNodeForPHI(cast<PHINode>(U)); 6551 6552 case Instruction::Select: 6553 // U can also be a select constant expr, which let fall through. Since 6554 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6555 // constant expressions cannot have instructions as operands, we'd have 6556 // returned getUnknown for a select constant expressions anyway. 6557 if (isa<Instruction>(U)) 6558 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6559 U->getOperand(1), U->getOperand(2)); 6560 break; 6561 6562 case Instruction::Call: 6563 case Instruction::Invoke: 6564 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6565 return getSCEV(RV); 6566 break; 6567 } 6568 6569 return getUnknown(V); 6570 } 6571 6572 //===----------------------------------------------------------------------===// 6573 // Iteration Count Computation Code 6574 // 6575 6576 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6577 if (!ExitCount) 6578 return 0; 6579 6580 ConstantInt *ExitConst = ExitCount->getValue(); 6581 6582 // Guard against huge trip counts. 6583 if (ExitConst->getValue().getActiveBits() > 32) 6584 return 0; 6585 6586 // In case of integer overflow, this returns 0, which is correct. 6587 return ((unsigned)ExitConst->getZExtValue()) + 1; 6588 } 6589 6590 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6591 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6592 return getSmallConstantTripCount(L, ExitingBB); 6593 6594 // No trip count information for multiple exits. 6595 return 0; 6596 } 6597 6598 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6599 BasicBlock *ExitingBlock) { 6600 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6601 assert(L->isLoopExiting(ExitingBlock) && 6602 "Exiting block must actually branch out of the loop!"); 6603 const SCEVConstant *ExitCount = 6604 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6605 return getConstantTripCount(ExitCount); 6606 } 6607 6608 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6609 const auto *MaxExitCount = 6610 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6611 return getConstantTripCount(MaxExitCount); 6612 } 6613 6614 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6615 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6616 return getSmallConstantTripMultiple(L, ExitingBB); 6617 6618 // No trip multiple information for multiple exits. 6619 return 0; 6620 } 6621 6622 /// Returns the largest constant divisor of the trip count of this loop as a 6623 /// normal unsigned value, if possible. This means that the actual trip count is 6624 /// always a multiple of the returned value (don't forget the trip count could 6625 /// very well be zero as well!). 6626 /// 6627 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6628 /// multiple of a constant (which is also the case if the trip count is simply 6629 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6630 /// if the trip count is very large (>= 2^32). 6631 /// 6632 /// As explained in the comments for getSmallConstantTripCount, this assumes 6633 /// that control exits the loop via ExitingBlock. 6634 unsigned 6635 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6636 BasicBlock *ExitingBlock) { 6637 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6638 assert(L->isLoopExiting(ExitingBlock) && 6639 "Exiting block must actually branch out of the loop!"); 6640 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6641 if (ExitCount == getCouldNotCompute()) 6642 return 1; 6643 6644 // Get the trip count from the BE count by adding 1. 6645 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6646 6647 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6648 if (!TC) 6649 // Attempt to factor more general cases. Returns the greatest power of 6650 // two divisor. If overflow happens, the trip count expression is still 6651 // divisible by the greatest power of 2 divisor returned. 6652 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6653 6654 ConstantInt *Result = TC->getValue(); 6655 6656 // Guard against huge trip counts (this requires checking 6657 // for zero to handle the case where the trip count == -1 and the 6658 // addition wraps). 6659 if (!Result || Result->getValue().getActiveBits() > 32 || 6660 Result->getValue().getActiveBits() == 0) 6661 return 1; 6662 6663 return (unsigned)Result->getZExtValue(); 6664 } 6665 6666 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6667 BasicBlock *ExitingBlock, 6668 ExitCountKind Kind) { 6669 switch (Kind) { 6670 case Exact: 6671 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6672 case ConstantMaximum: 6673 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6674 }; 6675 llvm_unreachable("Invalid ExitCountKind!"); 6676 } 6677 6678 const SCEV * 6679 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6680 SCEVUnionPredicate &Preds) { 6681 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6682 } 6683 6684 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6685 ExitCountKind Kind) { 6686 switch (Kind) { 6687 case Exact: 6688 return getBackedgeTakenInfo(L).getExact(L, this); 6689 case ConstantMaximum: 6690 return getBackedgeTakenInfo(L).getMax(this); 6691 }; 6692 llvm_unreachable("Invalid ExitCountKind!"); 6693 } 6694 6695 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6696 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6697 } 6698 6699 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6700 static void 6701 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6702 BasicBlock *Header = L->getHeader(); 6703 6704 // Push all Loop-header PHIs onto the Worklist stack. 6705 for (PHINode &PN : Header->phis()) 6706 Worklist.push_back(&PN); 6707 } 6708 6709 const ScalarEvolution::BackedgeTakenInfo & 6710 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6711 auto &BTI = getBackedgeTakenInfo(L); 6712 if (BTI.hasFullInfo()) 6713 return BTI; 6714 6715 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6716 6717 if (!Pair.second) 6718 return Pair.first->second; 6719 6720 BackedgeTakenInfo Result = 6721 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6722 6723 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6724 } 6725 6726 const ScalarEvolution::BackedgeTakenInfo & 6727 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6728 // Initially insert an invalid entry for this loop. If the insertion 6729 // succeeds, proceed to actually compute a backedge-taken count and 6730 // update the value. The temporary CouldNotCompute value tells SCEV 6731 // code elsewhere that it shouldn't attempt to request a new 6732 // backedge-taken count, which could result in infinite recursion. 6733 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6734 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6735 if (!Pair.second) 6736 return Pair.first->second; 6737 6738 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6739 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6740 // must be cleared in this scope. 6741 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6742 6743 // In product build, there are no usage of statistic. 6744 (void)NumTripCountsComputed; 6745 (void)NumTripCountsNotComputed; 6746 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6747 const SCEV *BEExact = Result.getExact(L, this); 6748 if (BEExact != getCouldNotCompute()) { 6749 assert(isLoopInvariant(BEExact, L) && 6750 isLoopInvariant(Result.getMax(this), L) && 6751 "Computed backedge-taken count isn't loop invariant for loop!"); 6752 ++NumTripCountsComputed; 6753 } 6754 else if (Result.getMax(this) == getCouldNotCompute() && 6755 isa<PHINode>(L->getHeader()->begin())) { 6756 // Only count loops that have phi nodes as not being computable. 6757 ++NumTripCountsNotComputed; 6758 } 6759 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6760 6761 // Now that we know more about the trip count for this loop, forget any 6762 // existing SCEV values for PHI nodes in this loop since they are only 6763 // conservative estimates made without the benefit of trip count 6764 // information. This is similar to the code in forgetLoop, except that 6765 // it handles SCEVUnknown PHI nodes specially. 6766 if (Result.hasAnyInfo()) { 6767 SmallVector<Instruction *, 16> Worklist; 6768 PushLoopPHIs(L, Worklist); 6769 6770 SmallPtrSet<Instruction *, 8> Discovered; 6771 while (!Worklist.empty()) { 6772 Instruction *I = Worklist.pop_back_val(); 6773 6774 ValueExprMapType::iterator It = 6775 ValueExprMap.find_as(static_cast<Value *>(I)); 6776 if (It != ValueExprMap.end()) { 6777 const SCEV *Old = It->second; 6778 6779 // SCEVUnknown for a PHI either means that it has an unrecognized 6780 // structure, or it's a PHI that's in the progress of being computed 6781 // by createNodeForPHI. In the former case, additional loop trip 6782 // count information isn't going to change anything. In the later 6783 // case, createNodeForPHI will perform the necessary updates on its 6784 // own when it gets to that point. 6785 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6786 eraseValueFromMap(It->first); 6787 forgetMemoizedResults(Old); 6788 } 6789 if (PHINode *PN = dyn_cast<PHINode>(I)) 6790 ConstantEvolutionLoopExitValue.erase(PN); 6791 } 6792 6793 // Since we don't need to invalidate anything for correctness and we're 6794 // only invalidating to make SCEV's results more precise, we get to stop 6795 // early to avoid invalidating too much. This is especially important in 6796 // cases like: 6797 // 6798 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6799 // loop0: 6800 // %pn0 = phi 6801 // ... 6802 // loop1: 6803 // %pn1 = phi 6804 // ... 6805 // 6806 // where both loop0 and loop1's backedge taken count uses the SCEV 6807 // expression for %v. If we don't have the early stop below then in cases 6808 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6809 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6810 // count for loop1, effectively nullifying SCEV's trip count cache. 6811 for (auto *U : I->users()) 6812 if (auto *I = dyn_cast<Instruction>(U)) { 6813 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6814 if (LoopForUser && L->contains(LoopForUser) && 6815 Discovered.insert(I).second) 6816 Worklist.push_back(I); 6817 } 6818 } 6819 } 6820 6821 // Re-lookup the insert position, since the call to 6822 // computeBackedgeTakenCount above could result in a 6823 // recusive call to getBackedgeTakenInfo (on a different 6824 // loop), which would invalidate the iterator computed 6825 // earlier. 6826 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6827 } 6828 6829 void ScalarEvolution::forgetAllLoops() { 6830 // This method is intended to forget all info about loops. It should 6831 // invalidate caches as if the following happened: 6832 // - The trip counts of all loops have changed arbitrarily 6833 // - Every llvm::Value has been updated in place to produce a different 6834 // result. 6835 BackedgeTakenCounts.clear(); 6836 PredicatedBackedgeTakenCounts.clear(); 6837 LoopPropertiesCache.clear(); 6838 ConstantEvolutionLoopExitValue.clear(); 6839 ValueExprMap.clear(); 6840 ValuesAtScopes.clear(); 6841 LoopDispositions.clear(); 6842 BlockDispositions.clear(); 6843 UnsignedRanges.clear(); 6844 SignedRanges.clear(); 6845 ExprValueMap.clear(); 6846 HasRecMap.clear(); 6847 MinTrailingZerosCache.clear(); 6848 PredicatedSCEVRewrites.clear(); 6849 } 6850 6851 void ScalarEvolution::forgetLoop(const Loop *L) { 6852 // Drop any stored trip count value. 6853 auto RemoveLoopFromBackedgeMap = 6854 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6855 auto BTCPos = Map.find(L); 6856 if (BTCPos != Map.end()) { 6857 BTCPos->second.clear(); 6858 Map.erase(BTCPos); 6859 } 6860 }; 6861 6862 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6863 SmallVector<Instruction *, 32> Worklist; 6864 SmallPtrSet<Instruction *, 16> Visited; 6865 6866 // Iterate over all the loops and sub-loops to drop SCEV information. 6867 while (!LoopWorklist.empty()) { 6868 auto *CurrL = LoopWorklist.pop_back_val(); 6869 6870 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6871 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6872 6873 // Drop information about predicated SCEV rewrites for this loop. 6874 for (auto I = PredicatedSCEVRewrites.begin(); 6875 I != PredicatedSCEVRewrites.end();) { 6876 std::pair<const SCEV *, const Loop *> Entry = I->first; 6877 if (Entry.second == CurrL) 6878 PredicatedSCEVRewrites.erase(I++); 6879 else 6880 ++I; 6881 } 6882 6883 auto LoopUsersItr = LoopUsers.find(CurrL); 6884 if (LoopUsersItr != LoopUsers.end()) { 6885 for (auto *S : LoopUsersItr->second) 6886 forgetMemoizedResults(S); 6887 LoopUsers.erase(LoopUsersItr); 6888 } 6889 6890 // Drop information about expressions based on loop-header PHIs. 6891 PushLoopPHIs(CurrL, Worklist); 6892 6893 while (!Worklist.empty()) { 6894 Instruction *I = Worklist.pop_back_val(); 6895 if (!Visited.insert(I).second) 6896 continue; 6897 6898 ValueExprMapType::iterator It = 6899 ValueExprMap.find_as(static_cast<Value *>(I)); 6900 if (It != ValueExprMap.end()) { 6901 eraseValueFromMap(It->first); 6902 forgetMemoizedResults(It->second); 6903 if (PHINode *PN = dyn_cast<PHINode>(I)) 6904 ConstantEvolutionLoopExitValue.erase(PN); 6905 } 6906 6907 PushDefUseChildren(I, Worklist); 6908 } 6909 6910 LoopPropertiesCache.erase(CurrL); 6911 // Forget all contained loops too, to avoid dangling entries in the 6912 // ValuesAtScopes map. 6913 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6914 } 6915 } 6916 6917 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6918 while (Loop *Parent = L->getParentLoop()) 6919 L = Parent; 6920 forgetLoop(L); 6921 } 6922 6923 void ScalarEvolution::forgetValue(Value *V) { 6924 Instruction *I = dyn_cast<Instruction>(V); 6925 if (!I) return; 6926 6927 // Drop information about expressions based on loop-header PHIs. 6928 SmallVector<Instruction *, 16> Worklist; 6929 Worklist.push_back(I); 6930 6931 SmallPtrSet<Instruction *, 8> Visited; 6932 while (!Worklist.empty()) { 6933 I = Worklist.pop_back_val(); 6934 if (!Visited.insert(I).second) 6935 continue; 6936 6937 ValueExprMapType::iterator It = 6938 ValueExprMap.find_as(static_cast<Value *>(I)); 6939 if (It != ValueExprMap.end()) { 6940 eraseValueFromMap(It->first); 6941 forgetMemoizedResults(It->second); 6942 if (PHINode *PN = dyn_cast<PHINode>(I)) 6943 ConstantEvolutionLoopExitValue.erase(PN); 6944 } 6945 6946 PushDefUseChildren(I, Worklist); 6947 } 6948 } 6949 6950 /// Get the exact loop backedge taken count considering all loop exits. A 6951 /// computable result can only be returned for loops with all exiting blocks 6952 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6953 /// is never skipped. This is a valid assumption as long as the loop exits via 6954 /// that test. For precise results, it is the caller's responsibility to specify 6955 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6956 const SCEV * 6957 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6958 SCEVUnionPredicate *Preds) const { 6959 // If any exits were not computable, the loop is not computable. 6960 if (!isComplete() || ExitNotTaken.empty()) 6961 return SE->getCouldNotCompute(); 6962 6963 const BasicBlock *Latch = L->getLoopLatch(); 6964 // All exiting blocks we have collected must dominate the only backedge. 6965 if (!Latch) 6966 return SE->getCouldNotCompute(); 6967 6968 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6969 // count is simply a minimum out of all these calculated exit counts. 6970 SmallVector<const SCEV *, 2> Ops; 6971 for (auto &ENT : ExitNotTaken) { 6972 const SCEV *BECount = ENT.ExactNotTaken; 6973 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6974 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6975 "We should only have known counts for exiting blocks that dominate " 6976 "latch!"); 6977 6978 Ops.push_back(BECount); 6979 6980 if (Preds && !ENT.hasAlwaysTruePredicate()) 6981 Preds->add(ENT.Predicate.get()); 6982 6983 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6984 "Predicate should be always true!"); 6985 } 6986 6987 return SE->getUMinFromMismatchedTypes(Ops); 6988 } 6989 6990 /// Get the exact not taken count for this loop exit. 6991 const SCEV * 6992 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6993 ScalarEvolution *SE) const { 6994 for (auto &ENT : ExitNotTaken) 6995 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6996 return ENT.ExactNotTaken; 6997 6998 return SE->getCouldNotCompute(); 6999 } 7000 7001 const SCEV * 7002 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 7003 ScalarEvolution *SE) const { 7004 for (auto &ENT : ExitNotTaken) 7005 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7006 return ENT.MaxNotTaken; 7007 7008 return SE->getCouldNotCompute(); 7009 } 7010 7011 /// getMax - Get the max backedge taken count for the loop. 7012 const SCEV * 7013 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 7014 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7015 return !ENT.hasAlwaysTruePredicate(); 7016 }; 7017 7018 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 7019 return SE->getCouldNotCompute(); 7020 7021 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 7022 "No point in having a non-constant max backedge taken count!"); 7023 return getMax(); 7024 } 7025 7026 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 7027 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7028 return !ENT.hasAlwaysTruePredicate(); 7029 }; 7030 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7031 } 7032 7033 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7034 ScalarEvolution *SE) const { 7035 if (getMax() && getMax() != SE->getCouldNotCompute() && 7036 SE->hasOperand(getMax(), S)) 7037 return true; 7038 7039 for (auto &ENT : ExitNotTaken) 7040 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7041 SE->hasOperand(ENT.ExactNotTaken, S)) 7042 return true; 7043 7044 return false; 7045 } 7046 7047 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7048 : ExactNotTaken(E), MaxNotTaken(E) { 7049 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7050 isa<SCEVConstant>(MaxNotTaken)) && 7051 "No point in having a non-constant max backedge taken count!"); 7052 } 7053 7054 ScalarEvolution::ExitLimit::ExitLimit( 7055 const SCEV *E, const SCEV *M, bool MaxOrZero, 7056 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7057 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7058 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7059 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7060 "Exact is not allowed to be less precise than Max"); 7061 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7062 isa<SCEVConstant>(MaxNotTaken)) && 7063 "No point in having a non-constant max backedge taken count!"); 7064 for (auto *PredSet : PredSetList) 7065 for (auto *P : *PredSet) 7066 addPredicate(P); 7067 } 7068 7069 ScalarEvolution::ExitLimit::ExitLimit( 7070 const SCEV *E, const SCEV *M, bool MaxOrZero, 7071 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7072 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7073 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7074 isa<SCEVConstant>(MaxNotTaken)) && 7075 "No point in having a non-constant max backedge taken count!"); 7076 } 7077 7078 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7079 bool MaxOrZero) 7080 : ExitLimit(E, M, MaxOrZero, None) { 7081 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7082 isa<SCEVConstant>(MaxNotTaken)) && 7083 "No point in having a non-constant max backedge taken count!"); 7084 } 7085 7086 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7087 /// computable exit into a persistent ExitNotTakenInfo array. 7088 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7089 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7090 ExitCounts, 7091 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7092 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7093 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7094 7095 ExitNotTaken.reserve(ExitCounts.size()); 7096 std::transform( 7097 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7098 [&](const EdgeExitInfo &EEI) { 7099 BasicBlock *ExitBB = EEI.first; 7100 const ExitLimit &EL = EEI.second; 7101 if (EL.Predicates.empty()) 7102 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7103 nullptr); 7104 7105 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7106 for (auto *Pred : EL.Predicates) 7107 Predicate->add(Pred); 7108 7109 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7110 std::move(Predicate)); 7111 }); 7112 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7113 "No point in having a non-constant max backedge taken count!"); 7114 } 7115 7116 /// Invalidate this result and free the ExitNotTakenInfo array. 7117 void ScalarEvolution::BackedgeTakenInfo::clear() { 7118 ExitNotTaken.clear(); 7119 } 7120 7121 /// Compute the number of times the backedge of the specified loop will execute. 7122 ScalarEvolution::BackedgeTakenInfo 7123 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7124 bool AllowPredicates) { 7125 SmallVector<BasicBlock *, 8> ExitingBlocks; 7126 L->getExitingBlocks(ExitingBlocks); 7127 7128 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7129 7130 SmallVector<EdgeExitInfo, 4> ExitCounts; 7131 bool CouldComputeBECount = true; 7132 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7133 const SCEV *MustExitMaxBECount = nullptr; 7134 const SCEV *MayExitMaxBECount = nullptr; 7135 bool MustExitMaxOrZero = false; 7136 7137 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7138 // and compute maxBECount. 7139 // Do a union of all the predicates here. 7140 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7141 BasicBlock *ExitBB = ExitingBlocks[i]; 7142 7143 // We canonicalize untaken exits to br (constant), ignore them so that 7144 // proving an exit untaken doesn't negatively impact our ability to reason 7145 // about the loop as whole. 7146 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7147 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7148 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7149 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7150 continue; 7151 } 7152 7153 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7154 7155 assert((AllowPredicates || EL.Predicates.empty()) && 7156 "Predicated exit limit when predicates are not allowed!"); 7157 7158 // 1. For each exit that can be computed, add an entry to ExitCounts. 7159 // CouldComputeBECount is true only if all exits can be computed. 7160 if (EL.ExactNotTaken == getCouldNotCompute()) 7161 // We couldn't compute an exact value for this exit, so 7162 // we won't be able to compute an exact value for the loop. 7163 CouldComputeBECount = false; 7164 else 7165 ExitCounts.emplace_back(ExitBB, EL); 7166 7167 // 2. Derive the loop's MaxBECount from each exit's max number of 7168 // non-exiting iterations. Partition the loop exits into two kinds: 7169 // LoopMustExits and LoopMayExits. 7170 // 7171 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7172 // is a LoopMayExit. If any computable LoopMustExit is found, then 7173 // MaxBECount is the minimum EL.MaxNotTaken of computable 7174 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7175 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7176 // computable EL.MaxNotTaken. 7177 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7178 DT.dominates(ExitBB, Latch)) { 7179 if (!MustExitMaxBECount) { 7180 MustExitMaxBECount = EL.MaxNotTaken; 7181 MustExitMaxOrZero = EL.MaxOrZero; 7182 } else { 7183 MustExitMaxBECount = 7184 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7185 } 7186 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7187 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7188 MayExitMaxBECount = EL.MaxNotTaken; 7189 else { 7190 MayExitMaxBECount = 7191 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7192 } 7193 } 7194 } 7195 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7196 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7197 // The loop backedge will be taken the maximum or zero times if there's 7198 // a single exit that must be taken the maximum or zero times. 7199 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7200 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7201 MaxBECount, MaxOrZero); 7202 } 7203 7204 ScalarEvolution::ExitLimit 7205 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7206 bool AllowPredicates) { 7207 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7208 // If our exiting block does not dominate the latch, then its connection with 7209 // loop's exit limit may be far from trivial. 7210 const BasicBlock *Latch = L->getLoopLatch(); 7211 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7212 return getCouldNotCompute(); 7213 7214 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7215 Instruction *Term = ExitingBlock->getTerminator(); 7216 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7217 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7218 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7219 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7220 "It should have one successor in loop and one exit block!"); 7221 // Proceed to the next level to examine the exit condition expression. 7222 return computeExitLimitFromCond( 7223 L, BI->getCondition(), ExitIfTrue, 7224 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7225 } 7226 7227 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7228 // For switch, make sure that there is a single exit from the loop. 7229 BasicBlock *Exit = nullptr; 7230 for (auto *SBB : successors(ExitingBlock)) 7231 if (!L->contains(SBB)) { 7232 if (Exit) // Multiple exit successors. 7233 return getCouldNotCompute(); 7234 Exit = SBB; 7235 } 7236 assert(Exit && "Exiting block must have at least one exit"); 7237 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7238 /*ControlsExit=*/IsOnlyExit); 7239 } 7240 7241 return getCouldNotCompute(); 7242 } 7243 7244 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7245 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7246 bool ControlsExit, bool AllowPredicates) { 7247 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7248 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7249 ControlsExit, AllowPredicates); 7250 } 7251 7252 Optional<ScalarEvolution::ExitLimit> 7253 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7254 bool ExitIfTrue, bool ControlsExit, 7255 bool AllowPredicates) { 7256 (void)this->L; 7257 (void)this->ExitIfTrue; 7258 (void)this->AllowPredicates; 7259 7260 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7261 this->AllowPredicates == AllowPredicates && 7262 "Variance in assumed invariant key components!"); 7263 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7264 if (Itr == TripCountMap.end()) 7265 return None; 7266 return Itr->second; 7267 } 7268 7269 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7270 bool ExitIfTrue, 7271 bool ControlsExit, 7272 bool AllowPredicates, 7273 const ExitLimit &EL) { 7274 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7275 this->AllowPredicates == AllowPredicates && 7276 "Variance in assumed invariant key components!"); 7277 7278 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7279 assert(InsertResult.second && "Expected successful insertion!"); 7280 (void)InsertResult; 7281 (void)ExitIfTrue; 7282 } 7283 7284 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7285 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7286 bool ControlsExit, bool AllowPredicates) { 7287 7288 if (auto MaybeEL = 7289 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7290 return *MaybeEL; 7291 7292 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7293 ControlsExit, AllowPredicates); 7294 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7295 return EL; 7296 } 7297 7298 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7299 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7300 bool ControlsExit, bool AllowPredicates) { 7301 // Check if the controlling expression for this loop is an And or Or. 7302 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7303 if (BO->getOpcode() == Instruction::And) { 7304 // Recurse on the operands of the and. 7305 bool EitherMayExit = !ExitIfTrue; 7306 ExitLimit EL0 = computeExitLimitFromCondCached( 7307 Cache, L, BO->getOperand(0), ExitIfTrue, 7308 ControlsExit && !EitherMayExit, AllowPredicates); 7309 ExitLimit EL1 = computeExitLimitFromCondCached( 7310 Cache, L, BO->getOperand(1), ExitIfTrue, 7311 ControlsExit && !EitherMayExit, AllowPredicates); 7312 // Be robust against unsimplified IR for the form "and i1 X, true" 7313 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7314 return CI->isOne() ? EL0 : EL1; 7315 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7316 return CI->isOne() ? EL1 : EL0; 7317 const SCEV *BECount = getCouldNotCompute(); 7318 const SCEV *MaxBECount = getCouldNotCompute(); 7319 if (EitherMayExit) { 7320 // Both conditions must be true for the loop to continue executing. 7321 // Choose the less conservative count. 7322 if (EL0.ExactNotTaken == getCouldNotCompute() || 7323 EL1.ExactNotTaken == getCouldNotCompute()) 7324 BECount = getCouldNotCompute(); 7325 else 7326 BECount = 7327 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7328 if (EL0.MaxNotTaken == getCouldNotCompute()) 7329 MaxBECount = EL1.MaxNotTaken; 7330 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7331 MaxBECount = EL0.MaxNotTaken; 7332 else 7333 MaxBECount = 7334 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7335 } else { 7336 // Both conditions must be true at the same time for the loop to exit. 7337 // For now, be conservative. 7338 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7339 MaxBECount = EL0.MaxNotTaken; 7340 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7341 BECount = EL0.ExactNotTaken; 7342 } 7343 7344 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7345 // to be more aggressive when computing BECount than when computing 7346 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7347 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7348 // to not. 7349 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7350 !isa<SCEVCouldNotCompute>(BECount)) 7351 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7352 7353 return ExitLimit(BECount, MaxBECount, false, 7354 {&EL0.Predicates, &EL1.Predicates}); 7355 } 7356 if (BO->getOpcode() == Instruction::Or) { 7357 // Recurse on the operands of the or. 7358 bool EitherMayExit = ExitIfTrue; 7359 ExitLimit EL0 = computeExitLimitFromCondCached( 7360 Cache, L, BO->getOperand(0), ExitIfTrue, 7361 ControlsExit && !EitherMayExit, AllowPredicates); 7362 ExitLimit EL1 = computeExitLimitFromCondCached( 7363 Cache, L, BO->getOperand(1), ExitIfTrue, 7364 ControlsExit && !EitherMayExit, AllowPredicates); 7365 // Be robust against unsimplified IR for the form "or i1 X, true" 7366 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7367 return CI->isZero() ? EL0 : EL1; 7368 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7369 return CI->isZero() ? EL1 : EL0; 7370 const SCEV *BECount = getCouldNotCompute(); 7371 const SCEV *MaxBECount = getCouldNotCompute(); 7372 if (EitherMayExit) { 7373 // Both conditions must be false for the loop to continue executing. 7374 // Choose the less conservative count. 7375 if (EL0.ExactNotTaken == getCouldNotCompute() || 7376 EL1.ExactNotTaken == getCouldNotCompute()) 7377 BECount = getCouldNotCompute(); 7378 else 7379 BECount = 7380 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7381 if (EL0.MaxNotTaken == getCouldNotCompute()) 7382 MaxBECount = EL1.MaxNotTaken; 7383 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7384 MaxBECount = EL0.MaxNotTaken; 7385 else 7386 MaxBECount = 7387 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7388 } else { 7389 // Both conditions must be false at the same time for the loop to exit. 7390 // For now, be conservative. 7391 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7392 MaxBECount = EL0.MaxNotTaken; 7393 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7394 BECount = EL0.ExactNotTaken; 7395 } 7396 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7397 // to be more aggressive when computing BECount than when computing 7398 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7399 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7400 // to not. 7401 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7402 !isa<SCEVCouldNotCompute>(BECount)) 7403 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7404 7405 return ExitLimit(BECount, MaxBECount, false, 7406 {&EL0.Predicates, &EL1.Predicates}); 7407 } 7408 } 7409 7410 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7411 // Proceed to the next level to examine the icmp. 7412 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7413 ExitLimit EL = 7414 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7415 if (EL.hasFullInfo() || !AllowPredicates) 7416 return EL; 7417 7418 // Try again, but use SCEV predicates this time. 7419 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7420 /*AllowPredicates=*/true); 7421 } 7422 7423 // Check for a constant condition. These are normally stripped out by 7424 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7425 // preserve the CFG and is temporarily leaving constant conditions 7426 // in place. 7427 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7428 if (ExitIfTrue == !CI->getZExtValue()) 7429 // The backedge is always taken. 7430 return getCouldNotCompute(); 7431 else 7432 // The backedge is never taken. 7433 return getZero(CI->getType()); 7434 } 7435 7436 // If it's not an integer or pointer comparison then compute it the hard way. 7437 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7438 } 7439 7440 ScalarEvolution::ExitLimit 7441 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7442 ICmpInst *ExitCond, 7443 bool ExitIfTrue, 7444 bool ControlsExit, 7445 bool AllowPredicates) { 7446 // If the condition was exit on true, convert the condition to exit on false 7447 ICmpInst::Predicate Pred; 7448 if (!ExitIfTrue) 7449 Pred = ExitCond->getPredicate(); 7450 else 7451 Pred = ExitCond->getInversePredicate(); 7452 const ICmpInst::Predicate OriginalPred = Pred; 7453 7454 // Handle common loops like: for (X = "string"; *X; ++X) 7455 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7456 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7457 ExitLimit ItCnt = 7458 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7459 if (ItCnt.hasAnyInfo()) 7460 return ItCnt; 7461 } 7462 7463 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7464 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7465 7466 // Try to evaluate any dependencies out of the loop. 7467 LHS = getSCEVAtScope(LHS, L); 7468 RHS = getSCEVAtScope(RHS, L); 7469 7470 // At this point, we would like to compute how many iterations of the 7471 // loop the predicate will return true for these inputs. 7472 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7473 // If there is a loop-invariant, force it into the RHS. 7474 std::swap(LHS, RHS); 7475 Pred = ICmpInst::getSwappedPredicate(Pred); 7476 } 7477 7478 // Simplify the operands before analyzing them. 7479 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7480 7481 // If we have a comparison of a chrec against a constant, try to use value 7482 // ranges to answer this query. 7483 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7484 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7485 if (AddRec->getLoop() == L) { 7486 // Form the constant range. 7487 ConstantRange CompRange = 7488 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7489 7490 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7491 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7492 } 7493 7494 switch (Pred) { 7495 case ICmpInst::ICMP_NE: { // while (X != Y) 7496 // Convert to: while (X-Y != 0) 7497 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7498 AllowPredicates); 7499 if (EL.hasAnyInfo()) return EL; 7500 break; 7501 } 7502 case ICmpInst::ICMP_EQ: { // while (X == Y) 7503 // Convert to: while (X-Y == 0) 7504 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7505 if (EL.hasAnyInfo()) return EL; 7506 break; 7507 } 7508 case ICmpInst::ICMP_SLT: 7509 case ICmpInst::ICMP_ULT: { // while (X < Y) 7510 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7511 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7512 AllowPredicates); 7513 if (EL.hasAnyInfo()) return EL; 7514 break; 7515 } 7516 case ICmpInst::ICMP_SGT: 7517 case ICmpInst::ICMP_UGT: { // while (X > Y) 7518 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7519 ExitLimit EL = 7520 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7521 AllowPredicates); 7522 if (EL.hasAnyInfo()) return EL; 7523 break; 7524 } 7525 default: 7526 break; 7527 } 7528 7529 auto *ExhaustiveCount = 7530 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7531 7532 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7533 return ExhaustiveCount; 7534 7535 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7536 ExitCond->getOperand(1), L, OriginalPred); 7537 } 7538 7539 ScalarEvolution::ExitLimit 7540 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7541 SwitchInst *Switch, 7542 BasicBlock *ExitingBlock, 7543 bool ControlsExit) { 7544 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7545 7546 // Give up if the exit is the default dest of a switch. 7547 if (Switch->getDefaultDest() == ExitingBlock) 7548 return getCouldNotCompute(); 7549 7550 assert(L->contains(Switch->getDefaultDest()) && 7551 "Default case must not exit the loop!"); 7552 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7553 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7554 7555 // while (X != Y) --> while (X-Y != 0) 7556 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7557 if (EL.hasAnyInfo()) 7558 return EL; 7559 7560 return getCouldNotCompute(); 7561 } 7562 7563 static ConstantInt * 7564 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7565 ScalarEvolution &SE) { 7566 const SCEV *InVal = SE.getConstant(C); 7567 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7568 assert(isa<SCEVConstant>(Val) && 7569 "Evaluation of SCEV at constant didn't fold correctly?"); 7570 return cast<SCEVConstant>(Val)->getValue(); 7571 } 7572 7573 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7574 /// compute the backedge execution count. 7575 ScalarEvolution::ExitLimit 7576 ScalarEvolution::computeLoadConstantCompareExitLimit( 7577 LoadInst *LI, 7578 Constant *RHS, 7579 const Loop *L, 7580 ICmpInst::Predicate predicate) { 7581 if (LI->isVolatile()) return getCouldNotCompute(); 7582 7583 // Check to see if the loaded pointer is a getelementptr of a global. 7584 // TODO: Use SCEV instead of manually grubbing with GEPs. 7585 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7586 if (!GEP) return getCouldNotCompute(); 7587 7588 // Make sure that it is really a constant global we are gepping, with an 7589 // initializer, and make sure the first IDX is really 0. 7590 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7591 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7592 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7593 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7594 return getCouldNotCompute(); 7595 7596 // Okay, we allow one non-constant index into the GEP instruction. 7597 Value *VarIdx = nullptr; 7598 std::vector<Constant*> Indexes; 7599 unsigned VarIdxNum = 0; 7600 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7601 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7602 Indexes.push_back(CI); 7603 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7604 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7605 VarIdx = GEP->getOperand(i); 7606 VarIdxNum = i-2; 7607 Indexes.push_back(nullptr); 7608 } 7609 7610 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7611 if (!VarIdx) 7612 return getCouldNotCompute(); 7613 7614 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7615 // Check to see if X is a loop variant variable value now. 7616 const SCEV *Idx = getSCEV(VarIdx); 7617 Idx = getSCEVAtScope(Idx, L); 7618 7619 // We can only recognize very limited forms of loop index expressions, in 7620 // particular, only affine AddRec's like {C1,+,C2}. 7621 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7622 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7623 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7624 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7625 return getCouldNotCompute(); 7626 7627 unsigned MaxSteps = MaxBruteForceIterations; 7628 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7629 ConstantInt *ItCst = ConstantInt::get( 7630 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7631 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7632 7633 // Form the GEP offset. 7634 Indexes[VarIdxNum] = Val; 7635 7636 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7637 Indexes); 7638 if (!Result) break; // Cannot compute! 7639 7640 // Evaluate the condition for this iteration. 7641 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7642 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7643 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7644 ++NumArrayLenItCounts; 7645 return getConstant(ItCst); // Found terminating iteration! 7646 } 7647 } 7648 return getCouldNotCompute(); 7649 } 7650 7651 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7652 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7653 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7654 if (!RHS) 7655 return getCouldNotCompute(); 7656 7657 const BasicBlock *Latch = L->getLoopLatch(); 7658 if (!Latch) 7659 return getCouldNotCompute(); 7660 7661 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7662 if (!Predecessor) 7663 return getCouldNotCompute(); 7664 7665 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7666 // Return LHS in OutLHS and shift_opt in OutOpCode. 7667 auto MatchPositiveShift = 7668 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7669 7670 using namespace PatternMatch; 7671 7672 ConstantInt *ShiftAmt; 7673 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7674 OutOpCode = Instruction::LShr; 7675 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7676 OutOpCode = Instruction::AShr; 7677 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7678 OutOpCode = Instruction::Shl; 7679 else 7680 return false; 7681 7682 return ShiftAmt->getValue().isStrictlyPositive(); 7683 }; 7684 7685 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7686 // 7687 // loop: 7688 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7689 // %iv.shifted = lshr i32 %iv, <positive constant> 7690 // 7691 // Return true on a successful match. Return the corresponding PHI node (%iv 7692 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7693 auto MatchShiftRecurrence = 7694 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7695 Optional<Instruction::BinaryOps> PostShiftOpCode; 7696 7697 { 7698 Instruction::BinaryOps OpC; 7699 Value *V; 7700 7701 // If we encounter a shift instruction, "peel off" the shift operation, 7702 // and remember that we did so. Later when we inspect %iv's backedge 7703 // value, we will make sure that the backedge value uses the same 7704 // operation. 7705 // 7706 // Note: the peeled shift operation does not have to be the same 7707 // instruction as the one feeding into the PHI's backedge value. We only 7708 // really care about it being the same *kind* of shift instruction -- 7709 // that's all that is required for our later inferences to hold. 7710 if (MatchPositiveShift(LHS, V, OpC)) { 7711 PostShiftOpCode = OpC; 7712 LHS = V; 7713 } 7714 } 7715 7716 PNOut = dyn_cast<PHINode>(LHS); 7717 if (!PNOut || PNOut->getParent() != L->getHeader()) 7718 return false; 7719 7720 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7721 Value *OpLHS; 7722 7723 return 7724 // The backedge value for the PHI node must be a shift by a positive 7725 // amount 7726 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7727 7728 // of the PHI node itself 7729 OpLHS == PNOut && 7730 7731 // and the kind of shift should be match the kind of shift we peeled 7732 // off, if any. 7733 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7734 }; 7735 7736 PHINode *PN; 7737 Instruction::BinaryOps OpCode; 7738 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7739 return getCouldNotCompute(); 7740 7741 const DataLayout &DL = getDataLayout(); 7742 7743 // The key rationale for this optimization is that for some kinds of shift 7744 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7745 // within a finite number of iterations. If the condition guarding the 7746 // backedge (in the sense that the backedge is taken if the condition is true) 7747 // is false for the value the shift recurrence stabilizes to, then we know 7748 // that the backedge is taken only a finite number of times. 7749 7750 ConstantInt *StableValue = nullptr; 7751 switch (OpCode) { 7752 default: 7753 llvm_unreachable("Impossible case!"); 7754 7755 case Instruction::AShr: { 7756 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7757 // bitwidth(K) iterations. 7758 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7759 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7760 Predecessor->getTerminator(), &DT); 7761 auto *Ty = cast<IntegerType>(RHS->getType()); 7762 if (Known.isNonNegative()) 7763 StableValue = ConstantInt::get(Ty, 0); 7764 else if (Known.isNegative()) 7765 StableValue = ConstantInt::get(Ty, -1, true); 7766 else 7767 return getCouldNotCompute(); 7768 7769 break; 7770 } 7771 case Instruction::LShr: 7772 case Instruction::Shl: 7773 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7774 // stabilize to 0 in at most bitwidth(K) iterations. 7775 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7776 break; 7777 } 7778 7779 auto *Result = 7780 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7781 assert(Result->getType()->isIntegerTy(1) && 7782 "Otherwise cannot be an operand to a branch instruction"); 7783 7784 if (Result->isZeroValue()) { 7785 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7786 const SCEV *UpperBound = 7787 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7788 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7789 } 7790 7791 return getCouldNotCompute(); 7792 } 7793 7794 /// Return true if we can constant fold an instruction of the specified type, 7795 /// assuming that all operands were constants. 7796 static bool CanConstantFold(const Instruction *I) { 7797 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7798 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7799 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7800 return true; 7801 7802 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7803 if (const Function *F = CI->getCalledFunction()) 7804 return canConstantFoldCallTo(CI, F); 7805 return false; 7806 } 7807 7808 /// Determine whether this instruction can constant evolve within this loop 7809 /// assuming its operands can all constant evolve. 7810 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7811 // An instruction outside of the loop can't be derived from a loop PHI. 7812 if (!L->contains(I)) return false; 7813 7814 if (isa<PHINode>(I)) { 7815 // We don't currently keep track of the control flow needed to evaluate 7816 // PHIs, so we cannot handle PHIs inside of loops. 7817 return L->getHeader() == I->getParent(); 7818 } 7819 7820 // If we won't be able to constant fold this expression even if the operands 7821 // are constants, bail early. 7822 return CanConstantFold(I); 7823 } 7824 7825 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7826 /// recursing through each instruction operand until reaching a loop header phi. 7827 static PHINode * 7828 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7829 DenseMap<Instruction *, PHINode *> &PHIMap, 7830 unsigned Depth) { 7831 if (Depth > MaxConstantEvolvingDepth) 7832 return nullptr; 7833 7834 // Otherwise, we can evaluate this instruction if all of its operands are 7835 // constant or derived from a PHI node themselves. 7836 PHINode *PHI = nullptr; 7837 for (Value *Op : UseInst->operands()) { 7838 if (isa<Constant>(Op)) continue; 7839 7840 Instruction *OpInst = dyn_cast<Instruction>(Op); 7841 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7842 7843 PHINode *P = dyn_cast<PHINode>(OpInst); 7844 if (!P) 7845 // If this operand is already visited, reuse the prior result. 7846 // We may have P != PHI if this is the deepest point at which the 7847 // inconsistent paths meet. 7848 P = PHIMap.lookup(OpInst); 7849 if (!P) { 7850 // Recurse and memoize the results, whether a phi is found or not. 7851 // This recursive call invalidates pointers into PHIMap. 7852 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7853 PHIMap[OpInst] = P; 7854 } 7855 if (!P) 7856 return nullptr; // Not evolving from PHI 7857 if (PHI && PHI != P) 7858 return nullptr; // Evolving from multiple different PHIs. 7859 PHI = P; 7860 } 7861 // This is a expression evolving from a constant PHI! 7862 return PHI; 7863 } 7864 7865 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7866 /// in the loop that V is derived from. We allow arbitrary operations along the 7867 /// way, but the operands of an operation must either be constants or a value 7868 /// derived from a constant PHI. If this expression does not fit with these 7869 /// constraints, return null. 7870 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7871 Instruction *I = dyn_cast<Instruction>(V); 7872 if (!I || !canConstantEvolve(I, L)) return nullptr; 7873 7874 if (PHINode *PN = dyn_cast<PHINode>(I)) 7875 return PN; 7876 7877 // Record non-constant instructions contained by the loop. 7878 DenseMap<Instruction *, PHINode *> PHIMap; 7879 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7880 } 7881 7882 /// EvaluateExpression - Given an expression that passes the 7883 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7884 /// in the loop has the value PHIVal. If we can't fold this expression for some 7885 /// reason, return null. 7886 static Constant *EvaluateExpression(Value *V, const Loop *L, 7887 DenseMap<Instruction *, Constant *> &Vals, 7888 const DataLayout &DL, 7889 const TargetLibraryInfo *TLI) { 7890 // Convenient constant check, but redundant for recursive calls. 7891 if (Constant *C = dyn_cast<Constant>(V)) return C; 7892 Instruction *I = dyn_cast<Instruction>(V); 7893 if (!I) return nullptr; 7894 7895 if (Constant *C = Vals.lookup(I)) return C; 7896 7897 // An instruction inside the loop depends on a value outside the loop that we 7898 // weren't given a mapping for, or a value such as a call inside the loop. 7899 if (!canConstantEvolve(I, L)) return nullptr; 7900 7901 // An unmapped PHI can be due to a branch or another loop inside this loop, 7902 // or due to this not being the initial iteration through a loop where we 7903 // couldn't compute the evolution of this particular PHI last time. 7904 if (isa<PHINode>(I)) return nullptr; 7905 7906 std::vector<Constant*> Operands(I->getNumOperands()); 7907 7908 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7909 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7910 if (!Operand) { 7911 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7912 if (!Operands[i]) return nullptr; 7913 continue; 7914 } 7915 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7916 Vals[Operand] = C; 7917 if (!C) return nullptr; 7918 Operands[i] = C; 7919 } 7920 7921 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7922 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7923 Operands[1], DL, TLI); 7924 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7925 if (!LI->isVolatile()) 7926 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7927 } 7928 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7929 } 7930 7931 7932 // If every incoming value to PN except the one for BB is a specific Constant, 7933 // return that, else return nullptr. 7934 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7935 Constant *IncomingVal = nullptr; 7936 7937 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7938 if (PN->getIncomingBlock(i) == BB) 7939 continue; 7940 7941 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7942 if (!CurrentVal) 7943 return nullptr; 7944 7945 if (IncomingVal != CurrentVal) { 7946 if (IncomingVal) 7947 return nullptr; 7948 IncomingVal = CurrentVal; 7949 } 7950 } 7951 7952 return IncomingVal; 7953 } 7954 7955 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7956 /// in the header of its containing loop, we know the loop executes a 7957 /// constant number of times, and the PHI node is just a recurrence 7958 /// involving constants, fold it. 7959 Constant * 7960 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7961 const APInt &BEs, 7962 const Loop *L) { 7963 auto I = ConstantEvolutionLoopExitValue.find(PN); 7964 if (I != ConstantEvolutionLoopExitValue.end()) 7965 return I->second; 7966 7967 if (BEs.ugt(MaxBruteForceIterations)) 7968 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7969 7970 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7971 7972 DenseMap<Instruction *, Constant *> CurrentIterVals; 7973 BasicBlock *Header = L->getHeader(); 7974 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7975 7976 BasicBlock *Latch = L->getLoopLatch(); 7977 if (!Latch) 7978 return nullptr; 7979 7980 for (PHINode &PHI : Header->phis()) { 7981 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7982 CurrentIterVals[&PHI] = StartCST; 7983 } 7984 if (!CurrentIterVals.count(PN)) 7985 return RetVal = nullptr; 7986 7987 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7988 7989 // Execute the loop symbolically to determine the exit value. 7990 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7991 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7992 7993 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7994 unsigned IterationNum = 0; 7995 const DataLayout &DL = getDataLayout(); 7996 for (; ; ++IterationNum) { 7997 if (IterationNum == NumIterations) 7998 return RetVal = CurrentIterVals[PN]; // Got exit value! 7999 8000 // Compute the value of the PHIs for the next iteration. 8001 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8002 DenseMap<Instruction *, Constant *> NextIterVals; 8003 Constant *NextPHI = 8004 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8005 if (!NextPHI) 8006 return nullptr; // Couldn't evaluate! 8007 NextIterVals[PN] = NextPHI; 8008 8009 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8010 8011 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8012 // cease to be able to evaluate one of them or if they stop evolving, 8013 // because that doesn't necessarily prevent us from computing PN. 8014 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8015 for (const auto &I : CurrentIterVals) { 8016 PHINode *PHI = dyn_cast<PHINode>(I.first); 8017 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8018 PHIsToCompute.emplace_back(PHI, I.second); 8019 } 8020 // We use two distinct loops because EvaluateExpression may invalidate any 8021 // iterators into CurrentIterVals. 8022 for (const auto &I : PHIsToCompute) { 8023 PHINode *PHI = I.first; 8024 Constant *&NextPHI = NextIterVals[PHI]; 8025 if (!NextPHI) { // Not already computed. 8026 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8027 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8028 } 8029 if (NextPHI != I.second) 8030 StoppedEvolving = false; 8031 } 8032 8033 // If all entries in CurrentIterVals == NextIterVals then we can stop 8034 // iterating, the loop can't continue to change. 8035 if (StoppedEvolving) 8036 return RetVal = CurrentIterVals[PN]; 8037 8038 CurrentIterVals.swap(NextIterVals); 8039 } 8040 } 8041 8042 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8043 Value *Cond, 8044 bool ExitWhen) { 8045 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8046 if (!PN) return getCouldNotCompute(); 8047 8048 // If the loop is canonicalized, the PHI will have exactly two entries. 8049 // That's the only form we support here. 8050 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8051 8052 DenseMap<Instruction *, Constant *> CurrentIterVals; 8053 BasicBlock *Header = L->getHeader(); 8054 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8055 8056 BasicBlock *Latch = L->getLoopLatch(); 8057 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8058 8059 for (PHINode &PHI : Header->phis()) { 8060 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8061 CurrentIterVals[&PHI] = StartCST; 8062 } 8063 if (!CurrentIterVals.count(PN)) 8064 return getCouldNotCompute(); 8065 8066 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8067 // the loop symbolically to determine when the condition gets a value of 8068 // "ExitWhen". 8069 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8070 const DataLayout &DL = getDataLayout(); 8071 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8072 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8073 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8074 8075 // Couldn't symbolically evaluate. 8076 if (!CondVal) return getCouldNotCompute(); 8077 8078 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8079 ++NumBruteForceTripCountsComputed; 8080 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8081 } 8082 8083 // Update all the PHI nodes for the next iteration. 8084 DenseMap<Instruction *, Constant *> NextIterVals; 8085 8086 // Create a list of which PHIs we need to compute. We want to do this before 8087 // calling EvaluateExpression on them because that may invalidate iterators 8088 // into CurrentIterVals. 8089 SmallVector<PHINode *, 8> PHIsToCompute; 8090 for (const auto &I : CurrentIterVals) { 8091 PHINode *PHI = dyn_cast<PHINode>(I.first); 8092 if (!PHI || PHI->getParent() != Header) continue; 8093 PHIsToCompute.push_back(PHI); 8094 } 8095 for (PHINode *PHI : PHIsToCompute) { 8096 Constant *&NextPHI = NextIterVals[PHI]; 8097 if (NextPHI) continue; // Already computed! 8098 8099 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8100 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8101 } 8102 CurrentIterVals.swap(NextIterVals); 8103 } 8104 8105 // Too many iterations were needed to evaluate. 8106 return getCouldNotCompute(); 8107 } 8108 8109 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8110 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8111 ValuesAtScopes[V]; 8112 // Check to see if we've folded this expression at this loop before. 8113 for (auto &LS : Values) 8114 if (LS.first == L) 8115 return LS.second ? LS.second : V; 8116 8117 Values.emplace_back(L, nullptr); 8118 8119 // Otherwise compute it. 8120 const SCEV *C = computeSCEVAtScope(V, L); 8121 for (auto &LS : reverse(ValuesAtScopes[V])) 8122 if (LS.first == L) { 8123 LS.second = C; 8124 break; 8125 } 8126 return C; 8127 } 8128 8129 /// This builds up a Constant using the ConstantExpr interface. That way, we 8130 /// will return Constants for objects which aren't represented by a 8131 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8132 /// Returns NULL if the SCEV isn't representable as a Constant. 8133 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8134 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8135 case scCouldNotCompute: 8136 case scAddRecExpr: 8137 break; 8138 case scConstant: 8139 return cast<SCEVConstant>(V)->getValue(); 8140 case scUnknown: 8141 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8142 case scSignExtend: { 8143 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8144 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8145 return ConstantExpr::getSExt(CastOp, SS->getType()); 8146 break; 8147 } 8148 case scZeroExtend: { 8149 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8150 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8151 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8152 break; 8153 } 8154 case scTruncate: { 8155 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8156 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8157 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8158 break; 8159 } 8160 case scAddExpr: { 8161 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8162 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8163 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8164 unsigned AS = PTy->getAddressSpace(); 8165 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8166 C = ConstantExpr::getBitCast(C, DestPtrTy); 8167 } 8168 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8169 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8170 if (!C2) return nullptr; 8171 8172 // First pointer! 8173 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8174 unsigned AS = C2->getType()->getPointerAddressSpace(); 8175 std::swap(C, C2); 8176 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8177 // The offsets have been converted to bytes. We can add bytes to an 8178 // i8* by GEP with the byte count in the first index. 8179 C = ConstantExpr::getBitCast(C, DestPtrTy); 8180 } 8181 8182 // Don't bother trying to sum two pointers. We probably can't 8183 // statically compute a load that results from it anyway. 8184 if (C2->getType()->isPointerTy()) 8185 return nullptr; 8186 8187 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8188 if (PTy->getElementType()->isStructTy()) 8189 C2 = ConstantExpr::getIntegerCast( 8190 C2, Type::getInt32Ty(C->getContext()), true); 8191 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8192 } else 8193 C = ConstantExpr::getAdd(C, C2); 8194 } 8195 return C; 8196 } 8197 break; 8198 } 8199 case scMulExpr: { 8200 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8201 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8202 // Don't bother with pointers at all. 8203 if (C->getType()->isPointerTy()) return nullptr; 8204 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8205 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8206 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8207 C = ConstantExpr::getMul(C, C2); 8208 } 8209 return C; 8210 } 8211 break; 8212 } 8213 case scUDivExpr: { 8214 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8215 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8216 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8217 if (LHS->getType() == RHS->getType()) 8218 return ConstantExpr::getUDiv(LHS, RHS); 8219 break; 8220 } 8221 case scSMaxExpr: 8222 case scUMaxExpr: 8223 case scSMinExpr: 8224 case scUMinExpr: 8225 break; // TODO: smax, umax, smin, umax. 8226 } 8227 return nullptr; 8228 } 8229 8230 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8231 if (isa<SCEVConstant>(V)) return V; 8232 8233 // If this instruction is evolved from a constant-evolving PHI, compute the 8234 // exit value from the loop without using SCEVs. 8235 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8236 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8237 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8238 const Loop *LI = this->LI[I->getParent()]; 8239 // Looking for loop exit value. 8240 if (LI && LI->getParentLoop() == L && 8241 PN->getParent() == LI->getHeader()) { 8242 // Okay, there is no closed form solution for the PHI node. Check 8243 // to see if the loop that contains it has a known backedge-taken 8244 // count. If so, we may be able to force computation of the exit 8245 // value. 8246 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8247 // This trivial case can show up in some degenerate cases where 8248 // the incoming IR has not yet been fully simplified. 8249 if (BackedgeTakenCount->isZero()) { 8250 Value *InitValue = nullptr; 8251 bool MultipleInitValues = false; 8252 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8253 if (!LI->contains(PN->getIncomingBlock(i))) { 8254 if (!InitValue) 8255 InitValue = PN->getIncomingValue(i); 8256 else if (InitValue != PN->getIncomingValue(i)) { 8257 MultipleInitValues = true; 8258 break; 8259 } 8260 } 8261 } 8262 if (!MultipleInitValues && InitValue) 8263 return getSCEV(InitValue); 8264 } 8265 // Do we have a loop invariant value flowing around the backedge 8266 // for a loop which must execute the backedge? 8267 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8268 isKnownPositive(BackedgeTakenCount) && 8269 PN->getNumIncomingValues() == 2) { 8270 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8271 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8272 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8273 return OnBackedge; 8274 } 8275 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8276 // Okay, we know how many times the containing loop executes. If 8277 // this is a constant evolving PHI node, get the final value at 8278 // the specified iteration number. 8279 Constant *RV = 8280 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8281 if (RV) return getSCEV(RV); 8282 } 8283 } 8284 8285 // If there is a single-input Phi, evaluate it at our scope. If we can 8286 // prove that this replacement does not break LCSSA form, use new value. 8287 if (PN->getNumOperands() == 1) { 8288 const SCEV *Input = getSCEV(PN->getOperand(0)); 8289 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8290 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8291 // for the simplest case just support constants. 8292 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8293 } 8294 } 8295 8296 // Okay, this is an expression that we cannot symbolically evaluate 8297 // into a SCEV. Check to see if it's possible to symbolically evaluate 8298 // the arguments into constants, and if so, try to constant propagate the 8299 // result. This is particularly useful for computing loop exit values. 8300 if (CanConstantFold(I)) { 8301 SmallVector<Constant *, 4> Operands; 8302 bool MadeImprovement = false; 8303 for (Value *Op : I->operands()) { 8304 if (Constant *C = dyn_cast<Constant>(Op)) { 8305 Operands.push_back(C); 8306 continue; 8307 } 8308 8309 // If any of the operands is non-constant and if they are 8310 // non-integer and non-pointer, don't even try to analyze them 8311 // with scev techniques. 8312 if (!isSCEVable(Op->getType())) 8313 return V; 8314 8315 const SCEV *OrigV = getSCEV(Op); 8316 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8317 MadeImprovement |= OrigV != OpV; 8318 8319 Constant *C = BuildConstantFromSCEV(OpV); 8320 if (!C) return V; 8321 if (C->getType() != Op->getType()) 8322 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8323 Op->getType(), 8324 false), 8325 C, Op->getType()); 8326 Operands.push_back(C); 8327 } 8328 8329 // Check to see if getSCEVAtScope actually made an improvement. 8330 if (MadeImprovement) { 8331 Constant *C = nullptr; 8332 const DataLayout &DL = getDataLayout(); 8333 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8334 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8335 Operands[1], DL, &TLI); 8336 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8337 if (!LI->isVolatile()) 8338 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8339 } else 8340 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8341 if (!C) return V; 8342 return getSCEV(C); 8343 } 8344 } 8345 } 8346 8347 // This is some other type of SCEVUnknown, just return it. 8348 return V; 8349 } 8350 8351 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8352 // Avoid performing the look-up in the common case where the specified 8353 // expression has no loop-variant portions. 8354 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8355 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8356 if (OpAtScope != Comm->getOperand(i)) { 8357 // Okay, at least one of these operands is loop variant but might be 8358 // foldable. Build a new instance of the folded commutative expression. 8359 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8360 Comm->op_begin()+i); 8361 NewOps.push_back(OpAtScope); 8362 8363 for (++i; i != e; ++i) { 8364 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8365 NewOps.push_back(OpAtScope); 8366 } 8367 if (isa<SCEVAddExpr>(Comm)) 8368 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8369 if (isa<SCEVMulExpr>(Comm)) 8370 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8371 if (isa<SCEVMinMaxExpr>(Comm)) 8372 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8373 llvm_unreachable("Unknown commutative SCEV type!"); 8374 } 8375 } 8376 // If we got here, all operands are loop invariant. 8377 return Comm; 8378 } 8379 8380 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8381 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8382 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8383 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8384 return Div; // must be loop invariant 8385 return getUDivExpr(LHS, RHS); 8386 } 8387 8388 // If this is a loop recurrence for a loop that does not contain L, then we 8389 // are dealing with the final value computed by the loop. 8390 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8391 // First, attempt to evaluate each operand. 8392 // Avoid performing the look-up in the common case where the specified 8393 // expression has no loop-variant portions. 8394 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8395 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8396 if (OpAtScope == AddRec->getOperand(i)) 8397 continue; 8398 8399 // Okay, at least one of these operands is loop variant but might be 8400 // foldable. Build a new instance of the folded commutative expression. 8401 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8402 AddRec->op_begin()+i); 8403 NewOps.push_back(OpAtScope); 8404 for (++i; i != e; ++i) 8405 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8406 8407 const SCEV *FoldedRec = 8408 getAddRecExpr(NewOps, AddRec->getLoop(), 8409 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8410 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8411 // The addrec may be folded to a nonrecurrence, for example, if the 8412 // induction variable is multiplied by zero after constant folding. Go 8413 // ahead and return the folded value. 8414 if (!AddRec) 8415 return FoldedRec; 8416 break; 8417 } 8418 8419 // If the scope is outside the addrec's loop, evaluate it by using the 8420 // loop exit value of the addrec. 8421 if (!AddRec->getLoop()->contains(L)) { 8422 // To evaluate this recurrence, we need to know how many times the AddRec 8423 // loop iterates. Compute this now. 8424 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8425 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8426 8427 // Then, evaluate the AddRec. 8428 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8429 } 8430 8431 return AddRec; 8432 } 8433 8434 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8435 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8436 if (Op == Cast->getOperand()) 8437 return Cast; // must be loop invariant 8438 return getZeroExtendExpr(Op, Cast->getType()); 8439 } 8440 8441 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8442 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8443 if (Op == Cast->getOperand()) 8444 return Cast; // must be loop invariant 8445 return getSignExtendExpr(Op, Cast->getType()); 8446 } 8447 8448 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8449 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8450 if (Op == Cast->getOperand()) 8451 return Cast; // must be loop invariant 8452 return getTruncateExpr(Op, Cast->getType()); 8453 } 8454 8455 llvm_unreachable("Unknown SCEV type!"); 8456 } 8457 8458 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8459 return getSCEVAtScope(getSCEV(V), L); 8460 } 8461 8462 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8463 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8464 return stripInjectiveFunctions(ZExt->getOperand()); 8465 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8466 return stripInjectiveFunctions(SExt->getOperand()); 8467 return S; 8468 } 8469 8470 /// Finds the minimum unsigned root of the following equation: 8471 /// 8472 /// A * X = B (mod N) 8473 /// 8474 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8475 /// A and B isn't important. 8476 /// 8477 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8478 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8479 ScalarEvolution &SE) { 8480 uint32_t BW = A.getBitWidth(); 8481 assert(BW == SE.getTypeSizeInBits(B->getType())); 8482 assert(A != 0 && "A must be non-zero."); 8483 8484 // 1. D = gcd(A, N) 8485 // 8486 // The gcd of A and N may have only one prime factor: 2. The number of 8487 // trailing zeros in A is its multiplicity 8488 uint32_t Mult2 = A.countTrailingZeros(); 8489 // D = 2^Mult2 8490 8491 // 2. Check if B is divisible by D. 8492 // 8493 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8494 // is not less than multiplicity of this prime factor for D. 8495 if (SE.GetMinTrailingZeros(B) < Mult2) 8496 return SE.getCouldNotCompute(); 8497 8498 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8499 // modulo (N / D). 8500 // 8501 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8502 // (N / D) in general. The inverse itself always fits into BW bits, though, 8503 // so we immediately truncate it. 8504 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8505 APInt Mod(BW + 1, 0); 8506 Mod.setBit(BW - Mult2); // Mod = N / D 8507 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8508 8509 // 4. Compute the minimum unsigned root of the equation: 8510 // I * (B / D) mod (N / D) 8511 // To simplify the computation, we factor out the divide by D: 8512 // (I * B mod N) / D 8513 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8514 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8515 } 8516 8517 /// For a given quadratic addrec, generate coefficients of the corresponding 8518 /// quadratic equation, multiplied by a common value to ensure that they are 8519 /// integers. 8520 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8521 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8522 /// were multiplied by, and BitWidth is the bit width of the original addrec 8523 /// coefficients. 8524 /// This function returns None if the addrec coefficients are not compile- 8525 /// time constants. 8526 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8527 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8528 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8529 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8530 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8531 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8532 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8533 << *AddRec << '\n'); 8534 8535 // We currently can only solve this if the coefficients are constants. 8536 if (!LC || !MC || !NC) { 8537 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8538 return None; 8539 } 8540 8541 APInt L = LC->getAPInt(); 8542 APInt M = MC->getAPInt(); 8543 APInt N = NC->getAPInt(); 8544 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8545 8546 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8547 unsigned NewWidth = BitWidth + 1; 8548 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8549 << BitWidth << '\n'); 8550 // The sign-extension (as opposed to a zero-extension) here matches the 8551 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8552 N = N.sext(NewWidth); 8553 M = M.sext(NewWidth); 8554 L = L.sext(NewWidth); 8555 8556 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8557 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8558 // L+M, L+2M+N, L+3M+3N, ... 8559 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8560 // 8561 // The equation Acc = 0 is then 8562 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8563 // In a quadratic form it becomes: 8564 // N n^2 + (2M-N) n + 2L = 0. 8565 8566 APInt A = N; 8567 APInt B = 2 * M - A; 8568 APInt C = 2 * L; 8569 APInt T = APInt(NewWidth, 2); 8570 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8571 << "x + " << C << ", coeff bw: " << NewWidth 8572 << ", multiplied by " << T << '\n'); 8573 return std::make_tuple(A, B, C, T, BitWidth); 8574 } 8575 8576 /// Helper function to compare optional APInts: 8577 /// (a) if X and Y both exist, return min(X, Y), 8578 /// (b) if neither X nor Y exist, return None, 8579 /// (c) if exactly one of X and Y exists, return that value. 8580 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8581 if (X.hasValue() && Y.hasValue()) { 8582 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8583 APInt XW = X->sextOrSelf(W); 8584 APInt YW = Y->sextOrSelf(W); 8585 return XW.slt(YW) ? *X : *Y; 8586 } 8587 if (!X.hasValue() && !Y.hasValue()) 8588 return None; 8589 return X.hasValue() ? *X : *Y; 8590 } 8591 8592 /// Helper function to truncate an optional APInt to a given BitWidth. 8593 /// When solving addrec-related equations, it is preferable to return a value 8594 /// that has the same bit width as the original addrec's coefficients. If the 8595 /// solution fits in the original bit width, truncate it (except for i1). 8596 /// Returning a value of a different bit width may inhibit some optimizations. 8597 /// 8598 /// In general, a solution to a quadratic equation generated from an addrec 8599 /// may require BW+1 bits, where BW is the bit width of the addrec's 8600 /// coefficients. The reason is that the coefficients of the quadratic 8601 /// equation are BW+1 bits wide (to avoid truncation when converting from 8602 /// the addrec to the equation). 8603 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8604 if (!X.hasValue()) 8605 return None; 8606 unsigned W = X->getBitWidth(); 8607 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8608 return X->trunc(BitWidth); 8609 return X; 8610 } 8611 8612 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8613 /// iterations. The values L, M, N are assumed to be signed, and they 8614 /// should all have the same bit widths. 8615 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8616 /// where BW is the bit width of the addrec's coefficients. 8617 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8618 /// returned as such, otherwise the bit width of the returned value may 8619 /// be greater than BW. 8620 /// 8621 /// This function returns None if 8622 /// (a) the addrec coefficients are not constant, or 8623 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8624 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8625 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8626 static Optional<APInt> 8627 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8628 APInt A, B, C, M; 8629 unsigned BitWidth; 8630 auto T = GetQuadraticEquation(AddRec); 8631 if (!T.hasValue()) 8632 return None; 8633 8634 std::tie(A, B, C, M, BitWidth) = *T; 8635 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8636 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8637 if (!X.hasValue()) 8638 return None; 8639 8640 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8641 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8642 if (!V->isZero()) 8643 return None; 8644 8645 return TruncIfPossible(X, BitWidth); 8646 } 8647 8648 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8649 /// iterations. The values M, N are assumed to be signed, and they 8650 /// should all have the same bit widths. 8651 /// Find the least n such that c(n) does not belong to the given range, 8652 /// while c(n-1) does. 8653 /// 8654 /// This function returns None if 8655 /// (a) the addrec coefficients are not constant, or 8656 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8657 /// bounds of the range. 8658 static Optional<APInt> 8659 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8660 const ConstantRange &Range, ScalarEvolution &SE) { 8661 assert(AddRec->getOperand(0)->isZero() && 8662 "Starting value of addrec should be 0"); 8663 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8664 << Range << ", addrec " << *AddRec << '\n'); 8665 // This case is handled in getNumIterationsInRange. Here we can assume that 8666 // we start in the range. 8667 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8668 "Addrec's initial value should be in range"); 8669 8670 APInt A, B, C, M; 8671 unsigned BitWidth; 8672 auto T = GetQuadraticEquation(AddRec); 8673 if (!T.hasValue()) 8674 return None; 8675 8676 // Be careful about the return value: there can be two reasons for not 8677 // returning an actual number. First, if no solutions to the equations 8678 // were found, and second, if the solutions don't leave the given range. 8679 // The first case means that the actual solution is "unknown", the second 8680 // means that it's known, but not valid. If the solution is unknown, we 8681 // cannot make any conclusions. 8682 // Return a pair: the optional solution and a flag indicating if the 8683 // solution was found. 8684 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8685 // Solve for signed overflow and unsigned overflow, pick the lower 8686 // solution. 8687 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8688 << Bound << " (before multiplying by " << M << ")\n"); 8689 Bound *= M; // The quadratic equation multiplier. 8690 8691 Optional<APInt> SO = None; 8692 if (BitWidth > 1) { 8693 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8694 "signed overflow\n"); 8695 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8696 } 8697 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8698 "unsigned overflow\n"); 8699 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8700 BitWidth+1); 8701 8702 auto LeavesRange = [&] (const APInt &X) { 8703 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8704 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8705 if (Range.contains(V0->getValue())) 8706 return false; 8707 // X should be at least 1, so X-1 is non-negative. 8708 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8709 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8710 if (Range.contains(V1->getValue())) 8711 return true; 8712 return false; 8713 }; 8714 8715 // If SolveQuadraticEquationWrap returns None, it means that there can 8716 // be a solution, but the function failed to find it. We cannot treat it 8717 // as "no solution". 8718 if (!SO.hasValue() || !UO.hasValue()) 8719 return { None, false }; 8720 8721 // Check the smaller value first to see if it leaves the range. 8722 // At this point, both SO and UO must have values. 8723 Optional<APInt> Min = MinOptional(SO, UO); 8724 if (LeavesRange(*Min)) 8725 return { Min, true }; 8726 Optional<APInt> Max = Min == SO ? UO : SO; 8727 if (LeavesRange(*Max)) 8728 return { Max, true }; 8729 8730 // Solutions were found, but were eliminated, hence the "true". 8731 return { None, true }; 8732 }; 8733 8734 std::tie(A, B, C, M, BitWidth) = *T; 8735 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8736 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8737 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8738 auto SL = SolveForBoundary(Lower); 8739 auto SU = SolveForBoundary(Upper); 8740 // If any of the solutions was unknown, no meaninigful conclusions can 8741 // be made. 8742 if (!SL.second || !SU.second) 8743 return None; 8744 8745 // Claim: The correct solution is not some value between Min and Max. 8746 // 8747 // Justification: Assuming that Min and Max are different values, one of 8748 // them is when the first signed overflow happens, the other is when the 8749 // first unsigned overflow happens. Crossing the range boundary is only 8750 // possible via an overflow (treating 0 as a special case of it, modeling 8751 // an overflow as crossing k*2^W for some k). 8752 // 8753 // The interesting case here is when Min was eliminated as an invalid 8754 // solution, but Max was not. The argument is that if there was another 8755 // overflow between Min and Max, it would also have been eliminated if 8756 // it was considered. 8757 // 8758 // For a given boundary, it is possible to have two overflows of the same 8759 // type (signed/unsigned) without having the other type in between: this 8760 // can happen when the vertex of the parabola is between the iterations 8761 // corresponding to the overflows. This is only possible when the two 8762 // overflows cross k*2^W for the same k. In such case, if the second one 8763 // left the range (and was the first one to do so), the first overflow 8764 // would have to enter the range, which would mean that either we had left 8765 // the range before or that we started outside of it. Both of these cases 8766 // are contradictions. 8767 // 8768 // Claim: In the case where SolveForBoundary returns None, the correct 8769 // solution is not some value between the Max for this boundary and the 8770 // Min of the other boundary. 8771 // 8772 // Justification: Assume that we had such Max_A and Min_B corresponding 8773 // to range boundaries A and B and such that Max_A < Min_B. If there was 8774 // a solution between Max_A and Min_B, it would have to be caused by an 8775 // overflow corresponding to either A or B. It cannot correspond to B, 8776 // since Min_B is the first occurrence of such an overflow. If it 8777 // corresponded to A, it would have to be either a signed or an unsigned 8778 // overflow that is larger than both eliminated overflows for A. But 8779 // between the eliminated overflows and this overflow, the values would 8780 // cover the entire value space, thus crossing the other boundary, which 8781 // is a contradiction. 8782 8783 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8784 } 8785 8786 ScalarEvolution::ExitLimit 8787 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8788 bool AllowPredicates) { 8789 8790 // This is only used for loops with a "x != y" exit test. The exit condition 8791 // is now expressed as a single expression, V = x-y. So the exit test is 8792 // effectively V != 0. We know and take advantage of the fact that this 8793 // expression only being used in a comparison by zero context. 8794 8795 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8796 // If the value is a constant 8797 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8798 // If the value is already zero, the branch will execute zero times. 8799 if (C->getValue()->isZero()) return C; 8800 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8801 } 8802 8803 const SCEVAddRecExpr *AddRec = 8804 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8805 8806 if (!AddRec && AllowPredicates) 8807 // Try to make this an AddRec using runtime tests, in the first X 8808 // iterations of this loop, where X is the SCEV expression found by the 8809 // algorithm below. 8810 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8811 8812 if (!AddRec || AddRec->getLoop() != L) 8813 return getCouldNotCompute(); 8814 8815 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8816 // the quadratic equation to solve it. 8817 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8818 // We can only use this value if the chrec ends up with an exact zero 8819 // value at this index. When solving for "X*X != 5", for example, we 8820 // should not accept a root of 2. 8821 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8822 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8823 return ExitLimit(R, R, false, Predicates); 8824 } 8825 return getCouldNotCompute(); 8826 } 8827 8828 // Otherwise we can only handle this if it is affine. 8829 if (!AddRec->isAffine()) 8830 return getCouldNotCompute(); 8831 8832 // If this is an affine expression, the execution count of this branch is 8833 // the minimum unsigned root of the following equation: 8834 // 8835 // Start + Step*N = 0 (mod 2^BW) 8836 // 8837 // equivalent to: 8838 // 8839 // Step*N = -Start (mod 2^BW) 8840 // 8841 // where BW is the common bit width of Start and Step. 8842 8843 // Get the initial value for the loop. 8844 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8845 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8846 8847 // For now we handle only constant steps. 8848 // 8849 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8850 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8851 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8852 // We have not yet seen any such cases. 8853 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8854 if (!StepC || StepC->getValue()->isZero()) 8855 return getCouldNotCompute(); 8856 8857 // For positive steps (counting up until unsigned overflow): 8858 // N = -Start/Step (as unsigned) 8859 // For negative steps (counting down to zero): 8860 // N = Start/-Step 8861 // First compute the unsigned distance from zero in the direction of Step. 8862 bool CountDown = StepC->getAPInt().isNegative(); 8863 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8864 8865 // Handle unitary steps, which cannot wraparound. 8866 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8867 // N = Distance (as unsigned) 8868 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8869 APInt MaxBECount = getUnsignedRangeMax(Distance); 8870 8871 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8872 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8873 // case, and see if we can improve the bound. 8874 // 8875 // Explicitly handling this here is necessary because getUnsignedRange 8876 // isn't context-sensitive; it doesn't know that we only care about the 8877 // range inside the loop. 8878 const SCEV *Zero = getZero(Distance->getType()); 8879 const SCEV *One = getOne(Distance->getType()); 8880 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8881 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8882 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8883 // as "unsigned_max(Distance + 1) - 1". 8884 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8885 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8886 } 8887 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8888 } 8889 8890 // If the condition controls loop exit (the loop exits only if the expression 8891 // is true) and the addition is no-wrap we can use unsigned divide to 8892 // compute the backedge count. In this case, the step may not divide the 8893 // distance, but we don't care because if the condition is "missed" the loop 8894 // will have undefined behavior due to wrapping. 8895 if (ControlsExit && AddRec->hasNoSelfWrap() && 8896 loopHasNoAbnormalExits(AddRec->getLoop())) { 8897 const SCEV *Exact = 8898 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8899 const SCEV *Max = 8900 Exact == getCouldNotCompute() 8901 ? Exact 8902 : getConstant(getUnsignedRangeMax(Exact)); 8903 return ExitLimit(Exact, Max, false, Predicates); 8904 } 8905 8906 // Solve the general equation. 8907 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8908 getNegativeSCEV(Start), *this); 8909 const SCEV *M = E == getCouldNotCompute() 8910 ? E 8911 : getConstant(getUnsignedRangeMax(E)); 8912 return ExitLimit(E, M, false, Predicates); 8913 } 8914 8915 ScalarEvolution::ExitLimit 8916 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8917 // Loops that look like: while (X == 0) are very strange indeed. We don't 8918 // handle them yet except for the trivial case. This could be expanded in the 8919 // future as needed. 8920 8921 // If the value is a constant, check to see if it is known to be non-zero 8922 // already. If so, the backedge will execute zero times. 8923 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8924 if (!C->getValue()->isZero()) 8925 return getZero(C->getType()); 8926 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8927 } 8928 8929 // We could implement others, but I really doubt anyone writes loops like 8930 // this, and if they did, they would already be constant folded. 8931 return getCouldNotCompute(); 8932 } 8933 8934 std::pair<BasicBlock *, BasicBlock *> 8935 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8936 // If the block has a unique predecessor, then there is no path from the 8937 // predecessor to the block that does not go through the direct edge 8938 // from the predecessor to the block. 8939 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8940 return {Pred, BB}; 8941 8942 // A loop's header is defined to be a block that dominates the loop. 8943 // If the header has a unique predecessor outside the loop, it must be 8944 // a block that has exactly one successor that can reach the loop. 8945 if (Loop *L = LI.getLoopFor(BB)) 8946 return {L->getLoopPredecessor(), L->getHeader()}; 8947 8948 return {nullptr, nullptr}; 8949 } 8950 8951 /// SCEV structural equivalence is usually sufficient for testing whether two 8952 /// expressions are equal, however for the purposes of looking for a condition 8953 /// guarding a loop, it can be useful to be a little more general, since a 8954 /// front-end may have replicated the controlling expression. 8955 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8956 // Quick check to see if they are the same SCEV. 8957 if (A == B) return true; 8958 8959 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8960 // Not all instructions that are "identical" compute the same value. For 8961 // instance, two distinct alloca instructions allocating the same type are 8962 // identical and do not read memory; but compute distinct values. 8963 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8964 }; 8965 8966 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8967 // two different instructions with the same value. Check for this case. 8968 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8969 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8970 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8971 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8972 if (ComputesEqualValues(AI, BI)) 8973 return true; 8974 8975 // Otherwise assume they may have a different value. 8976 return false; 8977 } 8978 8979 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8980 const SCEV *&LHS, const SCEV *&RHS, 8981 unsigned Depth) { 8982 bool Changed = false; 8983 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8984 // '0 != 0'. 8985 auto TrivialCase = [&](bool TriviallyTrue) { 8986 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8987 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8988 return true; 8989 }; 8990 // If we hit the max recursion limit bail out. 8991 if (Depth >= 3) 8992 return false; 8993 8994 // Canonicalize a constant to the right side. 8995 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8996 // Check for both operands constant. 8997 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8998 if (ConstantExpr::getICmp(Pred, 8999 LHSC->getValue(), 9000 RHSC->getValue())->isNullValue()) 9001 return TrivialCase(false); 9002 else 9003 return TrivialCase(true); 9004 } 9005 // Otherwise swap the operands to put the constant on the right. 9006 std::swap(LHS, RHS); 9007 Pred = ICmpInst::getSwappedPredicate(Pred); 9008 Changed = true; 9009 } 9010 9011 // If we're comparing an addrec with a value which is loop-invariant in the 9012 // addrec's loop, put the addrec on the left. Also make a dominance check, 9013 // as both operands could be addrecs loop-invariant in each other's loop. 9014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9015 const Loop *L = AR->getLoop(); 9016 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9017 std::swap(LHS, RHS); 9018 Pred = ICmpInst::getSwappedPredicate(Pred); 9019 Changed = true; 9020 } 9021 } 9022 9023 // If there's a constant operand, canonicalize comparisons with boundary 9024 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9025 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9026 const APInt &RA = RC->getAPInt(); 9027 9028 bool SimplifiedByConstantRange = false; 9029 9030 if (!ICmpInst::isEquality(Pred)) { 9031 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9032 if (ExactCR.isFullSet()) 9033 return TrivialCase(true); 9034 else if (ExactCR.isEmptySet()) 9035 return TrivialCase(false); 9036 9037 APInt NewRHS; 9038 CmpInst::Predicate NewPred; 9039 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9040 ICmpInst::isEquality(NewPred)) { 9041 // We were able to convert an inequality to an equality. 9042 Pred = NewPred; 9043 RHS = getConstant(NewRHS); 9044 Changed = SimplifiedByConstantRange = true; 9045 } 9046 } 9047 9048 if (!SimplifiedByConstantRange) { 9049 switch (Pred) { 9050 default: 9051 break; 9052 case ICmpInst::ICMP_EQ: 9053 case ICmpInst::ICMP_NE: 9054 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9055 if (!RA) 9056 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9057 if (const SCEVMulExpr *ME = 9058 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9059 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9060 ME->getOperand(0)->isAllOnesValue()) { 9061 RHS = AE->getOperand(1); 9062 LHS = ME->getOperand(1); 9063 Changed = true; 9064 } 9065 break; 9066 9067 9068 // The "Should have been caught earlier!" messages refer to the fact 9069 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9070 // should have fired on the corresponding cases, and canonicalized the 9071 // check to trivial case. 9072 9073 case ICmpInst::ICMP_UGE: 9074 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9075 Pred = ICmpInst::ICMP_UGT; 9076 RHS = getConstant(RA - 1); 9077 Changed = true; 9078 break; 9079 case ICmpInst::ICMP_ULE: 9080 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9081 Pred = ICmpInst::ICMP_ULT; 9082 RHS = getConstant(RA + 1); 9083 Changed = true; 9084 break; 9085 case ICmpInst::ICMP_SGE: 9086 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9087 Pred = ICmpInst::ICMP_SGT; 9088 RHS = getConstant(RA - 1); 9089 Changed = true; 9090 break; 9091 case ICmpInst::ICMP_SLE: 9092 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9093 Pred = ICmpInst::ICMP_SLT; 9094 RHS = getConstant(RA + 1); 9095 Changed = true; 9096 break; 9097 } 9098 } 9099 } 9100 9101 // Check for obvious equality. 9102 if (HasSameValue(LHS, RHS)) { 9103 if (ICmpInst::isTrueWhenEqual(Pred)) 9104 return TrivialCase(true); 9105 if (ICmpInst::isFalseWhenEqual(Pred)) 9106 return TrivialCase(false); 9107 } 9108 9109 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9110 // adding or subtracting 1 from one of the operands. 9111 switch (Pred) { 9112 case ICmpInst::ICMP_SLE: 9113 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9114 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9115 SCEV::FlagNSW); 9116 Pred = ICmpInst::ICMP_SLT; 9117 Changed = true; 9118 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9119 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9120 SCEV::FlagNSW); 9121 Pred = ICmpInst::ICMP_SLT; 9122 Changed = true; 9123 } 9124 break; 9125 case ICmpInst::ICMP_SGE: 9126 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9127 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9128 SCEV::FlagNSW); 9129 Pred = ICmpInst::ICMP_SGT; 9130 Changed = true; 9131 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9132 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9133 SCEV::FlagNSW); 9134 Pred = ICmpInst::ICMP_SGT; 9135 Changed = true; 9136 } 9137 break; 9138 case ICmpInst::ICMP_ULE: 9139 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9140 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9141 SCEV::FlagNUW); 9142 Pred = ICmpInst::ICMP_ULT; 9143 Changed = true; 9144 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9145 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9146 Pred = ICmpInst::ICMP_ULT; 9147 Changed = true; 9148 } 9149 break; 9150 case ICmpInst::ICMP_UGE: 9151 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9152 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9153 Pred = ICmpInst::ICMP_UGT; 9154 Changed = true; 9155 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9156 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9157 SCEV::FlagNUW); 9158 Pred = ICmpInst::ICMP_UGT; 9159 Changed = true; 9160 } 9161 break; 9162 default: 9163 break; 9164 } 9165 9166 // TODO: More simplifications are possible here. 9167 9168 // Recursively simplify until we either hit a recursion limit or nothing 9169 // changes. 9170 if (Changed) 9171 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9172 9173 return Changed; 9174 } 9175 9176 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9177 return getSignedRangeMax(S).isNegative(); 9178 } 9179 9180 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9181 return getSignedRangeMin(S).isStrictlyPositive(); 9182 } 9183 9184 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9185 return !getSignedRangeMin(S).isNegative(); 9186 } 9187 9188 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9189 return !getSignedRangeMax(S).isStrictlyPositive(); 9190 } 9191 9192 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9193 return isKnownNegative(S) || isKnownPositive(S); 9194 } 9195 9196 std::pair<const SCEV *, const SCEV *> 9197 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9198 // Compute SCEV on entry of loop L. 9199 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9200 if (Start == getCouldNotCompute()) 9201 return { Start, Start }; 9202 // Compute post increment SCEV for loop L. 9203 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9204 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9205 return { Start, PostInc }; 9206 } 9207 9208 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9209 const SCEV *LHS, const SCEV *RHS) { 9210 // First collect all loops. 9211 SmallPtrSet<const Loop *, 8> LoopsUsed; 9212 getUsedLoops(LHS, LoopsUsed); 9213 getUsedLoops(RHS, LoopsUsed); 9214 9215 if (LoopsUsed.empty()) 9216 return false; 9217 9218 // Domination relationship must be a linear order on collected loops. 9219 #ifndef NDEBUG 9220 for (auto *L1 : LoopsUsed) 9221 for (auto *L2 : LoopsUsed) 9222 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9223 DT.dominates(L2->getHeader(), L1->getHeader())) && 9224 "Domination relationship is not a linear order"); 9225 #endif 9226 9227 const Loop *MDL = 9228 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9229 [&](const Loop *L1, const Loop *L2) { 9230 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9231 }); 9232 9233 // Get init and post increment value for LHS. 9234 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9235 // if LHS contains unknown non-invariant SCEV then bail out. 9236 if (SplitLHS.first == getCouldNotCompute()) 9237 return false; 9238 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9239 // Get init and post increment value for RHS. 9240 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9241 // if RHS contains unknown non-invariant SCEV then bail out. 9242 if (SplitRHS.first == getCouldNotCompute()) 9243 return false; 9244 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9245 // It is possible that init SCEV contains an invariant load but it does 9246 // not dominate MDL and is not available at MDL loop entry, so we should 9247 // check it here. 9248 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9249 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9250 return false; 9251 9252 // It seems backedge guard check is faster than entry one so in some cases 9253 // it can speed up whole estimation by short circuit 9254 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9255 SplitRHS.second) && 9256 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9257 } 9258 9259 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9260 const SCEV *LHS, const SCEV *RHS) { 9261 // Canonicalize the inputs first. 9262 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9263 9264 if (isKnownViaInduction(Pred, LHS, RHS)) 9265 return true; 9266 9267 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9268 return true; 9269 9270 // Otherwise see what can be done with some simple reasoning. 9271 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9272 } 9273 9274 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9275 const SCEVAddRecExpr *LHS, 9276 const SCEV *RHS) { 9277 const Loop *L = LHS->getLoop(); 9278 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9279 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9280 } 9281 9282 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9283 ICmpInst::Predicate Pred, 9284 bool &Increasing) { 9285 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9286 9287 #ifndef NDEBUG 9288 // Verify an invariant: inverting the predicate should turn a monotonically 9289 // increasing change to a monotonically decreasing one, and vice versa. 9290 bool IncreasingSwapped; 9291 bool ResultSwapped = isMonotonicPredicateImpl( 9292 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9293 9294 assert(Result == ResultSwapped && "should be able to analyze both!"); 9295 if (ResultSwapped) 9296 assert(Increasing == !IncreasingSwapped && 9297 "monotonicity should flip as we flip the predicate"); 9298 #endif 9299 9300 return Result; 9301 } 9302 9303 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9304 ICmpInst::Predicate Pred, 9305 bool &Increasing) { 9306 9307 // A zero step value for LHS means the induction variable is essentially a 9308 // loop invariant value. We don't really depend on the predicate actually 9309 // flipping from false to true (for increasing predicates, and the other way 9310 // around for decreasing predicates), all we care about is that *if* the 9311 // predicate changes then it only changes from false to true. 9312 // 9313 // A zero step value in itself is not very useful, but there may be places 9314 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9315 // as general as possible. 9316 9317 switch (Pred) { 9318 default: 9319 return false; // Conservative answer 9320 9321 case ICmpInst::ICMP_UGT: 9322 case ICmpInst::ICMP_UGE: 9323 case ICmpInst::ICMP_ULT: 9324 case ICmpInst::ICMP_ULE: 9325 if (!LHS->hasNoUnsignedWrap()) 9326 return false; 9327 9328 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9329 return true; 9330 9331 case ICmpInst::ICMP_SGT: 9332 case ICmpInst::ICMP_SGE: 9333 case ICmpInst::ICMP_SLT: 9334 case ICmpInst::ICMP_SLE: { 9335 if (!LHS->hasNoSignedWrap()) 9336 return false; 9337 9338 const SCEV *Step = LHS->getStepRecurrence(*this); 9339 9340 if (isKnownNonNegative(Step)) { 9341 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9342 return true; 9343 } 9344 9345 if (isKnownNonPositive(Step)) { 9346 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9347 return true; 9348 } 9349 9350 return false; 9351 } 9352 9353 } 9354 9355 llvm_unreachable("switch has default clause!"); 9356 } 9357 9358 bool ScalarEvolution::isLoopInvariantPredicate( 9359 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9360 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9361 const SCEV *&InvariantRHS) { 9362 9363 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9364 if (!isLoopInvariant(RHS, L)) { 9365 if (!isLoopInvariant(LHS, L)) 9366 return false; 9367 9368 std::swap(LHS, RHS); 9369 Pred = ICmpInst::getSwappedPredicate(Pred); 9370 } 9371 9372 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9373 if (!ArLHS || ArLHS->getLoop() != L) 9374 return false; 9375 9376 bool Increasing; 9377 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9378 return false; 9379 9380 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9381 // true as the loop iterates, and the backedge is control dependent on 9382 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9383 // 9384 // * if the predicate was false in the first iteration then the predicate 9385 // is never evaluated again, since the loop exits without taking the 9386 // backedge. 9387 // * if the predicate was true in the first iteration then it will 9388 // continue to be true for all future iterations since it is 9389 // monotonically increasing. 9390 // 9391 // For both the above possibilities, we can replace the loop varying 9392 // predicate with its value on the first iteration of the loop (which is 9393 // loop invariant). 9394 // 9395 // A similar reasoning applies for a monotonically decreasing predicate, by 9396 // replacing true with false and false with true in the above two bullets. 9397 9398 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9399 9400 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9401 return false; 9402 9403 InvariantPred = Pred; 9404 InvariantLHS = ArLHS->getStart(); 9405 InvariantRHS = RHS; 9406 return true; 9407 } 9408 9409 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9410 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9411 if (HasSameValue(LHS, RHS)) 9412 return ICmpInst::isTrueWhenEqual(Pred); 9413 9414 // This code is split out from isKnownPredicate because it is called from 9415 // within isLoopEntryGuardedByCond. 9416 9417 auto CheckRanges = 9418 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9419 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9420 .contains(RangeLHS); 9421 }; 9422 9423 // The check at the top of the function catches the case where the values are 9424 // known to be equal. 9425 if (Pred == CmpInst::ICMP_EQ) 9426 return false; 9427 9428 if (Pred == CmpInst::ICMP_NE) 9429 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9430 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9431 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9432 9433 if (CmpInst::isSigned(Pred)) 9434 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9435 9436 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9437 } 9438 9439 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9440 const SCEV *LHS, 9441 const SCEV *RHS) { 9442 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9443 // Return Y via OutY. 9444 auto MatchBinaryAddToConst = 9445 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9446 SCEV::NoWrapFlags ExpectedFlags) { 9447 const SCEV *NonConstOp, *ConstOp; 9448 SCEV::NoWrapFlags FlagsPresent; 9449 9450 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9451 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9452 return false; 9453 9454 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9455 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9456 }; 9457 9458 APInt C; 9459 9460 switch (Pred) { 9461 default: 9462 break; 9463 9464 case ICmpInst::ICMP_SGE: 9465 std::swap(LHS, RHS); 9466 LLVM_FALLTHROUGH; 9467 case ICmpInst::ICMP_SLE: 9468 // X s<= (X + C)<nsw> if C >= 0 9469 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9470 return true; 9471 9472 // (X + C)<nsw> s<= X if C <= 0 9473 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9474 !C.isStrictlyPositive()) 9475 return true; 9476 break; 9477 9478 case ICmpInst::ICMP_SGT: 9479 std::swap(LHS, RHS); 9480 LLVM_FALLTHROUGH; 9481 case ICmpInst::ICMP_SLT: 9482 // X s< (X + C)<nsw> if C > 0 9483 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9484 C.isStrictlyPositive()) 9485 return true; 9486 9487 // (X + C)<nsw> s< X if C < 0 9488 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9489 return true; 9490 break; 9491 } 9492 9493 return false; 9494 } 9495 9496 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9497 const SCEV *LHS, 9498 const SCEV *RHS) { 9499 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9500 return false; 9501 9502 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9503 // the stack can result in exponential time complexity. 9504 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9505 9506 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9507 // 9508 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9509 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9510 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9511 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9512 // use isKnownPredicate later if needed. 9513 return isKnownNonNegative(RHS) && 9514 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9515 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9516 } 9517 9518 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9519 ICmpInst::Predicate Pred, 9520 const SCEV *LHS, const SCEV *RHS) { 9521 // No need to even try if we know the module has no guards. 9522 if (!HasGuards) 9523 return false; 9524 9525 return any_of(*BB, [&](Instruction &I) { 9526 using namespace llvm::PatternMatch; 9527 9528 Value *Condition; 9529 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9530 m_Value(Condition))) && 9531 isImpliedCond(Pred, LHS, RHS, Condition, false); 9532 }); 9533 } 9534 9535 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9536 /// protected by a conditional between LHS and RHS. This is used to 9537 /// to eliminate casts. 9538 bool 9539 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9540 ICmpInst::Predicate Pred, 9541 const SCEV *LHS, const SCEV *RHS) { 9542 // Interpret a null as meaning no loop, where there is obviously no guard 9543 // (interprocedural conditions notwithstanding). 9544 if (!L) return true; 9545 9546 if (VerifyIR) 9547 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9548 "This cannot be done on broken IR!"); 9549 9550 9551 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9552 return true; 9553 9554 BasicBlock *Latch = L->getLoopLatch(); 9555 if (!Latch) 9556 return false; 9557 9558 BranchInst *LoopContinuePredicate = 9559 dyn_cast<BranchInst>(Latch->getTerminator()); 9560 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9561 isImpliedCond(Pred, LHS, RHS, 9562 LoopContinuePredicate->getCondition(), 9563 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9564 return true; 9565 9566 // We don't want more than one activation of the following loops on the stack 9567 // -- that can lead to O(n!) time complexity. 9568 if (WalkingBEDominatingConds) 9569 return false; 9570 9571 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9572 9573 // See if we can exploit a trip count to prove the predicate. 9574 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9575 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9576 if (LatchBECount != getCouldNotCompute()) { 9577 // We know that Latch branches back to the loop header exactly 9578 // LatchBECount times. This means the backdege condition at Latch is 9579 // equivalent to "{0,+,1} u< LatchBECount". 9580 Type *Ty = LatchBECount->getType(); 9581 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9582 const SCEV *LoopCounter = 9583 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9584 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9585 LatchBECount)) 9586 return true; 9587 } 9588 9589 // Check conditions due to any @llvm.assume intrinsics. 9590 for (auto &AssumeVH : AC.assumptions()) { 9591 if (!AssumeVH) 9592 continue; 9593 auto *CI = cast<CallInst>(AssumeVH); 9594 if (!DT.dominates(CI, Latch->getTerminator())) 9595 continue; 9596 9597 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9598 return true; 9599 } 9600 9601 // If the loop is not reachable from the entry block, we risk running into an 9602 // infinite loop as we walk up into the dom tree. These loops do not matter 9603 // anyway, so we just return a conservative answer when we see them. 9604 if (!DT.isReachableFromEntry(L->getHeader())) 9605 return false; 9606 9607 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9608 return true; 9609 9610 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9611 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9612 assert(DTN && "should reach the loop header before reaching the root!"); 9613 9614 BasicBlock *BB = DTN->getBlock(); 9615 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9616 return true; 9617 9618 BasicBlock *PBB = BB->getSinglePredecessor(); 9619 if (!PBB) 9620 continue; 9621 9622 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9623 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9624 continue; 9625 9626 Value *Condition = ContinuePredicate->getCondition(); 9627 9628 // If we have an edge `E` within the loop body that dominates the only 9629 // latch, the condition guarding `E` also guards the backedge. This 9630 // reasoning works only for loops with a single latch. 9631 9632 BasicBlockEdge DominatingEdge(PBB, BB); 9633 if (DominatingEdge.isSingleEdge()) { 9634 // We're constructively (and conservatively) enumerating edges within the 9635 // loop body that dominate the latch. The dominator tree better agree 9636 // with us on this: 9637 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9638 9639 if (isImpliedCond(Pred, LHS, RHS, Condition, 9640 BB != ContinuePredicate->getSuccessor(0))) 9641 return true; 9642 } 9643 } 9644 9645 return false; 9646 } 9647 9648 bool 9649 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9650 ICmpInst::Predicate Pred, 9651 const SCEV *LHS, const SCEV *RHS) { 9652 // Interpret a null as meaning no loop, where there is obviously no guard 9653 // (interprocedural conditions notwithstanding). 9654 if (!L) return false; 9655 9656 if (VerifyIR) 9657 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9658 "This cannot be done on broken IR!"); 9659 9660 // Both LHS and RHS must be available at loop entry. 9661 assert(isAvailableAtLoopEntry(LHS, L) && 9662 "LHS is not available at Loop Entry"); 9663 assert(isAvailableAtLoopEntry(RHS, L) && 9664 "RHS is not available at Loop Entry"); 9665 9666 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9667 return true; 9668 9669 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9670 // the facts (a >= b && a != b) separately. A typical situation is when the 9671 // non-strict comparison is known from ranges and non-equality is known from 9672 // dominating predicates. If we are proving strict comparison, we always try 9673 // to prove non-equality and non-strict comparison separately. 9674 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9675 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9676 bool ProvedNonStrictComparison = false; 9677 bool ProvedNonEquality = false; 9678 9679 if (ProvingStrictComparison) { 9680 ProvedNonStrictComparison = 9681 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9682 ProvedNonEquality = 9683 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9684 if (ProvedNonStrictComparison && ProvedNonEquality) 9685 return true; 9686 } 9687 9688 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9689 auto ProveViaGuard = [&](BasicBlock *Block) { 9690 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9691 return true; 9692 if (ProvingStrictComparison) { 9693 if (!ProvedNonStrictComparison) 9694 ProvedNonStrictComparison = 9695 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9696 if (!ProvedNonEquality) 9697 ProvedNonEquality = 9698 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9699 if (ProvedNonStrictComparison && ProvedNonEquality) 9700 return true; 9701 } 9702 return false; 9703 }; 9704 9705 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9706 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9707 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9708 return true; 9709 if (ProvingStrictComparison) { 9710 if (!ProvedNonStrictComparison) 9711 ProvedNonStrictComparison = 9712 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9713 if (!ProvedNonEquality) 9714 ProvedNonEquality = 9715 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9716 if (ProvedNonStrictComparison && ProvedNonEquality) 9717 return true; 9718 } 9719 return false; 9720 }; 9721 9722 // Starting at the loop predecessor, climb up the predecessor chain, as long 9723 // as there are predecessors that can be found that have unique successors 9724 // leading to the original header. 9725 for (std::pair<BasicBlock *, BasicBlock *> 9726 Pair(L->getLoopPredecessor(), L->getHeader()); 9727 Pair.first; 9728 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9729 9730 if (ProveViaGuard(Pair.first)) 9731 return true; 9732 9733 BranchInst *LoopEntryPredicate = 9734 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9735 if (!LoopEntryPredicate || 9736 LoopEntryPredicate->isUnconditional()) 9737 continue; 9738 9739 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9740 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9741 return true; 9742 } 9743 9744 // Check conditions due to any @llvm.assume intrinsics. 9745 for (auto &AssumeVH : AC.assumptions()) { 9746 if (!AssumeVH) 9747 continue; 9748 auto *CI = cast<CallInst>(AssumeVH); 9749 if (!DT.dominates(CI, L->getHeader())) 9750 continue; 9751 9752 if (ProveViaCond(CI->getArgOperand(0), false)) 9753 return true; 9754 } 9755 9756 return false; 9757 } 9758 9759 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9760 const SCEV *LHS, const SCEV *RHS, 9761 Value *FoundCondValue, 9762 bool Inverse) { 9763 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9764 return false; 9765 9766 auto ClearOnExit = 9767 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9768 9769 // Recursively handle And and Or conditions. 9770 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9771 if (BO->getOpcode() == Instruction::And) { 9772 if (!Inverse) 9773 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9774 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9775 } else if (BO->getOpcode() == Instruction::Or) { 9776 if (Inverse) 9777 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9778 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9779 } 9780 } 9781 9782 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9783 if (!ICI) return false; 9784 9785 // Now that we found a conditional branch that dominates the loop or controls 9786 // the loop latch. Check to see if it is the comparison we are looking for. 9787 ICmpInst::Predicate FoundPred; 9788 if (Inverse) 9789 FoundPred = ICI->getInversePredicate(); 9790 else 9791 FoundPred = ICI->getPredicate(); 9792 9793 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9794 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9795 9796 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9797 } 9798 9799 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9800 const SCEV *RHS, 9801 ICmpInst::Predicate FoundPred, 9802 const SCEV *FoundLHS, 9803 const SCEV *FoundRHS) { 9804 // Balance the types. 9805 if (getTypeSizeInBits(LHS->getType()) < 9806 getTypeSizeInBits(FoundLHS->getType())) { 9807 if (CmpInst::isSigned(Pred)) { 9808 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9809 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9810 } else { 9811 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9812 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9813 } 9814 } else if (getTypeSizeInBits(LHS->getType()) > 9815 getTypeSizeInBits(FoundLHS->getType())) { 9816 if (CmpInst::isSigned(FoundPred)) { 9817 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9818 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9819 } else { 9820 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9821 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9822 } 9823 } 9824 9825 // Canonicalize the query to match the way instcombine will have 9826 // canonicalized the comparison. 9827 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9828 if (LHS == RHS) 9829 return CmpInst::isTrueWhenEqual(Pred); 9830 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9831 if (FoundLHS == FoundRHS) 9832 return CmpInst::isFalseWhenEqual(FoundPred); 9833 9834 // Check to see if we can make the LHS or RHS match. 9835 if (LHS == FoundRHS || RHS == FoundLHS) { 9836 if (isa<SCEVConstant>(RHS)) { 9837 std::swap(FoundLHS, FoundRHS); 9838 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9839 } else { 9840 std::swap(LHS, RHS); 9841 Pred = ICmpInst::getSwappedPredicate(Pred); 9842 } 9843 } 9844 9845 // Check whether the found predicate is the same as the desired predicate. 9846 if (FoundPred == Pred) 9847 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9848 9849 // Check whether swapping the found predicate makes it the same as the 9850 // desired predicate. 9851 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9852 if (isa<SCEVConstant>(RHS)) 9853 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9854 else 9855 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9856 RHS, LHS, FoundLHS, FoundRHS); 9857 } 9858 9859 // Unsigned comparison is the same as signed comparison when both the operands 9860 // are non-negative. 9861 if (CmpInst::isUnsigned(FoundPred) && 9862 CmpInst::getSignedPredicate(FoundPred) == Pred && 9863 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9864 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9865 9866 // Check if we can make progress by sharpening ranges. 9867 if (FoundPred == ICmpInst::ICMP_NE && 9868 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9869 9870 const SCEVConstant *C = nullptr; 9871 const SCEV *V = nullptr; 9872 9873 if (isa<SCEVConstant>(FoundLHS)) { 9874 C = cast<SCEVConstant>(FoundLHS); 9875 V = FoundRHS; 9876 } else { 9877 C = cast<SCEVConstant>(FoundRHS); 9878 V = FoundLHS; 9879 } 9880 9881 // The guarding predicate tells us that C != V. If the known range 9882 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9883 // range we consider has to correspond to same signedness as the 9884 // predicate we're interested in folding. 9885 9886 APInt Min = ICmpInst::isSigned(Pred) ? 9887 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9888 9889 if (Min == C->getAPInt()) { 9890 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9891 // This is true even if (Min + 1) wraps around -- in case of 9892 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9893 9894 APInt SharperMin = Min + 1; 9895 9896 switch (Pred) { 9897 case ICmpInst::ICMP_SGE: 9898 case ICmpInst::ICMP_UGE: 9899 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9900 // RHS, we're done. 9901 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9902 getConstant(SharperMin))) 9903 return true; 9904 LLVM_FALLTHROUGH; 9905 9906 case ICmpInst::ICMP_SGT: 9907 case ICmpInst::ICMP_UGT: 9908 // We know from the range information that (V `Pred` Min || 9909 // V == Min). We know from the guarding condition that !(V 9910 // == Min). This gives us 9911 // 9912 // V `Pred` Min || V == Min && !(V == Min) 9913 // => V `Pred` Min 9914 // 9915 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9916 9917 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9918 return true; 9919 LLVM_FALLTHROUGH; 9920 9921 default: 9922 // No change 9923 break; 9924 } 9925 } 9926 } 9927 9928 // Check whether the actual condition is beyond sufficient. 9929 if (FoundPred == ICmpInst::ICMP_EQ) 9930 if (ICmpInst::isTrueWhenEqual(Pred)) 9931 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9932 return true; 9933 if (Pred == ICmpInst::ICMP_NE) 9934 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9935 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9936 return true; 9937 9938 // Otherwise assume the worst. 9939 return false; 9940 } 9941 9942 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9943 const SCEV *&L, const SCEV *&R, 9944 SCEV::NoWrapFlags &Flags) { 9945 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9946 if (!AE || AE->getNumOperands() != 2) 9947 return false; 9948 9949 L = AE->getOperand(0); 9950 R = AE->getOperand(1); 9951 Flags = AE->getNoWrapFlags(); 9952 return true; 9953 } 9954 9955 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9956 const SCEV *Less) { 9957 // We avoid subtracting expressions here because this function is usually 9958 // fairly deep in the call stack (i.e. is called many times). 9959 9960 // X - X = 0. 9961 if (More == Less) 9962 return APInt(getTypeSizeInBits(More->getType()), 0); 9963 9964 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9965 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9966 const auto *MAR = cast<SCEVAddRecExpr>(More); 9967 9968 if (LAR->getLoop() != MAR->getLoop()) 9969 return None; 9970 9971 // We look at affine expressions only; not for correctness but to keep 9972 // getStepRecurrence cheap. 9973 if (!LAR->isAffine() || !MAR->isAffine()) 9974 return None; 9975 9976 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9977 return None; 9978 9979 Less = LAR->getStart(); 9980 More = MAR->getStart(); 9981 9982 // fall through 9983 } 9984 9985 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9986 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9987 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9988 return M - L; 9989 } 9990 9991 SCEV::NoWrapFlags Flags; 9992 const SCEV *LLess = nullptr, *RLess = nullptr; 9993 const SCEV *LMore = nullptr, *RMore = nullptr; 9994 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9995 // Compare (X + C1) vs X. 9996 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9997 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9998 if (RLess == More) 9999 return -(C1->getAPInt()); 10000 10001 // Compare X vs (X + C2). 10002 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10003 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10004 if (RMore == Less) 10005 return C2->getAPInt(); 10006 10007 // Compare (X + C1) vs (X + C2). 10008 if (C1 && C2 && RLess == RMore) 10009 return C2->getAPInt() - C1->getAPInt(); 10010 10011 return None; 10012 } 10013 10014 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10015 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10016 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10017 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10018 return false; 10019 10020 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10021 if (!AddRecLHS) 10022 return false; 10023 10024 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10025 if (!AddRecFoundLHS) 10026 return false; 10027 10028 // We'd like to let SCEV reason about control dependencies, so we constrain 10029 // both the inequalities to be about add recurrences on the same loop. This 10030 // way we can use isLoopEntryGuardedByCond later. 10031 10032 const Loop *L = AddRecFoundLHS->getLoop(); 10033 if (L != AddRecLHS->getLoop()) 10034 return false; 10035 10036 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10037 // 10038 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10039 // ... (2) 10040 // 10041 // Informal proof for (2), assuming (1) [*]: 10042 // 10043 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10044 // 10045 // Then 10046 // 10047 // FoundLHS s< FoundRHS s< INT_MIN - C 10048 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10049 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10050 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10051 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10052 // <=> FoundLHS + C s< FoundRHS + C 10053 // 10054 // [*]: (1) can be proved by ruling out overflow. 10055 // 10056 // [**]: This can be proved by analyzing all the four possibilities: 10057 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10058 // (A s>= 0, B s>= 0). 10059 // 10060 // Note: 10061 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10062 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10063 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10064 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10065 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10066 // C)". 10067 10068 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10069 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10070 if (!LDiff || !RDiff || *LDiff != *RDiff) 10071 return false; 10072 10073 if (LDiff->isMinValue()) 10074 return true; 10075 10076 APInt FoundRHSLimit; 10077 10078 if (Pred == CmpInst::ICMP_ULT) { 10079 FoundRHSLimit = -(*RDiff); 10080 } else { 10081 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10082 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10083 } 10084 10085 // Try to prove (1) or (2), as needed. 10086 return isAvailableAtLoopEntry(FoundRHS, L) && 10087 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10088 getConstant(FoundRHSLimit)); 10089 } 10090 10091 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10092 const SCEV *LHS, const SCEV *RHS, 10093 const SCEV *FoundLHS, 10094 const SCEV *FoundRHS, unsigned Depth) { 10095 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10096 10097 auto ClearOnExit = make_scope_exit([&]() { 10098 if (LPhi) { 10099 bool Erased = PendingMerges.erase(LPhi); 10100 assert(Erased && "Failed to erase LPhi!"); 10101 (void)Erased; 10102 } 10103 if (RPhi) { 10104 bool Erased = PendingMerges.erase(RPhi); 10105 assert(Erased && "Failed to erase RPhi!"); 10106 (void)Erased; 10107 } 10108 }); 10109 10110 // Find respective Phis and check that they are not being pending. 10111 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10112 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10113 if (!PendingMerges.insert(Phi).second) 10114 return false; 10115 LPhi = Phi; 10116 } 10117 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10118 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10119 // If we detect a loop of Phi nodes being processed by this method, for 10120 // example: 10121 // 10122 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10123 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10124 // 10125 // we don't want to deal with a case that complex, so return conservative 10126 // answer false. 10127 if (!PendingMerges.insert(Phi).second) 10128 return false; 10129 RPhi = Phi; 10130 } 10131 10132 // If none of LHS, RHS is a Phi, nothing to do here. 10133 if (!LPhi && !RPhi) 10134 return false; 10135 10136 // If there is a SCEVUnknown Phi we are interested in, make it left. 10137 if (!LPhi) { 10138 std::swap(LHS, RHS); 10139 std::swap(FoundLHS, FoundRHS); 10140 std::swap(LPhi, RPhi); 10141 Pred = ICmpInst::getSwappedPredicate(Pred); 10142 } 10143 10144 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10145 const BasicBlock *LBB = LPhi->getParent(); 10146 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10147 10148 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10149 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10150 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10151 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10152 }; 10153 10154 if (RPhi && RPhi->getParent() == LBB) { 10155 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10156 // If we compare two Phis from the same block, and for each entry block 10157 // the predicate is true for incoming values from this block, then the 10158 // predicate is also true for the Phis. 10159 for (const BasicBlock *IncBB : predecessors(LBB)) { 10160 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10161 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10162 if (!ProvedEasily(L, R)) 10163 return false; 10164 } 10165 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10166 // Case two: RHS is also a Phi from the same basic block, and it is an 10167 // AddRec. It means that there is a loop which has both AddRec and Unknown 10168 // PHIs, for it we can compare incoming values of AddRec from above the loop 10169 // and latch with their respective incoming values of LPhi. 10170 // TODO: Generalize to handle loops with many inputs in a header. 10171 if (LPhi->getNumIncomingValues() != 2) return false; 10172 10173 auto *RLoop = RAR->getLoop(); 10174 auto *Predecessor = RLoop->getLoopPredecessor(); 10175 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10176 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10177 if (!ProvedEasily(L1, RAR->getStart())) 10178 return false; 10179 auto *Latch = RLoop->getLoopLatch(); 10180 assert(Latch && "Loop with AddRec with no latch?"); 10181 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10182 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10183 return false; 10184 } else { 10185 // In all other cases go over inputs of LHS and compare each of them to RHS, 10186 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10187 // At this point RHS is either a non-Phi, or it is a Phi from some block 10188 // different from LBB. 10189 for (const BasicBlock *IncBB : predecessors(LBB)) { 10190 // Check that RHS is available in this block. 10191 if (!dominates(RHS, IncBB)) 10192 return false; 10193 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10194 if (!ProvedEasily(L, RHS)) 10195 return false; 10196 } 10197 } 10198 return true; 10199 } 10200 10201 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10202 const SCEV *LHS, const SCEV *RHS, 10203 const SCEV *FoundLHS, 10204 const SCEV *FoundRHS) { 10205 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10206 return true; 10207 10208 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10209 return true; 10210 10211 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10212 FoundLHS, FoundRHS) || 10213 // ~x < ~y --> x > y 10214 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10215 getNotSCEV(FoundRHS), 10216 getNotSCEV(FoundLHS)); 10217 } 10218 10219 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10220 template <typename MinMaxExprType> 10221 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10222 const SCEV *Candidate) { 10223 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10224 if (!MinMaxExpr) 10225 return false; 10226 10227 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10228 } 10229 10230 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10231 ICmpInst::Predicate Pred, 10232 const SCEV *LHS, const SCEV *RHS) { 10233 // If both sides are affine addrecs for the same loop, with equal 10234 // steps, and we know the recurrences don't wrap, then we only 10235 // need to check the predicate on the starting values. 10236 10237 if (!ICmpInst::isRelational(Pred)) 10238 return false; 10239 10240 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10241 if (!LAR) 10242 return false; 10243 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10244 if (!RAR) 10245 return false; 10246 if (LAR->getLoop() != RAR->getLoop()) 10247 return false; 10248 if (!LAR->isAffine() || !RAR->isAffine()) 10249 return false; 10250 10251 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10252 return false; 10253 10254 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10255 SCEV::FlagNSW : SCEV::FlagNUW; 10256 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10257 return false; 10258 10259 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10260 } 10261 10262 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10263 /// expression? 10264 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10265 ICmpInst::Predicate Pred, 10266 const SCEV *LHS, const SCEV *RHS) { 10267 switch (Pred) { 10268 default: 10269 return false; 10270 10271 case ICmpInst::ICMP_SGE: 10272 std::swap(LHS, RHS); 10273 LLVM_FALLTHROUGH; 10274 case ICmpInst::ICMP_SLE: 10275 return 10276 // min(A, ...) <= A 10277 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10278 // A <= max(A, ...) 10279 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10280 10281 case ICmpInst::ICMP_UGE: 10282 std::swap(LHS, RHS); 10283 LLVM_FALLTHROUGH; 10284 case ICmpInst::ICMP_ULE: 10285 return 10286 // min(A, ...) <= A 10287 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10288 // A <= max(A, ...) 10289 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10290 } 10291 10292 llvm_unreachable("covered switch fell through?!"); 10293 } 10294 10295 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10296 const SCEV *LHS, const SCEV *RHS, 10297 const SCEV *FoundLHS, 10298 const SCEV *FoundRHS, 10299 unsigned Depth) { 10300 assert(getTypeSizeInBits(LHS->getType()) == 10301 getTypeSizeInBits(RHS->getType()) && 10302 "LHS and RHS have different sizes?"); 10303 assert(getTypeSizeInBits(FoundLHS->getType()) == 10304 getTypeSizeInBits(FoundRHS->getType()) && 10305 "FoundLHS and FoundRHS have different sizes?"); 10306 // We want to avoid hurting the compile time with analysis of too big trees. 10307 if (Depth > MaxSCEVOperationsImplicationDepth) 10308 return false; 10309 // We only want to work with ICMP_SGT comparison so far. 10310 // TODO: Extend to ICMP_UGT? 10311 if (Pred == ICmpInst::ICMP_SLT) { 10312 Pred = ICmpInst::ICMP_SGT; 10313 std::swap(LHS, RHS); 10314 std::swap(FoundLHS, FoundRHS); 10315 } 10316 if (Pred != ICmpInst::ICMP_SGT) 10317 return false; 10318 10319 auto GetOpFromSExt = [&](const SCEV *S) { 10320 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10321 return Ext->getOperand(); 10322 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10323 // the constant in some cases. 10324 return S; 10325 }; 10326 10327 // Acquire values from extensions. 10328 auto *OrigLHS = LHS; 10329 auto *OrigFoundLHS = FoundLHS; 10330 LHS = GetOpFromSExt(LHS); 10331 FoundLHS = GetOpFromSExt(FoundLHS); 10332 10333 // Is the SGT predicate can be proved trivially or using the found context. 10334 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10335 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10336 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10337 FoundRHS, Depth + 1); 10338 }; 10339 10340 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10341 // We want to avoid creation of any new non-constant SCEV. Since we are 10342 // going to compare the operands to RHS, we should be certain that we don't 10343 // need any size extensions for this. So let's decline all cases when the 10344 // sizes of types of LHS and RHS do not match. 10345 // TODO: Maybe try to get RHS from sext to catch more cases? 10346 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10347 return false; 10348 10349 // Should not overflow. 10350 if (!LHSAddExpr->hasNoSignedWrap()) 10351 return false; 10352 10353 auto *LL = LHSAddExpr->getOperand(0); 10354 auto *LR = LHSAddExpr->getOperand(1); 10355 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10356 10357 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10358 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10359 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10360 }; 10361 // Try to prove the following rule: 10362 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10363 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10364 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10365 return true; 10366 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10367 Value *LL, *LR; 10368 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10369 10370 using namespace llvm::PatternMatch; 10371 10372 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10373 // Rules for division. 10374 // We are going to perform some comparisons with Denominator and its 10375 // derivative expressions. In general case, creating a SCEV for it may 10376 // lead to a complex analysis of the entire graph, and in particular it 10377 // can request trip count recalculation for the same loop. This would 10378 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10379 // this, we only want to create SCEVs that are constants in this section. 10380 // So we bail if Denominator is not a constant. 10381 if (!isa<ConstantInt>(LR)) 10382 return false; 10383 10384 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10385 10386 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10387 // then a SCEV for the numerator already exists and matches with FoundLHS. 10388 auto *Numerator = getExistingSCEV(LL); 10389 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10390 return false; 10391 10392 // Make sure that the numerator matches with FoundLHS and the denominator 10393 // is positive. 10394 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10395 return false; 10396 10397 auto *DTy = Denominator->getType(); 10398 auto *FRHSTy = FoundRHS->getType(); 10399 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10400 // One of types is a pointer and another one is not. We cannot extend 10401 // them properly to a wider type, so let us just reject this case. 10402 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10403 // to avoid this check. 10404 return false; 10405 10406 // Given that: 10407 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10408 auto *WTy = getWiderType(DTy, FRHSTy); 10409 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10410 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10411 10412 // Try to prove the following rule: 10413 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10414 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10415 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10416 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10417 if (isKnownNonPositive(RHS) && 10418 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10419 return true; 10420 10421 // Try to prove the following rule: 10422 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10423 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10424 // If we divide it by Denominator > 2, then: 10425 // 1. If FoundLHS is negative, then the result is 0. 10426 // 2. If FoundLHS is non-negative, then the result is non-negative. 10427 // Anyways, the result is non-negative. 10428 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10429 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10430 if (isKnownNegative(RHS) && 10431 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10432 return true; 10433 } 10434 } 10435 10436 // If our expression contained SCEVUnknown Phis, and we split it down and now 10437 // need to prove something for them, try to prove the predicate for every 10438 // possible incoming values of those Phis. 10439 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10440 return true; 10441 10442 return false; 10443 } 10444 10445 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10446 const SCEV *LHS, const SCEV *RHS) { 10447 // zext x u<= sext x, sext x s<= zext x 10448 switch (Pred) { 10449 case ICmpInst::ICMP_SGE: 10450 std::swap(LHS, RHS); 10451 LLVM_FALLTHROUGH; 10452 case ICmpInst::ICMP_SLE: { 10453 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10454 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10455 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10456 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10457 return true; 10458 break; 10459 } 10460 case ICmpInst::ICMP_UGE: 10461 std::swap(LHS, RHS); 10462 LLVM_FALLTHROUGH; 10463 case ICmpInst::ICMP_ULE: { 10464 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10465 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10466 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10467 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10468 return true; 10469 break; 10470 } 10471 default: 10472 break; 10473 }; 10474 return false; 10475 } 10476 10477 bool 10478 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10479 const SCEV *LHS, const SCEV *RHS) { 10480 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10481 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10482 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10483 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10484 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10485 } 10486 10487 bool 10488 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10489 const SCEV *LHS, const SCEV *RHS, 10490 const SCEV *FoundLHS, 10491 const SCEV *FoundRHS) { 10492 switch (Pred) { 10493 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10494 case ICmpInst::ICMP_EQ: 10495 case ICmpInst::ICMP_NE: 10496 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10497 return true; 10498 break; 10499 case ICmpInst::ICMP_SLT: 10500 case ICmpInst::ICMP_SLE: 10501 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10502 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10503 return true; 10504 break; 10505 case ICmpInst::ICMP_SGT: 10506 case ICmpInst::ICMP_SGE: 10507 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10508 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10509 return true; 10510 break; 10511 case ICmpInst::ICMP_ULT: 10512 case ICmpInst::ICMP_ULE: 10513 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10514 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10515 return true; 10516 break; 10517 case ICmpInst::ICMP_UGT: 10518 case ICmpInst::ICMP_UGE: 10519 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10520 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10521 return true; 10522 break; 10523 } 10524 10525 // Maybe it can be proved via operations? 10526 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10527 return true; 10528 10529 return false; 10530 } 10531 10532 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10533 const SCEV *LHS, 10534 const SCEV *RHS, 10535 const SCEV *FoundLHS, 10536 const SCEV *FoundRHS) { 10537 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10538 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10539 // reduce the compile time impact of this optimization. 10540 return false; 10541 10542 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10543 if (!Addend) 10544 return false; 10545 10546 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10547 10548 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10549 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10550 ConstantRange FoundLHSRange = 10551 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10552 10553 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10554 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10555 10556 // We can also compute the range of values for `LHS` that satisfy the 10557 // consequent, "`LHS` `Pred` `RHS`": 10558 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10559 ConstantRange SatisfyingLHSRange = 10560 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10561 10562 // The antecedent implies the consequent if every value of `LHS` that 10563 // satisfies the antecedent also satisfies the consequent. 10564 return SatisfyingLHSRange.contains(LHSRange); 10565 } 10566 10567 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10568 bool IsSigned, bool NoWrap) { 10569 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10570 10571 if (NoWrap) return false; 10572 10573 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10574 const SCEV *One = getOne(Stride->getType()); 10575 10576 if (IsSigned) { 10577 APInt MaxRHS = getSignedRangeMax(RHS); 10578 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10579 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10580 10581 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10582 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10583 } 10584 10585 APInt MaxRHS = getUnsignedRangeMax(RHS); 10586 APInt MaxValue = APInt::getMaxValue(BitWidth); 10587 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10588 10589 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10590 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10591 } 10592 10593 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10594 bool IsSigned, bool NoWrap) { 10595 if (NoWrap) return false; 10596 10597 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10598 const SCEV *One = getOne(Stride->getType()); 10599 10600 if (IsSigned) { 10601 APInt MinRHS = getSignedRangeMin(RHS); 10602 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10603 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10604 10605 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10606 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10607 } 10608 10609 APInt MinRHS = getUnsignedRangeMin(RHS); 10610 APInt MinValue = APInt::getMinValue(BitWidth); 10611 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10612 10613 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10614 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10615 } 10616 10617 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10618 bool Equality) { 10619 const SCEV *One = getOne(Step->getType()); 10620 Delta = Equality ? getAddExpr(Delta, Step) 10621 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10622 return getUDivExpr(Delta, Step); 10623 } 10624 10625 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10626 const SCEV *Stride, 10627 const SCEV *End, 10628 unsigned BitWidth, 10629 bool IsSigned) { 10630 10631 assert(!isKnownNonPositive(Stride) && 10632 "Stride is expected strictly positive!"); 10633 // Calculate the maximum backedge count based on the range of values 10634 // permitted by Start, End, and Stride. 10635 const SCEV *MaxBECount; 10636 APInt MinStart = 10637 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10638 10639 APInt StrideForMaxBECount = 10640 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10641 10642 // We already know that the stride is positive, so we paper over conservatism 10643 // in our range computation by forcing StrideForMaxBECount to be at least one. 10644 // In theory this is unnecessary, but we expect MaxBECount to be a 10645 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10646 // is nothing to constant fold it to). 10647 APInt One(BitWidth, 1, IsSigned); 10648 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10649 10650 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10651 : APInt::getMaxValue(BitWidth); 10652 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10653 10654 // Although End can be a MAX expression we estimate MaxEnd considering only 10655 // the case End = RHS of the loop termination condition. This is safe because 10656 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10657 // taken count. 10658 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10659 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10660 10661 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10662 getConstant(StrideForMaxBECount) /* Step */, 10663 false /* Equality */); 10664 10665 return MaxBECount; 10666 } 10667 10668 ScalarEvolution::ExitLimit 10669 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10670 const Loop *L, bool IsSigned, 10671 bool ControlsExit, bool AllowPredicates) { 10672 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10673 10674 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10675 bool PredicatedIV = false; 10676 10677 if (!IV && AllowPredicates) { 10678 // Try to make this an AddRec using runtime tests, in the first X 10679 // iterations of this loop, where X is the SCEV expression found by the 10680 // algorithm below. 10681 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10682 PredicatedIV = true; 10683 } 10684 10685 // Avoid weird loops 10686 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10687 return getCouldNotCompute(); 10688 10689 bool NoWrap = ControlsExit && 10690 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10691 10692 const SCEV *Stride = IV->getStepRecurrence(*this); 10693 10694 bool PositiveStride = isKnownPositive(Stride); 10695 10696 // Avoid negative or zero stride values. 10697 if (!PositiveStride) { 10698 // We can compute the correct backedge taken count for loops with unknown 10699 // strides if we can prove that the loop is not an infinite loop with side 10700 // effects. Here's the loop structure we are trying to handle - 10701 // 10702 // i = start 10703 // do { 10704 // A[i] = i; 10705 // i += s; 10706 // } while (i < end); 10707 // 10708 // The backedge taken count for such loops is evaluated as - 10709 // (max(end, start + stride) - start - 1) /u stride 10710 // 10711 // The additional preconditions that we need to check to prove correctness 10712 // of the above formula is as follows - 10713 // 10714 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10715 // NoWrap flag). 10716 // b) loop is single exit with no side effects. 10717 // 10718 // 10719 // Precondition a) implies that if the stride is negative, this is a single 10720 // trip loop. The backedge taken count formula reduces to zero in this case. 10721 // 10722 // Precondition b) implies that the unknown stride cannot be zero otherwise 10723 // we have UB. 10724 // 10725 // The positive stride case is the same as isKnownPositive(Stride) returning 10726 // true (original behavior of the function). 10727 // 10728 // We want to make sure that the stride is truly unknown as there are edge 10729 // cases where ScalarEvolution propagates no wrap flags to the 10730 // post-increment/decrement IV even though the increment/decrement operation 10731 // itself is wrapping. The computed backedge taken count may be wrong in 10732 // such cases. This is prevented by checking that the stride is not known to 10733 // be either positive or non-positive. For example, no wrap flags are 10734 // propagated to the post-increment IV of this loop with a trip count of 2 - 10735 // 10736 // unsigned char i; 10737 // for(i=127; i<128; i+=129) 10738 // A[i] = i; 10739 // 10740 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10741 !loopHasNoSideEffects(L)) 10742 return getCouldNotCompute(); 10743 } else if (!Stride->isOne() && 10744 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10745 // Avoid proven overflow cases: this will ensure that the backedge taken 10746 // count will not generate any unsigned overflow. Relaxed no-overflow 10747 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10748 // undefined behaviors like the case of C language. 10749 return getCouldNotCompute(); 10750 10751 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10752 : ICmpInst::ICMP_ULT; 10753 const SCEV *Start = IV->getStart(); 10754 const SCEV *End = RHS; 10755 // When the RHS is not invariant, we do not know the end bound of the loop and 10756 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10757 // calculate the MaxBECount, given the start, stride and max value for the end 10758 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10759 // checked above). 10760 if (!isLoopInvariant(RHS, L)) { 10761 const SCEV *MaxBECount = computeMaxBECountForLT( 10762 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10763 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10764 false /*MaxOrZero*/, Predicates); 10765 } 10766 // If the backedge is taken at least once, then it will be taken 10767 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10768 // is the LHS value of the less-than comparison the first time it is evaluated 10769 // and End is the RHS. 10770 const SCEV *BECountIfBackedgeTaken = 10771 computeBECount(getMinusSCEV(End, Start), Stride, false); 10772 // If the loop entry is guarded by the result of the backedge test of the 10773 // first loop iteration, then we know the backedge will be taken at least 10774 // once and so the backedge taken count is as above. If not then we use the 10775 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10776 // as if the backedge is taken at least once max(End,Start) is End and so the 10777 // result is as above, and if not max(End,Start) is Start so we get a backedge 10778 // count of zero. 10779 const SCEV *BECount; 10780 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10781 BECount = BECountIfBackedgeTaken; 10782 else { 10783 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10784 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10785 } 10786 10787 const SCEV *MaxBECount; 10788 bool MaxOrZero = false; 10789 if (isa<SCEVConstant>(BECount)) 10790 MaxBECount = BECount; 10791 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10792 // If we know exactly how many times the backedge will be taken if it's 10793 // taken at least once, then the backedge count will either be that or 10794 // zero. 10795 MaxBECount = BECountIfBackedgeTaken; 10796 MaxOrZero = true; 10797 } else { 10798 MaxBECount = computeMaxBECountForLT( 10799 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10800 } 10801 10802 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10803 !isa<SCEVCouldNotCompute>(BECount)) 10804 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10805 10806 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10807 } 10808 10809 ScalarEvolution::ExitLimit 10810 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10811 const Loop *L, bool IsSigned, 10812 bool ControlsExit, bool AllowPredicates) { 10813 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10814 // We handle only IV > Invariant 10815 if (!isLoopInvariant(RHS, L)) 10816 return getCouldNotCompute(); 10817 10818 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10819 if (!IV && AllowPredicates) 10820 // Try to make this an AddRec using runtime tests, in the first X 10821 // iterations of this loop, where X is the SCEV expression found by the 10822 // algorithm below. 10823 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10824 10825 // Avoid weird loops 10826 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10827 return getCouldNotCompute(); 10828 10829 bool NoWrap = ControlsExit && 10830 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10831 10832 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10833 10834 // Avoid negative or zero stride values 10835 if (!isKnownPositive(Stride)) 10836 return getCouldNotCompute(); 10837 10838 // Avoid proven overflow cases: this will ensure that the backedge taken count 10839 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10840 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10841 // behaviors like the case of C language. 10842 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10843 return getCouldNotCompute(); 10844 10845 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10846 : ICmpInst::ICMP_UGT; 10847 10848 const SCEV *Start = IV->getStart(); 10849 const SCEV *End = RHS; 10850 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10851 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10852 10853 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10854 10855 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10856 : getUnsignedRangeMax(Start); 10857 10858 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10859 : getUnsignedRangeMin(Stride); 10860 10861 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10862 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10863 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10864 10865 // Although End can be a MIN expression we estimate MinEnd considering only 10866 // the case End = RHS. This is safe because in the other case (Start - End) 10867 // is zero, leading to a zero maximum backedge taken count. 10868 APInt MinEnd = 10869 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10870 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10871 10872 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10873 ? BECount 10874 : computeBECount(getConstant(MaxStart - MinEnd), 10875 getConstant(MinStride), false); 10876 10877 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10878 MaxBECount = BECount; 10879 10880 return ExitLimit(BECount, MaxBECount, false, Predicates); 10881 } 10882 10883 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10884 ScalarEvolution &SE) const { 10885 if (Range.isFullSet()) // Infinite loop. 10886 return SE.getCouldNotCompute(); 10887 10888 // If the start is a non-zero constant, shift the range to simplify things. 10889 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10890 if (!SC->getValue()->isZero()) { 10891 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10892 Operands[0] = SE.getZero(SC->getType()); 10893 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10894 getNoWrapFlags(FlagNW)); 10895 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10896 return ShiftedAddRec->getNumIterationsInRange( 10897 Range.subtract(SC->getAPInt()), SE); 10898 // This is strange and shouldn't happen. 10899 return SE.getCouldNotCompute(); 10900 } 10901 10902 // The only time we can solve this is when we have all constant indices. 10903 // Otherwise, we cannot determine the overflow conditions. 10904 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10905 return SE.getCouldNotCompute(); 10906 10907 // Okay at this point we know that all elements of the chrec are constants and 10908 // that the start element is zero. 10909 10910 // First check to see if the range contains zero. If not, the first 10911 // iteration exits. 10912 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10913 if (!Range.contains(APInt(BitWidth, 0))) 10914 return SE.getZero(getType()); 10915 10916 if (isAffine()) { 10917 // If this is an affine expression then we have this situation: 10918 // Solve {0,+,A} in Range === Ax in Range 10919 10920 // We know that zero is in the range. If A is positive then we know that 10921 // the upper value of the range must be the first possible exit value. 10922 // If A is negative then the lower of the range is the last possible loop 10923 // value. Also note that we already checked for a full range. 10924 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10925 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10926 10927 // The exit value should be (End+A)/A. 10928 APInt ExitVal = (End + A).udiv(A); 10929 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10930 10931 // Evaluate at the exit value. If we really did fall out of the valid 10932 // range, then we computed our trip count, otherwise wrap around or other 10933 // things must have happened. 10934 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10935 if (Range.contains(Val->getValue())) 10936 return SE.getCouldNotCompute(); // Something strange happened 10937 10938 // Ensure that the previous value is in the range. This is a sanity check. 10939 assert(Range.contains( 10940 EvaluateConstantChrecAtConstant(this, 10941 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10942 "Linear scev computation is off in a bad way!"); 10943 return SE.getConstant(ExitValue); 10944 } 10945 10946 if (isQuadratic()) { 10947 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10948 return SE.getConstant(S.getValue()); 10949 } 10950 10951 return SE.getCouldNotCompute(); 10952 } 10953 10954 const SCEVAddRecExpr * 10955 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10956 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10957 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10958 // but in this case we cannot guarantee that the value returned will be an 10959 // AddRec because SCEV does not have a fixed point where it stops 10960 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10961 // may happen if we reach arithmetic depth limit while simplifying. So we 10962 // construct the returned value explicitly. 10963 SmallVector<const SCEV *, 3> Ops; 10964 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10965 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10966 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10967 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10968 // We know that the last operand is not a constant zero (otherwise it would 10969 // have been popped out earlier). This guarantees us that if the result has 10970 // the same last operand, then it will also not be popped out, meaning that 10971 // the returned value will be an AddRec. 10972 const SCEV *Last = getOperand(getNumOperands() - 1); 10973 assert(!Last->isZero() && "Recurrency with zero step?"); 10974 Ops.push_back(Last); 10975 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10976 SCEV::FlagAnyWrap)); 10977 } 10978 10979 // Return true when S contains at least an undef value. 10980 static inline bool containsUndefs(const SCEV *S) { 10981 return SCEVExprContains(S, [](const SCEV *S) { 10982 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10983 return isa<UndefValue>(SU->getValue()); 10984 return false; 10985 }); 10986 } 10987 10988 namespace { 10989 10990 // Collect all steps of SCEV expressions. 10991 struct SCEVCollectStrides { 10992 ScalarEvolution &SE; 10993 SmallVectorImpl<const SCEV *> &Strides; 10994 10995 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10996 : SE(SE), Strides(S) {} 10997 10998 bool follow(const SCEV *S) { 10999 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11000 Strides.push_back(AR->getStepRecurrence(SE)); 11001 return true; 11002 } 11003 11004 bool isDone() const { return false; } 11005 }; 11006 11007 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11008 struct SCEVCollectTerms { 11009 SmallVectorImpl<const SCEV *> &Terms; 11010 11011 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11012 11013 bool follow(const SCEV *S) { 11014 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11015 isa<SCEVSignExtendExpr>(S)) { 11016 if (!containsUndefs(S)) 11017 Terms.push_back(S); 11018 11019 // Stop recursion: once we collected a term, do not walk its operands. 11020 return false; 11021 } 11022 11023 // Keep looking. 11024 return true; 11025 } 11026 11027 bool isDone() const { return false; } 11028 }; 11029 11030 // Check if a SCEV contains an AddRecExpr. 11031 struct SCEVHasAddRec { 11032 bool &ContainsAddRec; 11033 11034 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11035 ContainsAddRec = false; 11036 } 11037 11038 bool follow(const SCEV *S) { 11039 if (isa<SCEVAddRecExpr>(S)) { 11040 ContainsAddRec = true; 11041 11042 // Stop recursion: once we collected a term, do not walk its operands. 11043 return false; 11044 } 11045 11046 // Keep looking. 11047 return true; 11048 } 11049 11050 bool isDone() const { return false; } 11051 }; 11052 11053 // Find factors that are multiplied with an expression that (possibly as a 11054 // subexpression) contains an AddRecExpr. In the expression: 11055 // 11056 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11057 // 11058 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11059 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11060 // parameters as they form a product with an induction variable. 11061 // 11062 // This collector expects all array size parameters to be in the same MulExpr. 11063 // It might be necessary to later add support for collecting parameters that are 11064 // spread over different nested MulExpr. 11065 struct SCEVCollectAddRecMultiplies { 11066 SmallVectorImpl<const SCEV *> &Terms; 11067 ScalarEvolution &SE; 11068 11069 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11070 : Terms(T), SE(SE) {} 11071 11072 bool follow(const SCEV *S) { 11073 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11074 bool HasAddRec = false; 11075 SmallVector<const SCEV *, 0> Operands; 11076 for (auto Op : Mul->operands()) { 11077 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11078 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11079 Operands.push_back(Op); 11080 } else if (Unknown) { 11081 HasAddRec = true; 11082 } else { 11083 bool ContainsAddRec = false; 11084 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11085 visitAll(Op, ContiansAddRec); 11086 HasAddRec |= ContainsAddRec; 11087 } 11088 } 11089 if (Operands.size() == 0) 11090 return true; 11091 11092 if (!HasAddRec) 11093 return false; 11094 11095 Terms.push_back(SE.getMulExpr(Operands)); 11096 // Stop recursion: once we collected a term, do not walk its operands. 11097 return false; 11098 } 11099 11100 // Keep looking. 11101 return true; 11102 } 11103 11104 bool isDone() const { return false; } 11105 }; 11106 11107 } // end anonymous namespace 11108 11109 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11110 /// two places: 11111 /// 1) The strides of AddRec expressions. 11112 /// 2) Unknowns that are multiplied with AddRec expressions. 11113 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11114 SmallVectorImpl<const SCEV *> &Terms) { 11115 SmallVector<const SCEV *, 4> Strides; 11116 SCEVCollectStrides StrideCollector(*this, Strides); 11117 visitAll(Expr, StrideCollector); 11118 11119 LLVM_DEBUG({ 11120 dbgs() << "Strides:\n"; 11121 for (const SCEV *S : Strides) 11122 dbgs() << *S << "\n"; 11123 }); 11124 11125 for (const SCEV *S : Strides) { 11126 SCEVCollectTerms TermCollector(Terms); 11127 visitAll(S, TermCollector); 11128 } 11129 11130 LLVM_DEBUG({ 11131 dbgs() << "Terms:\n"; 11132 for (const SCEV *T : Terms) 11133 dbgs() << *T << "\n"; 11134 }); 11135 11136 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11137 visitAll(Expr, MulCollector); 11138 } 11139 11140 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11141 SmallVectorImpl<const SCEV *> &Terms, 11142 SmallVectorImpl<const SCEV *> &Sizes) { 11143 int Last = Terms.size() - 1; 11144 const SCEV *Step = Terms[Last]; 11145 11146 // End of recursion. 11147 if (Last == 0) { 11148 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11149 SmallVector<const SCEV *, 2> Qs; 11150 for (const SCEV *Op : M->operands()) 11151 if (!isa<SCEVConstant>(Op)) 11152 Qs.push_back(Op); 11153 11154 Step = SE.getMulExpr(Qs); 11155 } 11156 11157 Sizes.push_back(Step); 11158 return true; 11159 } 11160 11161 for (const SCEV *&Term : Terms) { 11162 // Normalize the terms before the next call to findArrayDimensionsRec. 11163 const SCEV *Q, *R; 11164 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11165 11166 // Bail out when GCD does not evenly divide one of the terms. 11167 if (!R->isZero()) 11168 return false; 11169 11170 Term = Q; 11171 } 11172 11173 // Remove all SCEVConstants. 11174 Terms.erase( 11175 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11176 Terms.end()); 11177 11178 if (Terms.size() > 0) 11179 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11180 return false; 11181 11182 Sizes.push_back(Step); 11183 return true; 11184 } 11185 11186 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11187 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11188 for (const SCEV *T : Terms) 11189 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11190 return true; 11191 return false; 11192 } 11193 11194 // Return the number of product terms in S. 11195 static inline int numberOfTerms(const SCEV *S) { 11196 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11197 return Expr->getNumOperands(); 11198 return 1; 11199 } 11200 11201 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11202 if (isa<SCEVConstant>(T)) 11203 return nullptr; 11204 11205 if (isa<SCEVUnknown>(T)) 11206 return T; 11207 11208 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11209 SmallVector<const SCEV *, 2> Factors; 11210 for (const SCEV *Op : M->operands()) 11211 if (!isa<SCEVConstant>(Op)) 11212 Factors.push_back(Op); 11213 11214 return SE.getMulExpr(Factors); 11215 } 11216 11217 return T; 11218 } 11219 11220 /// Return the size of an element read or written by Inst. 11221 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11222 Type *Ty; 11223 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11224 Ty = Store->getValueOperand()->getType(); 11225 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11226 Ty = Load->getType(); 11227 else 11228 return nullptr; 11229 11230 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11231 return getSizeOfExpr(ETy, Ty); 11232 } 11233 11234 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11235 SmallVectorImpl<const SCEV *> &Sizes, 11236 const SCEV *ElementSize) { 11237 if (Terms.size() < 1 || !ElementSize) 11238 return; 11239 11240 // Early return when Terms do not contain parameters: we do not delinearize 11241 // non parametric SCEVs. 11242 if (!containsParameters(Terms)) 11243 return; 11244 11245 LLVM_DEBUG({ 11246 dbgs() << "Terms:\n"; 11247 for (const SCEV *T : Terms) 11248 dbgs() << *T << "\n"; 11249 }); 11250 11251 // Remove duplicates. 11252 array_pod_sort(Terms.begin(), Terms.end()); 11253 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11254 11255 // Put larger terms first. 11256 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11257 return numberOfTerms(LHS) > numberOfTerms(RHS); 11258 }); 11259 11260 // Try to divide all terms by the element size. If term is not divisible by 11261 // element size, proceed with the original term. 11262 for (const SCEV *&Term : Terms) { 11263 const SCEV *Q, *R; 11264 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11265 if (!Q->isZero()) 11266 Term = Q; 11267 } 11268 11269 SmallVector<const SCEV *, 4> NewTerms; 11270 11271 // Remove constant factors. 11272 for (const SCEV *T : Terms) 11273 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11274 NewTerms.push_back(NewT); 11275 11276 LLVM_DEBUG({ 11277 dbgs() << "Terms after sorting:\n"; 11278 for (const SCEV *T : NewTerms) 11279 dbgs() << *T << "\n"; 11280 }); 11281 11282 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11283 Sizes.clear(); 11284 return; 11285 } 11286 11287 // The last element to be pushed into Sizes is the size of an element. 11288 Sizes.push_back(ElementSize); 11289 11290 LLVM_DEBUG({ 11291 dbgs() << "Sizes:\n"; 11292 for (const SCEV *S : Sizes) 11293 dbgs() << *S << "\n"; 11294 }); 11295 } 11296 11297 void ScalarEvolution::computeAccessFunctions( 11298 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11299 SmallVectorImpl<const SCEV *> &Sizes) { 11300 // Early exit in case this SCEV is not an affine multivariate function. 11301 if (Sizes.empty()) 11302 return; 11303 11304 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11305 if (!AR->isAffine()) 11306 return; 11307 11308 const SCEV *Res = Expr; 11309 int Last = Sizes.size() - 1; 11310 for (int i = Last; i >= 0; i--) { 11311 const SCEV *Q, *R; 11312 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11313 11314 LLVM_DEBUG({ 11315 dbgs() << "Res: " << *Res << "\n"; 11316 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11317 dbgs() << "Res divided by Sizes[i]:\n"; 11318 dbgs() << "Quotient: " << *Q << "\n"; 11319 dbgs() << "Remainder: " << *R << "\n"; 11320 }); 11321 11322 Res = Q; 11323 11324 // Do not record the last subscript corresponding to the size of elements in 11325 // the array. 11326 if (i == Last) { 11327 11328 // Bail out if the remainder is too complex. 11329 if (isa<SCEVAddRecExpr>(R)) { 11330 Subscripts.clear(); 11331 Sizes.clear(); 11332 return; 11333 } 11334 11335 continue; 11336 } 11337 11338 // Record the access function for the current subscript. 11339 Subscripts.push_back(R); 11340 } 11341 11342 // Also push in last position the remainder of the last division: it will be 11343 // the access function of the innermost dimension. 11344 Subscripts.push_back(Res); 11345 11346 std::reverse(Subscripts.begin(), Subscripts.end()); 11347 11348 LLVM_DEBUG({ 11349 dbgs() << "Subscripts:\n"; 11350 for (const SCEV *S : Subscripts) 11351 dbgs() << *S << "\n"; 11352 }); 11353 } 11354 11355 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11356 /// sizes of an array access. Returns the remainder of the delinearization that 11357 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11358 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11359 /// expressions in the stride and base of a SCEV corresponding to the 11360 /// computation of a GCD (greatest common divisor) of base and stride. When 11361 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11362 /// 11363 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11364 /// 11365 /// void foo(long n, long m, long o, double A[n][m][o]) { 11366 /// 11367 /// for (long i = 0; i < n; i++) 11368 /// for (long j = 0; j < m; j++) 11369 /// for (long k = 0; k < o; k++) 11370 /// A[i][j][k] = 1.0; 11371 /// } 11372 /// 11373 /// the delinearization input is the following AddRec SCEV: 11374 /// 11375 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11376 /// 11377 /// From this SCEV, we are able to say that the base offset of the access is %A 11378 /// because it appears as an offset that does not divide any of the strides in 11379 /// the loops: 11380 /// 11381 /// CHECK: Base offset: %A 11382 /// 11383 /// and then SCEV->delinearize determines the size of some of the dimensions of 11384 /// the array as these are the multiples by which the strides are happening: 11385 /// 11386 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11387 /// 11388 /// Note that the outermost dimension remains of UnknownSize because there are 11389 /// no strides that would help identifying the size of the last dimension: when 11390 /// the array has been statically allocated, one could compute the size of that 11391 /// dimension by dividing the overall size of the array by the size of the known 11392 /// dimensions: %m * %o * 8. 11393 /// 11394 /// Finally delinearize provides the access functions for the array reference 11395 /// that does correspond to A[i][j][k] of the above C testcase: 11396 /// 11397 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11398 /// 11399 /// The testcases are checking the output of a function pass: 11400 /// DelinearizationPass that walks through all loads and stores of a function 11401 /// asking for the SCEV of the memory access with respect to all enclosing 11402 /// loops, calling SCEV->delinearize on that and printing the results. 11403 void ScalarEvolution::delinearize(const SCEV *Expr, 11404 SmallVectorImpl<const SCEV *> &Subscripts, 11405 SmallVectorImpl<const SCEV *> &Sizes, 11406 const SCEV *ElementSize) { 11407 // First step: collect parametric terms. 11408 SmallVector<const SCEV *, 4> Terms; 11409 collectParametricTerms(Expr, Terms); 11410 11411 if (Terms.empty()) 11412 return; 11413 11414 // Second step: find subscript sizes. 11415 findArrayDimensions(Terms, Sizes, ElementSize); 11416 11417 if (Sizes.empty()) 11418 return; 11419 11420 // Third step: compute the access functions for each subscript. 11421 computeAccessFunctions(Expr, Subscripts, Sizes); 11422 11423 if (Subscripts.empty()) 11424 return; 11425 11426 LLVM_DEBUG({ 11427 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11428 dbgs() << "ArrayDecl[UnknownSize]"; 11429 for (const SCEV *S : Sizes) 11430 dbgs() << "[" << *S << "]"; 11431 11432 dbgs() << "\nArrayRef"; 11433 for (const SCEV *S : Subscripts) 11434 dbgs() << "[" << *S << "]"; 11435 dbgs() << "\n"; 11436 }); 11437 } 11438 11439 bool ScalarEvolution::getIndexExpressionsFromGEP( 11440 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11441 SmallVectorImpl<int> &Sizes) { 11442 assert(Subscripts.empty() && Sizes.empty() && 11443 "Expected output lists to be empty on entry to this function."); 11444 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11445 Type *Ty = GEP->getPointerOperandType(); 11446 bool DroppedFirstDim = false; 11447 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11448 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11449 if (i == 1) { 11450 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11451 Ty = PtrTy->getElementType(); 11452 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11453 Ty = ArrayTy->getElementType(); 11454 } else { 11455 Subscripts.clear(); 11456 Sizes.clear(); 11457 return false; 11458 } 11459 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11460 if (Const->getValue()->isZero()) { 11461 DroppedFirstDim = true; 11462 continue; 11463 } 11464 Subscripts.push_back(Expr); 11465 continue; 11466 } 11467 11468 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11469 if (!ArrayTy) { 11470 Subscripts.clear(); 11471 Sizes.clear(); 11472 return false; 11473 } 11474 11475 Subscripts.push_back(Expr); 11476 if (!(DroppedFirstDim && i == 2)) 11477 Sizes.push_back(ArrayTy->getNumElements()); 11478 11479 Ty = ArrayTy->getElementType(); 11480 } 11481 return !Subscripts.empty(); 11482 } 11483 11484 //===----------------------------------------------------------------------===// 11485 // SCEVCallbackVH Class Implementation 11486 //===----------------------------------------------------------------------===// 11487 11488 void ScalarEvolution::SCEVCallbackVH::deleted() { 11489 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11490 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11491 SE->ConstantEvolutionLoopExitValue.erase(PN); 11492 SE->eraseValueFromMap(getValPtr()); 11493 // this now dangles! 11494 } 11495 11496 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11497 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11498 11499 // Forget all the expressions associated with users of the old value, 11500 // so that future queries will recompute the expressions using the new 11501 // value. 11502 Value *Old = getValPtr(); 11503 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11504 SmallPtrSet<User *, 8> Visited; 11505 while (!Worklist.empty()) { 11506 User *U = Worklist.pop_back_val(); 11507 // Deleting the Old value will cause this to dangle. Postpone 11508 // that until everything else is done. 11509 if (U == Old) 11510 continue; 11511 if (!Visited.insert(U).second) 11512 continue; 11513 if (PHINode *PN = dyn_cast<PHINode>(U)) 11514 SE->ConstantEvolutionLoopExitValue.erase(PN); 11515 SE->eraseValueFromMap(U); 11516 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11517 } 11518 // Delete the Old value. 11519 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11520 SE->ConstantEvolutionLoopExitValue.erase(PN); 11521 SE->eraseValueFromMap(Old); 11522 // this now dangles! 11523 } 11524 11525 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11526 : CallbackVH(V), SE(se) {} 11527 11528 //===----------------------------------------------------------------------===// 11529 // ScalarEvolution Class Implementation 11530 //===----------------------------------------------------------------------===// 11531 11532 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11533 AssumptionCache &AC, DominatorTree &DT, 11534 LoopInfo &LI) 11535 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11536 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11537 LoopDispositions(64), BlockDispositions(64) { 11538 // To use guards for proving predicates, we need to scan every instruction in 11539 // relevant basic blocks, and not just terminators. Doing this is a waste of 11540 // time if the IR does not actually contain any calls to 11541 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11542 // 11543 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11544 // to _add_ guards to the module when there weren't any before, and wants 11545 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11546 // efficient in lieu of being smart in that rather obscure case. 11547 11548 auto *GuardDecl = F.getParent()->getFunction( 11549 Intrinsic::getName(Intrinsic::experimental_guard)); 11550 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11551 } 11552 11553 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11554 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11555 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11556 ValueExprMap(std::move(Arg.ValueExprMap)), 11557 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11558 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11559 PendingMerges(std::move(Arg.PendingMerges)), 11560 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11561 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11562 PredicatedBackedgeTakenCounts( 11563 std::move(Arg.PredicatedBackedgeTakenCounts)), 11564 ConstantEvolutionLoopExitValue( 11565 std::move(Arg.ConstantEvolutionLoopExitValue)), 11566 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11567 LoopDispositions(std::move(Arg.LoopDispositions)), 11568 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11569 BlockDispositions(std::move(Arg.BlockDispositions)), 11570 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11571 SignedRanges(std::move(Arg.SignedRanges)), 11572 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11573 UniquePreds(std::move(Arg.UniquePreds)), 11574 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11575 LoopUsers(std::move(Arg.LoopUsers)), 11576 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11577 FirstUnknown(Arg.FirstUnknown) { 11578 Arg.FirstUnknown = nullptr; 11579 } 11580 11581 ScalarEvolution::~ScalarEvolution() { 11582 // Iterate through all the SCEVUnknown instances and call their 11583 // destructors, so that they release their references to their values. 11584 for (SCEVUnknown *U = FirstUnknown; U;) { 11585 SCEVUnknown *Tmp = U; 11586 U = U->Next; 11587 Tmp->~SCEVUnknown(); 11588 } 11589 FirstUnknown = nullptr; 11590 11591 ExprValueMap.clear(); 11592 ValueExprMap.clear(); 11593 HasRecMap.clear(); 11594 11595 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11596 // that a loop had multiple computable exits. 11597 for (auto &BTCI : BackedgeTakenCounts) 11598 BTCI.second.clear(); 11599 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11600 BTCI.second.clear(); 11601 11602 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11603 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11604 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11605 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11606 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11607 } 11608 11609 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11610 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11611 } 11612 11613 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11614 const Loop *L) { 11615 // Print all inner loops first 11616 for (Loop *I : *L) 11617 PrintLoopInfo(OS, SE, I); 11618 11619 OS << "Loop "; 11620 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11621 OS << ": "; 11622 11623 SmallVector<BasicBlock *, 8> ExitingBlocks; 11624 L->getExitingBlocks(ExitingBlocks); 11625 if (ExitingBlocks.size() != 1) 11626 OS << "<multiple exits> "; 11627 11628 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11629 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11630 else 11631 OS << "Unpredictable backedge-taken count.\n"; 11632 11633 if (ExitingBlocks.size() > 1) 11634 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11635 OS << " exit count for " << ExitingBlock->getName() << ": " 11636 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11637 } 11638 11639 OS << "Loop "; 11640 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11641 OS << ": "; 11642 11643 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11644 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11645 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11646 OS << ", actual taken count either this or zero."; 11647 } else { 11648 OS << "Unpredictable max backedge-taken count. "; 11649 } 11650 11651 OS << "\n" 11652 "Loop "; 11653 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11654 OS << ": "; 11655 11656 SCEVUnionPredicate Pred; 11657 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11658 if (!isa<SCEVCouldNotCompute>(PBT)) { 11659 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11660 OS << " Predicates:\n"; 11661 Pred.print(OS, 4); 11662 } else { 11663 OS << "Unpredictable predicated backedge-taken count. "; 11664 } 11665 OS << "\n"; 11666 11667 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11668 OS << "Loop "; 11669 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11670 OS << ": "; 11671 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11672 } 11673 } 11674 11675 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11676 switch (LD) { 11677 case ScalarEvolution::LoopVariant: 11678 return "Variant"; 11679 case ScalarEvolution::LoopInvariant: 11680 return "Invariant"; 11681 case ScalarEvolution::LoopComputable: 11682 return "Computable"; 11683 } 11684 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11685 } 11686 11687 void ScalarEvolution::print(raw_ostream &OS) const { 11688 // ScalarEvolution's implementation of the print method is to print 11689 // out SCEV values of all instructions that are interesting. Doing 11690 // this potentially causes it to create new SCEV objects though, 11691 // which technically conflicts with the const qualifier. This isn't 11692 // observable from outside the class though, so casting away the 11693 // const isn't dangerous. 11694 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11695 11696 if (ClassifyExpressions) { 11697 OS << "Classifying expressions for: "; 11698 F.printAsOperand(OS, /*PrintType=*/false); 11699 OS << "\n"; 11700 for (Instruction &I : instructions(F)) 11701 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11702 OS << I << '\n'; 11703 OS << " --> "; 11704 const SCEV *SV = SE.getSCEV(&I); 11705 SV->print(OS); 11706 if (!isa<SCEVCouldNotCompute>(SV)) { 11707 OS << " U: "; 11708 SE.getUnsignedRange(SV).print(OS); 11709 OS << " S: "; 11710 SE.getSignedRange(SV).print(OS); 11711 } 11712 11713 const Loop *L = LI.getLoopFor(I.getParent()); 11714 11715 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11716 if (AtUse != SV) { 11717 OS << " --> "; 11718 AtUse->print(OS); 11719 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11720 OS << " U: "; 11721 SE.getUnsignedRange(AtUse).print(OS); 11722 OS << " S: "; 11723 SE.getSignedRange(AtUse).print(OS); 11724 } 11725 } 11726 11727 if (L) { 11728 OS << "\t\t" "Exits: "; 11729 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11730 if (!SE.isLoopInvariant(ExitValue, L)) { 11731 OS << "<<Unknown>>"; 11732 } else { 11733 OS << *ExitValue; 11734 } 11735 11736 bool First = true; 11737 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11738 if (First) { 11739 OS << "\t\t" "LoopDispositions: { "; 11740 First = false; 11741 } else { 11742 OS << ", "; 11743 } 11744 11745 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11746 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11747 } 11748 11749 for (auto *InnerL : depth_first(L)) { 11750 if (InnerL == L) 11751 continue; 11752 if (First) { 11753 OS << "\t\t" "LoopDispositions: { "; 11754 First = false; 11755 } else { 11756 OS << ", "; 11757 } 11758 11759 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11760 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11761 } 11762 11763 OS << " }"; 11764 } 11765 11766 OS << "\n"; 11767 } 11768 } 11769 11770 OS << "Determining loop execution counts for: "; 11771 F.printAsOperand(OS, /*PrintType=*/false); 11772 OS << "\n"; 11773 for (Loop *I : LI) 11774 PrintLoopInfo(OS, &SE, I); 11775 } 11776 11777 ScalarEvolution::LoopDisposition 11778 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11779 auto &Values = LoopDispositions[S]; 11780 for (auto &V : Values) { 11781 if (V.getPointer() == L) 11782 return V.getInt(); 11783 } 11784 Values.emplace_back(L, LoopVariant); 11785 LoopDisposition D = computeLoopDisposition(S, L); 11786 auto &Values2 = LoopDispositions[S]; 11787 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11788 if (V.getPointer() == L) { 11789 V.setInt(D); 11790 break; 11791 } 11792 } 11793 return D; 11794 } 11795 11796 ScalarEvolution::LoopDisposition 11797 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11798 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11799 case scConstant: 11800 return LoopInvariant; 11801 case scTruncate: 11802 case scZeroExtend: 11803 case scSignExtend: 11804 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11805 case scAddRecExpr: { 11806 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11807 11808 // If L is the addrec's loop, it's computable. 11809 if (AR->getLoop() == L) 11810 return LoopComputable; 11811 11812 // Add recurrences are never invariant in the function-body (null loop). 11813 if (!L) 11814 return LoopVariant; 11815 11816 // Everything that is not defined at loop entry is variant. 11817 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11818 return LoopVariant; 11819 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11820 " dominate the contained loop's header?"); 11821 11822 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11823 if (AR->getLoop()->contains(L)) 11824 return LoopInvariant; 11825 11826 // This recurrence is variant w.r.t. L if any of its operands 11827 // are variant. 11828 for (auto *Op : AR->operands()) 11829 if (!isLoopInvariant(Op, L)) 11830 return LoopVariant; 11831 11832 // Otherwise it's loop-invariant. 11833 return LoopInvariant; 11834 } 11835 case scAddExpr: 11836 case scMulExpr: 11837 case scUMaxExpr: 11838 case scSMaxExpr: 11839 case scUMinExpr: 11840 case scSMinExpr: { 11841 bool HasVarying = false; 11842 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11843 LoopDisposition D = getLoopDisposition(Op, L); 11844 if (D == LoopVariant) 11845 return LoopVariant; 11846 if (D == LoopComputable) 11847 HasVarying = true; 11848 } 11849 return HasVarying ? LoopComputable : LoopInvariant; 11850 } 11851 case scUDivExpr: { 11852 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11853 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11854 if (LD == LoopVariant) 11855 return LoopVariant; 11856 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11857 if (RD == LoopVariant) 11858 return LoopVariant; 11859 return (LD == LoopInvariant && RD == LoopInvariant) ? 11860 LoopInvariant : LoopComputable; 11861 } 11862 case scUnknown: 11863 // All non-instruction values are loop invariant. All instructions are loop 11864 // invariant if they are not contained in the specified loop. 11865 // Instructions are never considered invariant in the function body 11866 // (null loop) because they are defined within the "loop". 11867 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11868 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11869 return LoopInvariant; 11870 case scCouldNotCompute: 11871 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11872 } 11873 llvm_unreachable("Unknown SCEV kind!"); 11874 } 11875 11876 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11877 return getLoopDisposition(S, L) == LoopInvariant; 11878 } 11879 11880 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11881 return getLoopDisposition(S, L) == LoopComputable; 11882 } 11883 11884 ScalarEvolution::BlockDisposition 11885 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11886 auto &Values = BlockDispositions[S]; 11887 for (auto &V : Values) { 11888 if (V.getPointer() == BB) 11889 return V.getInt(); 11890 } 11891 Values.emplace_back(BB, DoesNotDominateBlock); 11892 BlockDisposition D = computeBlockDisposition(S, BB); 11893 auto &Values2 = BlockDispositions[S]; 11894 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11895 if (V.getPointer() == BB) { 11896 V.setInt(D); 11897 break; 11898 } 11899 } 11900 return D; 11901 } 11902 11903 ScalarEvolution::BlockDisposition 11904 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11905 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11906 case scConstant: 11907 return ProperlyDominatesBlock; 11908 case scTruncate: 11909 case scZeroExtend: 11910 case scSignExtend: 11911 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11912 case scAddRecExpr: { 11913 // This uses a "dominates" query instead of "properly dominates" query 11914 // to test for proper dominance too, because the instruction which 11915 // produces the addrec's value is a PHI, and a PHI effectively properly 11916 // dominates its entire containing block. 11917 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11918 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11919 return DoesNotDominateBlock; 11920 11921 // Fall through into SCEVNAryExpr handling. 11922 LLVM_FALLTHROUGH; 11923 } 11924 case scAddExpr: 11925 case scMulExpr: 11926 case scUMaxExpr: 11927 case scSMaxExpr: 11928 case scUMinExpr: 11929 case scSMinExpr: { 11930 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11931 bool Proper = true; 11932 for (const SCEV *NAryOp : NAry->operands()) { 11933 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11934 if (D == DoesNotDominateBlock) 11935 return DoesNotDominateBlock; 11936 if (D == DominatesBlock) 11937 Proper = false; 11938 } 11939 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11940 } 11941 case scUDivExpr: { 11942 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11943 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11944 BlockDisposition LD = getBlockDisposition(LHS, BB); 11945 if (LD == DoesNotDominateBlock) 11946 return DoesNotDominateBlock; 11947 BlockDisposition RD = getBlockDisposition(RHS, BB); 11948 if (RD == DoesNotDominateBlock) 11949 return DoesNotDominateBlock; 11950 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11951 ProperlyDominatesBlock : DominatesBlock; 11952 } 11953 case scUnknown: 11954 if (Instruction *I = 11955 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11956 if (I->getParent() == BB) 11957 return DominatesBlock; 11958 if (DT.properlyDominates(I->getParent(), BB)) 11959 return ProperlyDominatesBlock; 11960 return DoesNotDominateBlock; 11961 } 11962 return ProperlyDominatesBlock; 11963 case scCouldNotCompute: 11964 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11965 } 11966 llvm_unreachable("Unknown SCEV kind!"); 11967 } 11968 11969 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11970 return getBlockDisposition(S, BB) >= DominatesBlock; 11971 } 11972 11973 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11974 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11975 } 11976 11977 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11978 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11979 } 11980 11981 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11982 auto IsS = [&](const SCEV *X) { return S == X; }; 11983 auto ContainsS = [&](const SCEV *X) { 11984 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11985 }; 11986 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11987 } 11988 11989 void 11990 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11991 ValuesAtScopes.erase(S); 11992 LoopDispositions.erase(S); 11993 BlockDispositions.erase(S); 11994 UnsignedRanges.erase(S); 11995 SignedRanges.erase(S); 11996 ExprValueMap.erase(S); 11997 HasRecMap.erase(S); 11998 MinTrailingZerosCache.erase(S); 11999 12000 for (auto I = PredicatedSCEVRewrites.begin(); 12001 I != PredicatedSCEVRewrites.end();) { 12002 std::pair<const SCEV *, const Loop *> Entry = I->first; 12003 if (Entry.first == S) 12004 PredicatedSCEVRewrites.erase(I++); 12005 else 12006 ++I; 12007 } 12008 12009 auto RemoveSCEVFromBackedgeMap = 12010 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12011 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12012 BackedgeTakenInfo &BEInfo = I->second; 12013 if (BEInfo.hasOperand(S, this)) { 12014 BEInfo.clear(); 12015 Map.erase(I++); 12016 } else 12017 ++I; 12018 } 12019 }; 12020 12021 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12022 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12023 } 12024 12025 void 12026 ScalarEvolution::getUsedLoops(const SCEV *S, 12027 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12028 struct FindUsedLoops { 12029 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12030 : LoopsUsed(LoopsUsed) {} 12031 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12032 bool follow(const SCEV *S) { 12033 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12034 LoopsUsed.insert(AR->getLoop()); 12035 return true; 12036 } 12037 12038 bool isDone() const { return false; } 12039 }; 12040 12041 FindUsedLoops F(LoopsUsed); 12042 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12043 } 12044 12045 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12046 SmallPtrSet<const Loop *, 8> LoopsUsed; 12047 getUsedLoops(S, LoopsUsed); 12048 for (auto *L : LoopsUsed) 12049 LoopUsers[L].push_back(S); 12050 } 12051 12052 void ScalarEvolution::verify() const { 12053 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12054 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12055 12056 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12057 12058 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12059 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12060 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12061 12062 const SCEV *visitConstant(const SCEVConstant *Constant) { 12063 return SE.getConstant(Constant->getAPInt()); 12064 } 12065 12066 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12067 return SE.getUnknown(Expr->getValue()); 12068 } 12069 12070 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12071 return SE.getCouldNotCompute(); 12072 } 12073 }; 12074 12075 SCEVMapper SCM(SE2); 12076 12077 while (!LoopStack.empty()) { 12078 auto *L = LoopStack.pop_back_val(); 12079 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12080 12081 auto *CurBECount = SCM.visit( 12082 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12083 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12084 12085 if (CurBECount == SE2.getCouldNotCompute() || 12086 NewBECount == SE2.getCouldNotCompute()) { 12087 // NB! This situation is legal, but is very suspicious -- whatever pass 12088 // change the loop to make a trip count go from could not compute to 12089 // computable or vice-versa *should have* invalidated SCEV. However, we 12090 // choose not to assert here (for now) since we don't want false 12091 // positives. 12092 continue; 12093 } 12094 12095 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12096 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12097 // not propagate undef aggressively). This means we can (and do) fail 12098 // verification in cases where a transform makes the trip count of a loop 12099 // go from "undef" to "undef+1" (say). The transform is fine, since in 12100 // both cases the loop iterates "undef" times, but SCEV thinks we 12101 // increased the trip count of the loop by 1 incorrectly. 12102 continue; 12103 } 12104 12105 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12106 SE.getTypeSizeInBits(NewBECount->getType())) 12107 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12108 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12109 SE.getTypeSizeInBits(NewBECount->getType())) 12110 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12111 12112 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12113 12114 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12115 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12116 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12117 dbgs() << "Old: " << *CurBECount << "\n"; 12118 dbgs() << "New: " << *NewBECount << "\n"; 12119 dbgs() << "Delta: " << *Delta << "\n"; 12120 std::abort(); 12121 } 12122 } 12123 } 12124 12125 bool ScalarEvolution::invalidate( 12126 Function &F, const PreservedAnalyses &PA, 12127 FunctionAnalysisManager::Invalidator &Inv) { 12128 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12129 // of its dependencies is invalidated. 12130 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12131 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12132 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12133 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12134 Inv.invalidate<LoopAnalysis>(F, PA); 12135 } 12136 12137 AnalysisKey ScalarEvolutionAnalysis::Key; 12138 12139 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12140 FunctionAnalysisManager &AM) { 12141 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12142 AM.getResult<AssumptionAnalysis>(F), 12143 AM.getResult<DominatorTreeAnalysis>(F), 12144 AM.getResult<LoopAnalysis>(F)); 12145 } 12146 12147 PreservedAnalyses 12148 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12149 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12150 return PreservedAnalyses::all(); 12151 } 12152 12153 PreservedAnalyses 12154 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12155 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12156 return PreservedAnalyses::all(); 12157 } 12158 12159 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12160 "Scalar Evolution Analysis", false, true) 12161 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12162 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12163 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12164 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12165 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12166 "Scalar Evolution Analysis", false, true) 12167 12168 char ScalarEvolutionWrapperPass::ID = 0; 12169 12170 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12171 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12172 } 12173 12174 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12175 SE.reset(new ScalarEvolution( 12176 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12177 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12178 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12179 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12180 return false; 12181 } 12182 12183 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12184 12185 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12186 SE->print(OS); 12187 } 12188 12189 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12190 if (!VerifySCEV) 12191 return; 12192 12193 SE->verify(); 12194 } 12195 12196 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12197 AU.setPreservesAll(); 12198 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12199 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12200 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12201 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12202 } 12203 12204 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12205 const SCEV *RHS) { 12206 FoldingSetNodeID ID; 12207 assert(LHS->getType() == RHS->getType() && 12208 "Type mismatch between LHS and RHS"); 12209 // Unique this node based on the arguments 12210 ID.AddInteger(SCEVPredicate::P_Equal); 12211 ID.AddPointer(LHS); 12212 ID.AddPointer(RHS); 12213 void *IP = nullptr; 12214 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12215 return S; 12216 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12217 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12218 UniquePreds.InsertNode(Eq, IP); 12219 return Eq; 12220 } 12221 12222 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12223 const SCEVAddRecExpr *AR, 12224 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12225 FoldingSetNodeID ID; 12226 // Unique this node based on the arguments 12227 ID.AddInteger(SCEVPredicate::P_Wrap); 12228 ID.AddPointer(AR); 12229 ID.AddInteger(AddedFlags); 12230 void *IP = nullptr; 12231 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12232 return S; 12233 auto *OF = new (SCEVAllocator) 12234 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12235 UniquePreds.InsertNode(OF, IP); 12236 return OF; 12237 } 12238 12239 namespace { 12240 12241 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12242 public: 12243 12244 /// Rewrites \p S in the context of a loop L and the SCEV predication 12245 /// infrastructure. 12246 /// 12247 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12248 /// equivalences present in \p Pred. 12249 /// 12250 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12251 /// \p NewPreds such that the result will be an AddRecExpr. 12252 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12253 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12254 SCEVUnionPredicate *Pred) { 12255 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12256 return Rewriter.visit(S); 12257 } 12258 12259 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12260 if (Pred) { 12261 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12262 for (auto *Pred : ExprPreds) 12263 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12264 if (IPred->getLHS() == Expr) 12265 return IPred->getRHS(); 12266 } 12267 return convertToAddRecWithPreds(Expr); 12268 } 12269 12270 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12271 const SCEV *Operand = visit(Expr->getOperand()); 12272 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12273 if (AR && AR->getLoop() == L && AR->isAffine()) { 12274 // This couldn't be folded because the operand didn't have the nuw 12275 // flag. Add the nusw flag as an assumption that we could make. 12276 const SCEV *Step = AR->getStepRecurrence(SE); 12277 Type *Ty = Expr->getType(); 12278 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12279 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12280 SE.getSignExtendExpr(Step, Ty), L, 12281 AR->getNoWrapFlags()); 12282 } 12283 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12284 } 12285 12286 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12287 const SCEV *Operand = visit(Expr->getOperand()); 12288 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12289 if (AR && AR->getLoop() == L && AR->isAffine()) { 12290 // This couldn't be folded because the operand didn't have the nsw 12291 // flag. Add the nssw flag as an assumption that we could make. 12292 const SCEV *Step = AR->getStepRecurrence(SE); 12293 Type *Ty = Expr->getType(); 12294 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12295 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12296 SE.getSignExtendExpr(Step, Ty), L, 12297 AR->getNoWrapFlags()); 12298 } 12299 return SE.getSignExtendExpr(Operand, Expr->getType()); 12300 } 12301 12302 private: 12303 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12304 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12305 SCEVUnionPredicate *Pred) 12306 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12307 12308 bool addOverflowAssumption(const SCEVPredicate *P) { 12309 if (!NewPreds) { 12310 // Check if we've already made this assumption. 12311 return Pred && Pred->implies(P); 12312 } 12313 NewPreds->insert(P); 12314 return true; 12315 } 12316 12317 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12318 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12319 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12320 return addOverflowAssumption(A); 12321 } 12322 12323 // If \p Expr represents a PHINode, we try to see if it can be represented 12324 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12325 // to add this predicate as a runtime overflow check, we return the AddRec. 12326 // If \p Expr does not meet these conditions (is not a PHI node, or we 12327 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12328 // return \p Expr. 12329 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12330 if (!isa<PHINode>(Expr->getValue())) 12331 return Expr; 12332 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12333 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12334 if (!PredicatedRewrite) 12335 return Expr; 12336 for (auto *P : PredicatedRewrite->second){ 12337 // Wrap predicates from outer loops are not supported. 12338 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12339 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12340 if (L != AR->getLoop()) 12341 return Expr; 12342 } 12343 if (!addOverflowAssumption(P)) 12344 return Expr; 12345 } 12346 return PredicatedRewrite->first; 12347 } 12348 12349 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12350 SCEVUnionPredicate *Pred; 12351 const Loop *L; 12352 }; 12353 12354 } // end anonymous namespace 12355 12356 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12357 SCEVUnionPredicate &Preds) { 12358 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12359 } 12360 12361 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12362 const SCEV *S, const Loop *L, 12363 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12364 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12365 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12366 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12367 12368 if (!AddRec) 12369 return nullptr; 12370 12371 // Since the transformation was successful, we can now transfer the SCEV 12372 // predicates. 12373 for (auto *P : TransformPreds) 12374 Preds.insert(P); 12375 12376 return AddRec; 12377 } 12378 12379 /// SCEV predicates 12380 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12381 SCEVPredicateKind Kind) 12382 : FastID(ID), Kind(Kind) {} 12383 12384 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12385 const SCEV *LHS, const SCEV *RHS) 12386 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12387 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12388 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12389 } 12390 12391 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12392 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12393 12394 if (!Op) 12395 return false; 12396 12397 return Op->LHS == LHS && Op->RHS == RHS; 12398 } 12399 12400 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12401 12402 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12403 12404 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12405 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12406 } 12407 12408 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12409 const SCEVAddRecExpr *AR, 12410 IncrementWrapFlags Flags) 12411 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12412 12413 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12414 12415 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12416 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12417 12418 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12419 } 12420 12421 bool SCEVWrapPredicate::isAlwaysTrue() const { 12422 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12423 IncrementWrapFlags IFlags = Flags; 12424 12425 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12426 IFlags = clearFlags(IFlags, IncrementNSSW); 12427 12428 return IFlags == IncrementAnyWrap; 12429 } 12430 12431 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12432 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12433 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12434 OS << "<nusw>"; 12435 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12436 OS << "<nssw>"; 12437 OS << "\n"; 12438 } 12439 12440 SCEVWrapPredicate::IncrementWrapFlags 12441 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12442 ScalarEvolution &SE) { 12443 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12444 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12445 12446 // We can safely transfer the NSW flag as NSSW. 12447 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12448 ImpliedFlags = IncrementNSSW; 12449 12450 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12451 // If the increment is positive, the SCEV NUW flag will also imply the 12452 // WrapPredicate NUSW flag. 12453 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12454 if (Step->getValue()->getValue().isNonNegative()) 12455 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12456 } 12457 12458 return ImpliedFlags; 12459 } 12460 12461 /// Union predicates don't get cached so create a dummy set ID for it. 12462 SCEVUnionPredicate::SCEVUnionPredicate() 12463 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12464 12465 bool SCEVUnionPredicate::isAlwaysTrue() const { 12466 return all_of(Preds, 12467 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12468 } 12469 12470 ArrayRef<const SCEVPredicate *> 12471 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12472 auto I = SCEVToPreds.find(Expr); 12473 if (I == SCEVToPreds.end()) 12474 return ArrayRef<const SCEVPredicate *>(); 12475 return I->second; 12476 } 12477 12478 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12479 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12480 return all_of(Set->Preds, 12481 [this](const SCEVPredicate *I) { return this->implies(I); }); 12482 12483 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12484 if (ScevPredsIt == SCEVToPreds.end()) 12485 return false; 12486 auto &SCEVPreds = ScevPredsIt->second; 12487 12488 return any_of(SCEVPreds, 12489 [N](const SCEVPredicate *I) { return I->implies(N); }); 12490 } 12491 12492 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12493 12494 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12495 for (auto Pred : Preds) 12496 Pred->print(OS, Depth); 12497 } 12498 12499 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12500 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12501 for (auto Pred : Set->Preds) 12502 add(Pred); 12503 return; 12504 } 12505 12506 if (implies(N)) 12507 return; 12508 12509 const SCEV *Key = N->getExpr(); 12510 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12511 " associated expression!"); 12512 12513 SCEVToPreds[Key].push_back(N); 12514 Preds.push_back(N); 12515 } 12516 12517 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12518 Loop &L) 12519 : SE(SE), L(L) {} 12520 12521 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12522 const SCEV *Expr = SE.getSCEV(V); 12523 RewriteEntry &Entry = RewriteMap[Expr]; 12524 12525 // If we already have an entry and the version matches, return it. 12526 if (Entry.second && Generation == Entry.first) 12527 return Entry.second; 12528 12529 // We found an entry but it's stale. Rewrite the stale entry 12530 // according to the current predicate. 12531 if (Entry.second) 12532 Expr = Entry.second; 12533 12534 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12535 Entry = {Generation, NewSCEV}; 12536 12537 return NewSCEV; 12538 } 12539 12540 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12541 if (!BackedgeCount) { 12542 SCEVUnionPredicate BackedgePred; 12543 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12544 addPredicate(BackedgePred); 12545 } 12546 return BackedgeCount; 12547 } 12548 12549 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12550 if (Preds.implies(&Pred)) 12551 return; 12552 Preds.add(&Pred); 12553 updateGeneration(); 12554 } 12555 12556 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12557 return Preds; 12558 } 12559 12560 void PredicatedScalarEvolution::updateGeneration() { 12561 // If the generation number wrapped recompute everything. 12562 if (++Generation == 0) { 12563 for (auto &II : RewriteMap) { 12564 const SCEV *Rewritten = II.second.second; 12565 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12566 } 12567 } 12568 } 12569 12570 void PredicatedScalarEvolution::setNoOverflow( 12571 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12572 const SCEV *Expr = getSCEV(V); 12573 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12574 12575 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12576 12577 // Clear the statically implied flags. 12578 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12579 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12580 12581 auto II = FlagsMap.insert({V, Flags}); 12582 if (!II.second) 12583 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12584 } 12585 12586 bool PredicatedScalarEvolution::hasNoOverflow( 12587 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12588 const SCEV *Expr = getSCEV(V); 12589 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12590 12591 Flags = SCEVWrapPredicate::clearFlags( 12592 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12593 12594 auto II = FlagsMap.find(V); 12595 12596 if (II != FlagsMap.end()) 12597 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12598 12599 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12600 } 12601 12602 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12603 const SCEV *Expr = this->getSCEV(V); 12604 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12605 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12606 12607 if (!New) 12608 return nullptr; 12609 12610 for (auto *P : NewPreds) 12611 Preds.add(P); 12612 12613 updateGeneration(); 12614 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12615 return New; 12616 } 12617 12618 PredicatedScalarEvolution::PredicatedScalarEvolution( 12619 const PredicatedScalarEvolution &Init) 12620 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12621 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12622 for (auto I : Init.FlagsMap) 12623 FlagsMap.insert(I); 12624 } 12625 12626 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12627 // For each block. 12628 for (auto *BB : L.getBlocks()) 12629 for (auto &I : *BB) { 12630 if (!SE.isSCEVable(I.getType())) 12631 continue; 12632 12633 auto *Expr = SE.getSCEV(&I); 12634 auto II = RewriteMap.find(Expr); 12635 12636 if (II == RewriteMap.end()) 12637 continue; 12638 12639 // Don't print things that are not interesting. 12640 if (II->second.second == Expr) 12641 continue; 12642 12643 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12644 OS.indent(Depth + 2) << *Expr << "\n"; 12645 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12646 } 12647 } 12648 12649 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12650 // arbitrary expressions. 12651 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12652 // 4, A / B becomes X / 8). 12653 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12654 const SCEV *&RHS) { 12655 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12656 if (Add == nullptr || Add->getNumOperands() != 2) 12657 return false; 12658 12659 const SCEV *A = Add->getOperand(1); 12660 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12661 12662 if (Mul == nullptr) 12663 return false; 12664 12665 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12666 // (SomeExpr + (-(SomeExpr / B) * B)). 12667 if (Expr == getURemExpr(A, B)) { 12668 LHS = A; 12669 RHS = B; 12670 return true; 12671 } 12672 return false; 12673 }; 12674 12675 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12676 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12677 return MatchURemWithDivisor(Mul->getOperand(1)) || 12678 MatchURemWithDivisor(Mul->getOperand(2)); 12679 12680 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12681 if (Mul->getNumOperands() == 2) 12682 return MatchURemWithDivisor(Mul->getOperand(1)) || 12683 MatchURemWithDivisor(Mul->getOperand(0)) || 12684 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12685 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12686 return false; 12687 } 12688