1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/APInt.h" 63 #include "llvm/ADT/ArrayRef.h" 64 #include "llvm/ADT/DenseMap.h" 65 #include "llvm/ADT/DepthFirstIterator.h" 66 #include "llvm/ADT/EquivalenceClasses.h" 67 #include "llvm/ADT/FoldingSet.h" 68 #include "llvm/ADT/None.h" 69 #include "llvm/ADT/Optional.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/ADT/ScopeExit.h" 72 #include "llvm/ADT/Sequence.h" 73 #include "llvm/ADT/SetVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallSet.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/Statistic.h" 78 #include "llvm/ADT/StringRef.h" 79 #include "llvm/Analysis/AssumptionCache.h" 80 #include "llvm/Analysis/ConstantFolding.h" 81 #include "llvm/Analysis/InstructionSimplify.h" 82 #include "llvm/Analysis/LoopInfo.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.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/Pass.h" 115 #include "llvm/Support/Casting.h" 116 #include "llvm/Support/CommandLine.h" 117 #include "llvm/Support/Compiler.h" 118 #include "llvm/Support/Debug.h" 119 #include "llvm/Support/ErrorHandling.h" 120 #include "llvm/Support/KnownBits.h" 121 #include "llvm/Support/SaveAndRestore.h" 122 #include "llvm/Support/raw_ostream.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <climits> 126 #include <cstddef> 127 #include <cstdint> 128 #include <cstdlib> 129 #include <map> 130 #include <memory> 131 #include <tuple> 132 #include <utility> 133 #include <vector> 134 135 using namespace llvm; 136 137 #define DEBUG_TYPE "scalar-evolution" 138 139 STATISTIC(NumArrayLenItCounts, 140 "Number of trip counts computed with array length"); 141 STATISTIC(NumTripCountsComputed, 142 "Number of loops with predictable loop counts"); 143 STATISTIC(NumTripCountsNotComputed, 144 "Number of loops without predictable loop counts"); 145 STATISTIC(NumBruteForceTripCountsComputed, 146 "Number of loops with trip counts computed by force"); 147 148 static cl::opt<unsigned> 149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 150 cl::desc("Maximum number of iterations SCEV will " 151 "symbolically execute a constant " 152 "derived loop"), 153 cl::init(100)); 154 155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 156 static cl::opt<bool> VerifySCEV( 157 "verify-scev", cl::Hidden, 158 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 159 static cl::opt<bool> 160 VerifySCEVMap("verify-scev-maps", cl::Hidden, 161 cl::desc("Verify no dangling value in ScalarEvolution's " 162 "ExprValueMap (slow)")); 163 164 static cl::opt<unsigned> MulOpsInlineThreshold( 165 "scev-mulops-inline-threshold", cl::Hidden, 166 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 167 cl::init(32)); 168 169 static cl::opt<unsigned> AddOpsInlineThreshold( 170 "scev-addops-inline-threshold", cl::Hidden, 171 cl::desc("Threshold for inlining addition operands into a SCEV"), 172 cl::init(500)); 173 174 static cl::opt<unsigned> MaxSCEVCompareDepth( 175 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 176 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 180 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 181 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 182 cl::init(2)); 183 184 static cl::opt<unsigned> MaxValueCompareDepth( 185 "scalar-evolution-max-value-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive value complexity comparisons"), 187 cl::init(2)); 188 189 static cl::opt<unsigned> 190 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive arithmetics"), 192 cl::init(32)); 193 194 static cl::opt<unsigned> MaxConstantEvolvingDepth( 195 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 197 198 static cl::opt<unsigned> 199 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden, 200 cl::desc("Maximum depth of recursive SExt/ZExt"), 201 cl::init(8)); 202 203 static cl::opt<unsigned> 204 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 205 cl::desc("Max coefficients in AddRec during evolving"), 206 cl::init(16)); 207 208 static cl::opt<bool> VersionUnknown( 209 "scev-version-unknown", cl::Hidden, 210 cl::desc("Use predicated scalar evolution to version SCEVUnknowns"), 211 cl::init(false)); 212 213 //===----------------------------------------------------------------------===// 214 // SCEV class definitions 215 //===----------------------------------------------------------------------===// 216 217 //===----------------------------------------------------------------------===// 218 // Implementation of the SCEV class. 219 // 220 221 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 222 LLVM_DUMP_METHOD void SCEV::dump() const { 223 print(dbgs()); 224 dbgs() << '\n'; 225 } 226 #endif 227 228 void SCEV::print(raw_ostream &OS) const { 229 switch (static_cast<SCEVTypes>(getSCEVType())) { 230 case scConstant: 231 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 232 return; 233 case scTruncate: { 234 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 235 const SCEV *Op = Trunc->getOperand(); 236 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 237 << *Trunc->getType() << ")"; 238 return; 239 } 240 case scZeroExtend: { 241 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 242 const SCEV *Op = ZExt->getOperand(); 243 OS << "(zext " << *Op->getType() << " " << *Op << " to " 244 << *ZExt->getType() << ")"; 245 return; 246 } 247 case scSignExtend: { 248 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 249 const SCEV *Op = SExt->getOperand(); 250 OS << "(sext " << *Op->getType() << " " << *Op << " to " 251 << *SExt->getType() << ")"; 252 return; 253 } 254 case scAddRecExpr: { 255 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 256 OS << "{" << *AR->getOperand(0); 257 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 258 OS << ",+," << *AR->getOperand(i); 259 OS << "}<"; 260 if (AR->hasNoUnsignedWrap()) 261 OS << "nuw><"; 262 if (AR->hasNoSignedWrap()) 263 OS << "nsw><"; 264 if (AR->hasNoSelfWrap() && 265 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 266 OS << "nw><"; 267 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 268 OS << ">"; 269 return; 270 } 271 case scAddExpr: 272 case scMulExpr: 273 case scUMaxExpr: 274 case scSMaxExpr: { 275 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 276 const char *OpStr = nullptr; 277 switch (NAry->getSCEVType()) { 278 case scAddExpr: OpStr = " + "; break; 279 case scMulExpr: OpStr = " * "; break; 280 case scUMaxExpr: OpStr = " umax "; break; 281 case scSMaxExpr: OpStr = " smax "; break; 282 } 283 OS << "("; 284 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 285 I != E; ++I) { 286 OS << **I; 287 if (std::next(I) != E) 288 OS << OpStr; 289 } 290 OS << ")"; 291 switch (NAry->getSCEVType()) { 292 case scAddExpr: 293 case scMulExpr: 294 if (NAry->hasNoUnsignedWrap()) 295 OS << "<nuw>"; 296 if (NAry->hasNoSignedWrap()) 297 OS << "<nsw>"; 298 } 299 return; 300 } 301 case scUDivExpr: { 302 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 303 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 304 return; 305 } 306 case scUnknown: { 307 const SCEVUnknown *U = cast<SCEVUnknown>(this); 308 Type *AllocTy; 309 if (U->isSizeOf(AllocTy)) { 310 OS << "sizeof(" << *AllocTy << ")"; 311 return; 312 } 313 if (U->isAlignOf(AllocTy)) { 314 OS << "alignof(" << *AllocTy << ")"; 315 return; 316 } 317 318 Type *CTy; 319 Constant *FieldNo; 320 if (U->isOffsetOf(CTy, FieldNo)) { 321 OS << "offsetof(" << *CTy << ", "; 322 FieldNo->printAsOperand(OS, false); 323 OS << ")"; 324 return; 325 } 326 327 // Otherwise just print it normally. 328 U->getValue()->printAsOperand(OS, false); 329 return; 330 } 331 case scCouldNotCompute: 332 OS << "***COULDNOTCOMPUTE***"; 333 return; 334 } 335 llvm_unreachable("Unknown SCEV kind!"); 336 } 337 338 Type *SCEV::getType() const { 339 switch (static_cast<SCEVTypes>(getSCEVType())) { 340 case scConstant: 341 return cast<SCEVConstant>(this)->getType(); 342 case scTruncate: 343 case scZeroExtend: 344 case scSignExtend: 345 return cast<SCEVCastExpr>(this)->getType(); 346 case scAddRecExpr: 347 case scMulExpr: 348 case scUMaxExpr: 349 case scSMaxExpr: 350 return cast<SCEVNAryExpr>(this)->getType(); 351 case scAddExpr: 352 return cast<SCEVAddExpr>(this)->getType(); 353 case scUDivExpr: 354 return cast<SCEVUDivExpr>(this)->getType(); 355 case scUnknown: 356 return cast<SCEVUnknown>(this)->getType(); 357 case scCouldNotCompute: 358 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 359 } 360 llvm_unreachable("Unknown SCEV kind!"); 361 } 362 363 bool SCEV::isZero() const { 364 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 365 return SC->getValue()->isZero(); 366 return false; 367 } 368 369 bool SCEV::isOne() const { 370 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 371 return SC->getValue()->isOne(); 372 return false; 373 } 374 375 bool SCEV::isAllOnesValue() const { 376 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 377 return SC->getValue()->isMinusOne(); 378 return false; 379 } 380 381 bool SCEV::isNonConstantNegative() const { 382 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 383 if (!Mul) return false; 384 385 // If there is a constant factor, it will be first. 386 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 387 if (!SC) return false; 388 389 // Return true if the value is negative, this matches things like (-42 * V). 390 return SC->getAPInt().isNegative(); 391 } 392 393 SCEVCouldNotCompute::SCEVCouldNotCompute() : 394 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 395 396 bool SCEVCouldNotCompute::classof(const SCEV *S) { 397 return S->getSCEVType() == scCouldNotCompute; 398 } 399 400 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 401 FoldingSetNodeID ID; 402 ID.AddInteger(scConstant); 403 ID.AddPointer(V); 404 void *IP = nullptr; 405 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 406 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 407 UniqueSCEVs.InsertNode(S, IP); 408 return S; 409 } 410 411 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 412 return getConstant(ConstantInt::get(getContext(), Val)); 413 } 414 415 const SCEV * 416 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 417 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 418 return getConstant(ConstantInt::get(ITy, V, isSigned)); 419 } 420 421 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 422 unsigned SCEVTy, const SCEV *op, Type *ty) 423 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 424 425 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 426 const SCEV *op, Type *ty) 427 : SCEVCastExpr(ID, scTruncate, op, ty) { 428 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 429 (Ty->isIntegerTy() || Ty->isPointerTy()) && 430 "Cannot truncate non-integer value!"); 431 } 432 433 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 434 const SCEV *op, Type *ty) 435 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 436 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 437 (Ty->isIntegerTy() || Ty->isPointerTy()) && 438 "Cannot zero extend non-integer value!"); 439 } 440 441 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 442 const SCEV *op, Type *ty) 443 : SCEVCastExpr(ID, scSignExtend, op, ty) { 444 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 445 (Ty->isIntegerTy() || Ty->isPointerTy()) && 446 "Cannot sign extend non-integer value!"); 447 } 448 449 void SCEVUnknown::deleted() { 450 // Clear this SCEVUnknown from various maps. 451 SE->forgetMemoizedResults(this); 452 453 // Remove this SCEVUnknown from the uniquing map. 454 SE->UniqueSCEVs.RemoveNode(this); 455 456 // Release the value. 457 setValPtr(nullptr); 458 } 459 460 void SCEVUnknown::allUsesReplacedWith(Value *New) { 461 // Remove this SCEVUnknown from the uniquing map. 462 SE->UniqueSCEVs.RemoveNode(this); 463 464 // Update this SCEVUnknown to point to the new value. This is needed 465 // because there may still be outstanding SCEVs which still point to 466 // this SCEVUnknown. 467 setValPtr(New); 468 } 469 470 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 471 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 472 if (VCE->getOpcode() == Instruction::PtrToInt) 473 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 474 if (CE->getOpcode() == Instruction::GetElementPtr && 475 CE->getOperand(0)->isNullValue() && 476 CE->getNumOperands() == 2) 477 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 478 if (CI->isOne()) { 479 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 480 ->getElementType(); 481 return true; 482 } 483 484 return false; 485 } 486 487 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 488 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 489 if (VCE->getOpcode() == Instruction::PtrToInt) 490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 491 if (CE->getOpcode() == Instruction::GetElementPtr && 492 CE->getOperand(0)->isNullValue()) { 493 Type *Ty = 494 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 495 if (StructType *STy = dyn_cast<StructType>(Ty)) 496 if (!STy->isPacked() && 497 CE->getNumOperands() == 3 && 498 CE->getOperand(1)->isNullValue()) { 499 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 500 if (CI->isOne() && 501 STy->getNumElements() == 2 && 502 STy->getElementType(0)->isIntegerTy(1)) { 503 AllocTy = STy->getElementType(1); 504 return true; 505 } 506 } 507 } 508 509 return false; 510 } 511 512 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 513 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 514 if (VCE->getOpcode() == Instruction::PtrToInt) 515 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 516 if (CE->getOpcode() == Instruction::GetElementPtr && 517 CE->getNumOperands() == 3 && 518 CE->getOperand(0)->isNullValue() && 519 CE->getOperand(1)->isNullValue()) { 520 Type *Ty = 521 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 522 // Ignore vector types here so that ScalarEvolutionExpander doesn't 523 // emit getelementptrs that index into vectors. 524 if (Ty->isStructTy() || Ty->isArrayTy()) { 525 CTy = Ty; 526 FieldNo = CE->getOperand(2); 527 return true; 528 } 529 } 530 531 return false; 532 } 533 534 //===----------------------------------------------------------------------===// 535 // SCEV Utilities 536 //===----------------------------------------------------------------------===// 537 538 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 539 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 540 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 541 /// have been previously deemed to be "equally complex" by this routine. It is 542 /// intended to avoid exponential time complexity in cases like: 543 /// 544 /// %a = f(%x, %y) 545 /// %b = f(%a, %a) 546 /// %c = f(%b, %b) 547 /// 548 /// %d = f(%x, %y) 549 /// %e = f(%d, %d) 550 /// %f = f(%e, %e) 551 /// 552 /// CompareValueComplexity(%f, %c) 553 /// 554 /// Since we do not continue running this routine on expression trees once we 555 /// have seen unequal values, there is no need to track them in the cache. 556 static int 557 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 558 const LoopInfo *const LI, Value *LV, Value *RV, 559 unsigned Depth) { 560 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 561 return 0; 562 563 // Order pointer values after integer values. This helps SCEVExpander form 564 // GEPs. 565 bool LIsPointer = LV->getType()->isPointerTy(), 566 RIsPointer = RV->getType()->isPointerTy(); 567 if (LIsPointer != RIsPointer) 568 return (int)LIsPointer - (int)RIsPointer; 569 570 // Compare getValueID values. 571 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 572 if (LID != RID) 573 return (int)LID - (int)RID; 574 575 // Sort arguments by their position. 576 if (const auto *LA = dyn_cast<Argument>(LV)) { 577 const auto *RA = cast<Argument>(RV); 578 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 579 return (int)LArgNo - (int)RArgNo; 580 } 581 582 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 583 const auto *RGV = cast<GlobalValue>(RV); 584 585 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 586 auto LT = GV->getLinkage(); 587 return !(GlobalValue::isPrivateLinkage(LT) || 588 GlobalValue::isInternalLinkage(LT)); 589 }; 590 591 // Use the names to distinguish the two values, but only if the 592 // names are semantically important. 593 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 594 return LGV->getName().compare(RGV->getName()); 595 } 596 597 // For instructions, compare their loop depth, and their operand count. This 598 // is pretty loose. 599 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 600 const auto *RInst = cast<Instruction>(RV); 601 602 // Compare loop depths. 603 const BasicBlock *LParent = LInst->getParent(), 604 *RParent = RInst->getParent(); 605 if (LParent != RParent) { 606 unsigned LDepth = LI->getLoopDepth(LParent), 607 RDepth = LI->getLoopDepth(RParent); 608 if (LDepth != RDepth) 609 return (int)LDepth - (int)RDepth; 610 } 611 612 // Compare the number of operands. 613 unsigned LNumOps = LInst->getNumOperands(), 614 RNumOps = RInst->getNumOperands(); 615 if (LNumOps != RNumOps) 616 return (int)LNumOps - (int)RNumOps; 617 618 for (unsigned Idx : seq(0u, LNumOps)) { 619 int Result = 620 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 621 RInst->getOperand(Idx), Depth + 1); 622 if (Result != 0) 623 return Result; 624 } 625 } 626 627 EqCacheValue.unionSets(LV, RV); 628 return 0; 629 } 630 631 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 632 // than RHS, respectively. A three-way result allows recursive comparisons to be 633 // more efficient. 634 static int CompareSCEVComplexity( 635 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 636 EquivalenceClasses<const Value *> &EqCacheValue, 637 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 638 DominatorTree &DT, unsigned Depth = 0) { 639 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 640 if (LHS == RHS) 641 return 0; 642 643 // Primarily, sort the SCEVs by their getSCEVType(). 644 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 645 if (LType != RType) 646 return (int)LType - (int)RType; 647 648 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 649 return 0; 650 // Aside from the getSCEVType() ordering, the particular ordering 651 // isn't very important except that it's beneficial to be consistent, 652 // so that (a + b) and (b + a) don't end up as different expressions. 653 switch (static_cast<SCEVTypes>(LType)) { 654 case scUnknown: { 655 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 656 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 657 658 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 659 RU->getValue(), Depth + 1); 660 if (X == 0) 661 EqCacheSCEV.unionSets(LHS, RHS); 662 return X; 663 } 664 665 case scConstant: { 666 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 667 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 668 669 // Compare constant values. 670 const APInt &LA = LC->getAPInt(); 671 const APInt &RA = RC->getAPInt(); 672 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 673 if (LBitWidth != RBitWidth) 674 return (int)LBitWidth - (int)RBitWidth; 675 return LA.ult(RA) ? -1 : 1; 676 } 677 678 case scAddRecExpr: { 679 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 680 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 681 682 // There is always a dominance between two recs that are used by one SCEV, 683 // so we can safely sort recs by loop header dominance. We require such 684 // order in getAddExpr. 685 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 686 if (LLoop != RLoop) { 687 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 688 assert(LHead != RHead && "Two loops share the same header?"); 689 if (DT.dominates(LHead, RHead)) 690 return 1; 691 else 692 assert(DT.dominates(RHead, LHead) && 693 "No dominance between recurrences used by one SCEV?"); 694 return -1; 695 } 696 697 // Addrec complexity grows with operand count. 698 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 699 if (LNumOps != RNumOps) 700 return (int)LNumOps - (int)RNumOps; 701 702 // Compare NoWrap flags. 703 if (LA->getNoWrapFlags() != RA->getNoWrapFlags()) 704 return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags(); 705 706 // Lexicographically compare. 707 for (unsigned i = 0; i != LNumOps; ++i) { 708 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 709 LA->getOperand(i), RA->getOperand(i), DT, 710 Depth + 1); 711 if (X != 0) 712 return X; 713 } 714 EqCacheSCEV.unionSets(LHS, RHS); 715 return 0; 716 } 717 718 case scAddExpr: 719 case scMulExpr: 720 case scSMaxExpr: 721 case scUMaxExpr: { 722 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 723 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 724 725 // Lexicographically compare n-ary expressions. 726 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 727 if (LNumOps != RNumOps) 728 return (int)LNumOps - (int)RNumOps; 729 730 // Compare NoWrap flags. 731 if (LC->getNoWrapFlags() != RC->getNoWrapFlags()) 732 return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags(); 733 734 for (unsigned i = 0; i != LNumOps; ++i) { 735 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 736 LC->getOperand(i), RC->getOperand(i), DT, 737 Depth + 1); 738 if (X != 0) 739 return X; 740 } 741 EqCacheSCEV.unionSets(LHS, RHS); 742 return 0; 743 } 744 745 case scUDivExpr: { 746 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 747 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 748 749 // Lexicographically compare udiv expressions. 750 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 751 RC->getLHS(), DT, Depth + 1); 752 if (X != 0) 753 return X; 754 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 755 RC->getRHS(), DT, Depth + 1); 756 if (X == 0) 757 EqCacheSCEV.unionSets(LHS, RHS); 758 return X; 759 } 760 761 case scTruncate: 762 case scZeroExtend: 763 case scSignExtend: { 764 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 765 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 766 767 // Compare cast expressions by operand. 768 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 769 LC->getOperand(), RC->getOperand(), DT, 770 Depth + 1); 771 if (X == 0) 772 EqCacheSCEV.unionSets(LHS, RHS); 773 return X; 774 } 775 776 case scCouldNotCompute: 777 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 778 } 779 llvm_unreachable("Unknown SCEV kind!"); 780 } 781 782 /// Given a list of SCEV objects, order them by their complexity, and group 783 /// objects of the same complexity together by value. When this routine is 784 /// finished, we know that any duplicates in the vector are consecutive and that 785 /// complexity is monotonically increasing. 786 /// 787 /// Note that we go take special precautions to ensure that we get deterministic 788 /// results from this routine. In other words, we don't want the results of 789 /// this to depend on where the addresses of various SCEV objects happened to 790 /// land in memory. 791 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 792 LoopInfo *LI, DominatorTree &DT) { 793 if (Ops.size() < 2) return; // Noop 794 795 EquivalenceClasses<const SCEV *> EqCacheSCEV; 796 EquivalenceClasses<const Value *> EqCacheValue; 797 if (Ops.size() == 2) { 798 // This is the common case, which also happens to be trivially simple. 799 // Special case it. 800 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 801 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 802 std::swap(LHS, RHS); 803 return; 804 } 805 806 // Do the rough sort by complexity. 807 std::stable_sort(Ops.begin(), Ops.end(), 808 [&](const SCEV *LHS, const SCEV *RHS) { 809 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 810 LHS, RHS, DT) < 0; 811 }); 812 813 // Now that we are sorted by complexity, group elements of the same 814 // complexity. Note that this is, at worst, N^2, but the vector is likely to 815 // be extremely short in practice. Note that we take this approach because we 816 // do not want to depend on the addresses of the objects we are grouping. 817 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 818 const SCEV *S = Ops[i]; 819 unsigned Complexity = S->getSCEVType(); 820 821 // If there are any objects of the same complexity and same value as this 822 // one, group them. 823 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 824 if (Ops[j] == S) { // Found a duplicate. 825 // Move it to immediately after i'th element. 826 std::swap(Ops[i+1], Ops[j]); 827 ++i; // no need to rescan it. 828 if (i == e-2) return; // Done! 829 } 830 } 831 } 832 } 833 834 // Returns the size of the SCEV S. 835 static inline int sizeOfSCEV(const SCEV *S) { 836 struct FindSCEVSize { 837 int Size = 0; 838 839 FindSCEVSize() = default; 840 841 bool follow(const SCEV *S) { 842 ++Size; 843 // Keep looking at all operands of S. 844 return true; 845 } 846 847 bool isDone() const { 848 return false; 849 } 850 }; 851 852 FindSCEVSize F; 853 SCEVTraversal<FindSCEVSize> ST(F); 854 ST.visitAll(S); 855 return F.Size; 856 } 857 858 namespace { 859 860 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 861 public: 862 // Computes the Quotient and Remainder of the division of Numerator by 863 // Denominator. 864 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 865 const SCEV *Denominator, const SCEV **Quotient, 866 const SCEV **Remainder) { 867 assert(Numerator && Denominator && "Uninitialized SCEV"); 868 869 SCEVDivision D(SE, Numerator, Denominator); 870 871 // Check for the trivial case here to avoid having to check for it in the 872 // rest of the code. 873 if (Numerator == Denominator) { 874 *Quotient = D.One; 875 *Remainder = D.Zero; 876 return; 877 } 878 879 if (Numerator->isZero()) { 880 *Quotient = D.Zero; 881 *Remainder = D.Zero; 882 return; 883 } 884 885 // A simple case when N/1. The quotient is N. 886 if (Denominator->isOne()) { 887 *Quotient = Numerator; 888 *Remainder = D.Zero; 889 return; 890 } 891 892 // Split the Denominator when it is a product. 893 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 894 const SCEV *Q, *R; 895 *Quotient = Numerator; 896 for (const SCEV *Op : T->operands()) { 897 divide(SE, *Quotient, Op, &Q, &R); 898 *Quotient = Q; 899 900 // Bail out when the Numerator is not divisible by one of the terms of 901 // the Denominator. 902 if (!R->isZero()) { 903 *Quotient = D.Zero; 904 *Remainder = Numerator; 905 return; 906 } 907 } 908 *Remainder = D.Zero; 909 return; 910 } 911 912 D.visit(Numerator); 913 *Quotient = D.Quotient; 914 *Remainder = D.Remainder; 915 } 916 917 // Except in the trivial case described above, we do not know how to divide 918 // Expr by Denominator for the following functions with empty implementation. 919 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 920 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 921 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 922 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 923 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 924 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 925 void visitUnknown(const SCEVUnknown *Numerator) {} 926 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 927 928 void visitConstant(const SCEVConstant *Numerator) { 929 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 930 APInt NumeratorVal = Numerator->getAPInt(); 931 APInt DenominatorVal = D->getAPInt(); 932 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 933 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 934 935 if (NumeratorBW > DenominatorBW) 936 DenominatorVal = DenominatorVal.sext(NumeratorBW); 937 else if (NumeratorBW < DenominatorBW) 938 NumeratorVal = NumeratorVal.sext(DenominatorBW); 939 940 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 941 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 942 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 943 Quotient = SE.getConstant(QuotientVal); 944 Remainder = SE.getConstant(RemainderVal); 945 return; 946 } 947 } 948 949 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 950 const SCEV *StartQ, *StartR, *StepQ, *StepR; 951 if (!Numerator->isAffine()) 952 return cannotDivide(Numerator); 953 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 954 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 955 // Bail out if the types do not match. 956 Type *Ty = Denominator->getType(); 957 if (Ty != StartQ->getType() || Ty != StartR->getType() || 958 Ty != StepQ->getType() || Ty != StepR->getType()) 959 return cannotDivide(Numerator); 960 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 961 Numerator->getNoWrapFlags()); 962 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 963 Numerator->getNoWrapFlags()); 964 } 965 966 void visitAddExpr(const SCEVAddExpr *Numerator) { 967 SmallVector<const SCEV *, 2> Qs, Rs; 968 Type *Ty = Denominator->getType(); 969 970 for (const SCEV *Op : Numerator->operands()) { 971 const SCEV *Q, *R; 972 divide(SE, Op, Denominator, &Q, &R); 973 974 // Bail out if types do not match. 975 if (Ty != Q->getType() || Ty != R->getType()) 976 return cannotDivide(Numerator); 977 978 Qs.push_back(Q); 979 Rs.push_back(R); 980 } 981 982 if (Qs.size() == 1) { 983 Quotient = Qs[0]; 984 Remainder = Rs[0]; 985 return; 986 } 987 988 Quotient = SE.getAddExpr(Qs); 989 Remainder = SE.getAddExpr(Rs); 990 } 991 992 void visitMulExpr(const SCEVMulExpr *Numerator) { 993 SmallVector<const SCEV *, 2> Qs; 994 Type *Ty = Denominator->getType(); 995 996 bool FoundDenominatorTerm = false; 997 for (const SCEV *Op : Numerator->operands()) { 998 // Bail out if types do not match. 999 if (Ty != Op->getType()) 1000 return cannotDivide(Numerator); 1001 1002 if (FoundDenominatorTerm) { 1003 Qs.push_back(Op); 1004 continue; 1005 } 1006 1007 // Check whether Denominator divides one of the product operands. 1008 const SCEV *Q, *R; 1009 divide(SE, Op, Denominator, &Q, &R); 1010 if (!R->isZero()) { 1011 Qs.push_back(Op); 1012 continue; 1013 } 1014 1015 // Bail out if types do not match. 1016 if (Ty != Q->getType()) 1017 return cannotDivide(Numerator); 1018 1019 FoundDenominatorTerm = true; 1020 Qs.push_back(Q); 1021 } 1022 1023 if (FoundDenominatorTerm) { 1024 Remainder = Zero; 1025 if (Qs.size() == 1) 1026 Quotient = Qs[0]; 1027 else 1028 Quotient = SE.getMulExpr(Qs); 1029 return; 1030 } 1031 1032 if (!isa<SCEVUnknown>(Denominator)) 1033 return cannotDivide(Numerator); 1034 1035 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1036 ValueToValueMap RewriteMap; 1037 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1038 cast<SCEVConstant>(Zero)->getValue(); 1039 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1040 1041 if (Remainder->isZero()) { 1042 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1043 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1044 cast<SCEVConstant>(One)->getValue(); 1045 Quotient = 1046 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1047 return; 1048 } 1049 1050 // Quotient is (Numerator - Remainder) divided by Denominator. 1051 const SCEV *Q, *R; 1052 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1053 // This SCEV does not seem to simplify: fail the division here. 1054 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1055 return cannotDivide(Numerator); 1056 divide(SE, Diff, Denominator, &Q, &R); 1057 if (R != Zero) 1058 return cannotDivide(Numerator); 1059 Quotient = Q; 1060 } 1061 1062 private: 1063 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1064 const SCEV *Denominator) 1065 : SE(S), Denominator(Denominator) { 1066 Zero = SE.getZero(Denominator->getType()); 1067 One = SE.getOne(Denominator->getType()); 1068 1069 // We generally do not know how to divide Expr by Denominator. We 1070 // initialize the division to a "cannot divide" state to simplify the rest 1071 // of the code. 1072 cannotDivide(Numerator); 1073 } 1074 1075 // Convenience function for giving up on the division. We set the quotient to 1076 // be equal to zero and the remainder to be equal to the numerator. 1077 void cannotDivide(const SCEV *Numerator) { 1078 Quotient = Zero; 1079 Remainder = Numerator; 1080 } 1081 1082 ScalarEvolution &SE; 1083 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1084 }; 1085 1086 } // end anonymous namespace 1087 1088 //===----------------------------------------------------------------------===// 1089 // Simple SCEV method implementations 1090 //===----------------------------------------------------------------------===// 1091 1092 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1093 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1094 ScalarEvolution &SE, 1095 Type *ResultTy) { 1096 // Handle the simplest case efficiently. 1097 if (K == 1) 1098 return SE.getTruncateOrZeroExtend(It, ResultTy); 1099 1100 // We are using the following formula for BC(It, K): 1101 // 1102 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1103 // 1104 // Suppose, W is the bitwidth of the return value. We must be prepared for 1105 // overflow. Hence, we must assure that the result of our computation is 1106 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1107 // safe in modular arithmetic. 1108 // 1109 // However, this code doesn't use exactly that formula; the formula it uses 1110 // is something like the following, where T is the number of factors of 2 in 1111 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1112 // exponentiation: 1113 // 1114 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1115 // 1116 // This formula is trivially equivalent to the previous formula. However, 1117 // this formula can be implemented much more efficiently. The trick is that 1118 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1119 // arithmetic. To do exact division in modular arithmetic, all we have 1120 // to do is multiply by the inverse. Therefore, this step can be done at 1121 // width W. 1122 // 1123 // The next issue is how to safely do the division by 2^T. The way this 1124 // is done is by doing the multiplication step at a width of at least W + T 1125 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1126 // when we perform the division by 2^T (which is equivalent to a right shift 1127 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1128 // truncated out after the division by 2^T. 1129 // 1130 // In comparison to just directly using the first formula, this technique 1131 // is much more efficient; using the first formula requires W * K bits, 1132 // but this formula less than W + K bits. Also, the first formula requires 1133 // a division step, whereas this formula only requires multiplies and shifts. 1134 // 1135 // It doesn't matter whether the subtraction step is done in the calculation 1136 // width or the input iteration count's width; if the subtraction overflows, 1137 // the result must be zero anyway. We prefer here to do it in the width of 1138 // the induction variable because it helps a lot for certain cases; CodeGen 1139 // isn't smart enough to ignore the overflow, which leads to much less 1140 // efficient code if the width of the subtraction is wider than the native 1141 // register width. 1142 // 1143 // (It's possible to not widen at all by pulling out factors of 2 before 1144 // the multiplication; for example, K=2 can be calculated as 1145 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1146 // extra arithmetic, so it's not an obvious win, and it gets 1147 // much more complicated for K > 3.) 1148 1149 // Protection from insane SCEVs; this bound is conservative, 1150 // but it probably doesn't matter. 1151 if (K > 1000) 1152 return SE.getCouldNotCompute(); 1153 1154 unsigned W = SE.getTypeSizeInBits(ResultTy); 1155 1156 // Calculate K! / 2^T and T; we divide out the factors of two before 1157 // multiplying for calculating K! / 2^T to avoid overflow. 1158 // Other overflow doesn't matter because we only care about the bottom 1159 // W bits of the result. 1160 APInt OddFactorial(W, 1); 1161 unsigned T = 1; 1162 for (unsigned i = 3; i <= K; ++i) { 1163 APInt Mult(W, i); 1164 unsigned TwoFactors = Mult.countTrailingZeros(); 1165 T += TwoFactors; 1166 Mult.lshrInPlace(TwoFactors); 1167 OddFactorial *= Mult; 1168 } 1169 1170 // We need at least W + T bits for the multiplication step 1171 unsigned CalculationBits = W + T; 1172 1173 // Calculate 2^T, at width T+W. 1174 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1175 1176 // Calculate the multiplicative inverse of K! / 2^T; 1177 // this multiplication factor will perform the exact division by 1178 // K! / 2^T. 1179 APInt Mod = APInt::getSignedMinValue(W+1); 1180 APInt MultiplyFactor = OddFactorial.zext(W+1); 1181 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1182 MultiplyFactor = MultiplyFactor.trunc(W); 1183 1184 // Calculate the product, at width T+W 1185 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1186 CalculationBits); 1187 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1188 for (unsigned i = 1; i != K; ++i) { 1189 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1190 Dividend = SE.getMulExpr(Dividend, 1191 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1192 } 1193 1194 // Divide by 2^T 1195 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1196 1197 // Truncate the result, and divide by K! / 2^T. 1198 1199 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1200 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1201 } 1202 1203 /// Return the value of this chain of recurrences at the specified iteration 1204 /// number. We can evaluate this recurrence by multiplying each element in the 1205 /// chain by the binomial coefficient corresponding to it. In other words, we 1206 /// can evaluate {A,+,B,+,C,+,D} as: 1207 /// 1208 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1209 /// 1210 /// where BC(It, k) stands for binomial coefficient. 1211 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1212 ScalarEvolution &SE) const { 1213 const SCEV *Result = getStart(); 1214 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1215 // The computation is correct in the face of overflow provided that the 1216 // multiplication is performed _after_ the evaluation of the binomial 1217 // coefficient. 1218 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1219 if (isa<SCEVCouldNotCompute>(Coeff)) 1220 return Coeff; 1221 1222 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1223 } 1224 return Result; 1225 } 1226 1227 //===----------------------------------------------------------------------===// 1228 // SCEV Expression folder implementations 1229 //===----------------------------------------------------------------------===// 1230 1231 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1232 Type *Ty) { 1233 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1234 "This is not a truncating conversion!"); 1235 assert(isSCEVable(Ty) && 1236 "This is not a conversion to a SCEVable type!"); 1237 Ty = getEffectiveSCEVType(Ty); 1238 1239 FoldingSetNodeID ID; 1240 ID.AddInteger(scTruncate); 1241 ID.AddPointer(Op); 1242 ID.AddPointer(Ty); 1243 void *IP = nullptr; 1244 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1245 1246 // Fold if the operand is constant. 1247 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1248 return getConstant( 1249 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1250 1251 // trunc(trunc(x)) --> trunc(x) 1252 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1253 return getTruncateExpr(ST->getOperand(), Ty); 1254 1255 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1256 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1257 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1258 1259 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1260 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1261 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1262 1263 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1264 // eliminate all the truncates, or we replace other casts with truncates. 1265 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1266 SmallVector<const SCEV *, 4> Operands; 1267 bool hasTrunc = false; 1268 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1269 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1270 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1271 hasTrunc = isa<SCEVTruncateExpr>(S); 1272 Operands.push_back(S); 1273 } 1274 if (!hasTrunc) 1275 return getAddExpr(Operands); 1276 // In spite we checked in the beginning that ID is not in the cache, 1277 // it is possible that during recursion and different modification 1278 // ID came to cache, so if we found it, just return it. 1279 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1280 return S; 1281 } 1282 1283 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1284 // eliminate all the truncates, or we replace other casts with truncates. 1285 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1286 SmallVector<const SCEV *, 4> Operands; 1287 bool hasTrunc = false; 1288 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1289 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1290 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1291 hasTrunc = isa<SCEVTruncateExpr>(S); 1292 Operands.push_back(S); 1293 } 1294 if (!hasTrunc) 1295 return getMulExpr(Operands); 1296 // In spite we checked in the beginning that ID is not in the cache, 1297 // it is possible that during recursion and different modification 1298 // ID came to cache, so if we found it, just return it. 1299 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1300 return S; 1301 } 1302 1303 // If the input value is a chrec scev, truncate the chrec's operands. 1304 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1305 SmallVector<const SCEV *, 4> Operands; 1306 for (const SCEV *Op : AddRec->operands()) 1307 Operands.push_back(getTruncateExpr(Op, Ty)); 1308 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1309 } 1310 1311 // The cast wasn't folded; create an explicit cast node. We can reuse 1312 // the existing insert position since if we get here, we won't have 1313 // made any changes which would invalidate it. 1314 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1315 Op, Ty); 1316 UniqueSCEVs.InsertNode(S, IP); 1317 addToLoopUseLists(S); 1318 return S; 1319 } 1320 1321 // Get the limit of a recurrence such that incrementing by Step cannot cause 1322 // signed overflow as long as the value of the recurrence within the 1323 // loop does not exceed this limit before incrementing. 1324 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1325 ICmpInst::Predicate *Pred, 1326 ScalarEvolution *SE) { 1327 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1328 if (SE->isKnownPositive(Step)) { 1329 *Pred = ICmpInst::ICMP_SLT; 1330 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1331 SE->getSignedRangeMax(Step)); 1332 } 1333 if (SE->isKnownNegative(Step)) { 1334 *Pred = ICmpInst::ICMP_SGT; 1335 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1336 SE->getSignedRangeMin(Step)); 1337 } 1338 return nullptr; 1339 } 1340 1341 // Get the limit of a recurrence such that incrementing by Step cannot cause 1342 // unsigned overflow as long as the value of the recurrence within the loop does 1343 // not exceed this limit before incrementing. 1344 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1345 ICmpInst::Predicate *Pred, 1346 ScalarEvolution *SE) { 1347 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1348 *Pred = ICmpInst::ICMP_ULT; 1349 1350 return SE->getConstant(APInt::getMinValue(BitWidth) - 1351 SE->getUnsignedRangeMax(Step)); 1352 } 1353 1354 namespace { 1355 1356 struct ExtendOpTraitsBase { 1357 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1358 unsigned); 1359 }; 1360 1361 // Used to make code generic over signed and unsigned overflow. 1362 template <typename ExtendOp> struct ExtendOpTraits { 1363 // Members present: 1364 // 1365 // static const SCEV::NoWrapFlags WrapType; 1366 // 1367 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1368 // 1369 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1370 // ICmpInst::Predicate *Pred, 1371 // ScalarEvolution *SE); 1372 }; 1373 1374 template <> 1375 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1376 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1377 1378 static const GetExtendExprTy GetExtendExpr; 1379 1380 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1381 ICmpInst::Predicate *Pred, 1382 ScalarEvolution *SE) { 1383 return getSignedOverflowLimitForStep(Step, Pred, SE); 1384 } 1385 }; 1386 1387 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1388 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1389 1390 template <> 1391 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1392 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1393 1394 static const GetExtendExprTy GetExtendExpr; 1395 1396 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1397 ICmpInst::Predicate *Pred, 1398 ScalarEvolution *SE) { 1399 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1400 } 1401 }; 1402 1403 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1404 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1405 1406 } // end anonymous namespace 1407 1408 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1409 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1410 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1411 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1412 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1413 // expression "Step + sext/zext(PreIncAR)" is congruent with 1414 // "sext/zext(PostIncAR)" 1415 template <typename ExtendOpTy> 1416 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1417 ScalarEvolution *SE, unsigned Depth) { 1418 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1419 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1420 1421 const Loop *L = AR->getLoop(); 1422 const SCEV *Start = AR->getStart(); 1423 const SCEV *Step = AR->getStepRecurrence(*SE); 1424 1425 // Check for a simple looking step prior to loop entry. 1426 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1427 if (!SA) 1428 return nullptr; 1429 1430 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1431 // subtraction is expensive. For this purpose, perform a quick and dirty 1432 // difference, by checking for Step in the operand list. 1433 SmallVector<const SCEV *, 4> DiffOps; 1434 for (const SCEV *Op : SA->operands()) 1435 if (Op != Step) 1436 DiffOps.push_back(Op); 1437 1438 if (DiffOps.size() == SA->getNumOperands()) 1439 return nullptr; 1440 1441 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1442 // `Step`: 1443 1444 // 1. NSW/NUW flags on the step increment. 1445 auto PreStartFlags = 1446 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1447 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1448 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1449 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1450 1451 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1452 // "S+X does not sign/unsign-overflow". 1453 // 1454 1455 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1456 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1457 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1458 return PreStart; 1459 1460 // 2. Direct overflow check on the step operation's expression. 1461 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1462 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1463 const SCEV *OperandExtendedStart = 1464 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1465 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1466 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1467 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1468 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1469 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1470 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1471 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1472 } 1473 return PreStart; 1474 } 1475 1476 // 3. Loop precondition. 1477 ICmpInst::Predicate Pred; 1478 const SCEV *OverflowLimit = 1479 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1480 1481 if (OverflowLimit && 1482 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1483 return PreStart; 1484 1485 return nullptr; 1486 } 1487 1488 // Get the normalized zero or sign extended expression for this AddRec's Start. 1489 template <typename ExtendOpTy> 1490 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1491 ScalarEvolution *SE, 1492 unsigned Depth) { 1493 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1494 1495 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1496 if (!PreStart) 1497 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1498 1499 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1500 Depth), 1501 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1502 } 1503 1504 // Try to prove away overflow by looking at "nearby" add recurrences. A 1505 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1506 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1507 // 1508 // Formally: 1509 // 1510 // {S,+,X} == {S-T,+,X} + T 1511 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1512 // 1513 // If ({S-T,+,X} + T) does not overflow ... (1) 1514 // 1515 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1516 // 1517 // If {S-T,+,X} does not overflow ... (2) 1518 // 1519 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1520 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1521 // 1522 // If (S-T)+T does not overflow ... (3) 1523 // 1524 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1525 // == {Ext(S),+,Ext(X)} == LHS 1526 // 1527 // Thus, if (1), (2) and (3) are true for some T, then 1528 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1529 // 1530 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1531 // does not overflow" restricted to the 0th iteration. Therefore we only need 1532 // to check for (1) and (2). 1533 // 1534 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1535 // is `Delta` (defined below). 1536 template <typename ExtendOpTy> 1537 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1538 const SCEV *Step, 1539 const Loop *L) { 1540 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1541 1542 // We restrict `Start` to a constant to prevent SCEV from spending too much 1543 // time here. It is correct (but more expensive) to continue with a 1544 // non-constant `Start` and do a general SCEV subtraction to compute 1545 // `PreStart` below. 1546 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1547 if (!StartC) 1548 return false; 1549 1550 APInt StartAI = StartC->getAPInt(); 1551 1552 for (unsigned Delta : {-2, -1, 1, 2}) { 1553 const SCEV *PreStart = getConstant(StartAI - Delta); 1554 1555 FoldingSetNodeID ID; 1556 ID.AddInteger(scAddRecExpr); 1557 ID.AddPointer(PreStart); 1558 ID.AddPointer(Step); 1559 ID.AddPointer(L); 1560 void *IP = nullptr; 1561 const auto *PreAR = 1562 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1563 1564 // Give up if we don't already have the add recurrence we need because 1565 // actually constructing an add recurrence is relatively expensive. 1566 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1567 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1568 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1569 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1570 DeltaS, &Pred, this); 1571 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1572 return true; 1573 } 1574 } 1575 1576 return false; 1577 } 1578 1579 const SCEV * 1580 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1581 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1582 "This is not an extending conversion!"); 1583 assert(isSCEVable(Ty) && 1584 "This is not a conversion to a SCEVable type!"); 1585 Ty = getEffectiveSCEVType(Ty); 1586 1587 // Fold if the operand is constant. 1588 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1589 return getConstant( 1590 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1591 1592 // zext(zext(x)) --> zext(x) 1593 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1594 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1595 1596 // Before doing any expensive analysis, check to see if we've already 1597 // computed a SCEV for this Op and Ty. 1598 FoldingSetNodeID ID; 1599 ID.AddInteger(scZeroExtend); 1600 ID.AddPointer(Op); 1601 ID.AddPointer(Ty); 1602 void *IP = nullptr; 1603 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1604 if (Depth > MaxExtDepth) { 1605 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1606 Op, Ty); 1607 UniqueSCEVs.InsertNode(S, IP); 1608 addToLoopUseLists(S); 1609 return S; 1610 } 1611 1612 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1613 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1614 // It's possible the bits taken off by the truncate were all zero bits. If 1615 // so, we should be able to simplify this further. 1616 const SCEV *X = ST->getOperand(); 1617 ConstantRange CR = getUnsignedRange(X); 1618 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1619 unsigned NewBits = getTypeSizeInBits(Ty); 1620 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1621 CR.zextOrTrunc(NewBits))) 1622 return getTruncateOrZeroExtend(X, Ty); 1623 } 1624 1625 // If the input value is a chrec scev, and we can prove that the value 1626 // did not overflow the old, smaller, value, we can zero extend all of the 1627 // operands (often constants). This allows analysis of something like 1628 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1629 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1630 if (AR->isAffine()) { 1631 const SCEV *Start = AR->getStart(); 1632 const SCEV *Step = AR->getStepRecurrence(*this); 1633 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1634 const Loop *L = AR->getLoop(); 1635 1636 if (!AR->hasNoUnsignedWrap()) { 1637 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1638 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1639 } 1640 1641 // If we have special knowledge that this addrec won't overflow, 1642 // we don't need to do any further analysis. 1643 if (AR->hasNoUnsignedWrap()) 1644 return getAddRecExpr( 1645 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1646 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1647 1648 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1649 // Note that this serves two purposes: It filters out loops that are 1650 // simply not analyzable, and it covers the case where this code is 1651 // being called from within backedge-taken count analysis, such that 1652 // attempting to ask for the backedge-taken count would likely result 1653 // in infinite recursion. In the later case, the analysis code will 1654 // cope with a conservative value, and it will take care to purge 1655 // that value once it has finished. 1656 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1657 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1658 // Manually compute the final value for AR, checking for 1659 // overflow. 1660 1661 // Check whether the backedge-taken count can be losslessly casted to 1662 // the addrec's type. The count is always unsigned. 1663 const SCEV *CastedMaxBECount = 1664 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1665 const SCEV *RecastedMaxBECount = 1666 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1667 if (MaxBECount == RecastedMaxBECount) { 1668 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1669 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1670 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1671 SCEV::FlagAnyWrap, Depth + 1); 1672 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1673 SCEV::FlagAnyWrap, 1674 Depth + 1), 1675 WideTy, Depth + 1); 1676 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1677 const SCEV *WideMaxBECount = 1678 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1679 const SCEV *OperandExtendedAdd = 1680 getAddExpr(WideStart, 1681 getMulExpr(WideMaxBECount, 1682 getZeroExtendExpr(Step, WideTy, Depth + 1), 1683 SCEV::FlagAnyWrap, Depth + 1), 1684 SCEV::FlagAnyWrap, Depth + 1); 1685 if (ZAdd == OperandExtendedAdd) { 1686 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1687 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1688 // Return the expression with the addrec on the outside. 1689 return getAddRecExpr( 1690 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1691 Depth + 1), 1692 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1693 AR->getNoWrapFlags()); 1694 } 1695 // Similar to above, only this time treat the step value as signed. 1696 // This covers loops that count down. 1697 OperandExtendedAdd = 1698 getAddExpr(WideStart, 1699 getMulExpr(WideMaxBECount, 1700 getSignExtendExpr(Step, WideTy, Depth + 1), 1701 SCEV::FlagAnyWrap, Depth + 1), 1702 SCEV::FlagAnyWrap, Depth + 1); 1703 if (ZAdd == OperandExtendedAdd) { 1704 // Cache knowledge of AR NW, which is propagated to this AddRec. 1705 // Negative step causes unsigned wrap, but it still can't self-wrap. 1706 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1707 // Return the expression with the addrec on the outside. 1708 return getAddRecExpr( 1709 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1710 Depth + 1), 1711 getSignExtendExpr(Step, Ty, Depth + 1), L, 1712 AR->getNoWrapFlags()); 1713 } 1714 } 1715 } 1716 1717 // Normally, in the cases we can prove no-overflow via a 1718 // backedge guarding condition, we can also compute a backedge 1719 // taken count for the loop. The exceptions are assumptions and 1720 // guards present in the loop -- SCEV is not great at exploiting 1721 // these to compute max backedge taken counts, but can still use 1722 // these to prove lack of overflow. Use this fact to avoid 1723 // doing extra work that may not pay off. 1724 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1725 !AC.assumptions().empty()) { 1726 // If the backedge is guarded by a comparison with the pre-inc 1727 // value the addrec is safe. Also, if the entry is guarded by 1728 // a comparison with the start value and the backedge is 1729 // guarded by a comparison with the post-inc value, the addrec 1730 // is safe. 1731 if (isKnownPositive(Step)) { 1732 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1733 getUnsignedRangeMax(Step)); 1734 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1735 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1736 // Cache knowledge of AR NUW, which is propagated to this 1737 // AddRec. 1738 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1739 // Return the expression with the addrec on the outside. 1740 return getAddRecExpr( 1741 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1742 Depth + 1), 1743 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1744 AR->getNoWrapFlags()); 1745 } 1746 } else if (isKnownNegative(Step)) { 1747 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1748 getSignedRangeMin(Step)); 1749 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1750 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1751 // Cache knowledge of AR NW, which is propagated to this 1752 // AddRec. Negative step causes unsigned wrap, but it 1753 // still can't self-wrap. 1754 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1755 // Return the expression with the addrec on the outside. 1756 return getAddRecExpr( 1757 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1758 Depth + 1), 1759 getSignExtendExpr(Step, Ty, Depth + 1), L, 1760 AR->getNoWrapFlags()); 1761 } 1762 } 1763 } 1764 1765 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1766 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1767 return getAddRecExpr( 1768 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1769 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1770 } 1771 } 1772 1773 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1774 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1775 if (SA->hasNoUnsignedWrap()) { 1776 // If the addition does not unsign overflow then we can, by definition, 1777 // commute the zero extension with the addition operation. 1778 SmallVector<const SCEV *, 4> Ops; 1779 for (const auto *Op : SA->operands()) 1780 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1781 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1782 } 1783 } 1784 1785 // The cast wasn't folded; create an explicit cast node. 1786 // Recompute the insert position, as it may have been invalidated. 1787 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1788 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1789 Op, Ty); 1790 UniqueSCEVs.InsertNode(S, IP); 1791 addToLoopUseLists(S); 1792 return S; 1793 } 1794 1795 const SCEV * 1796 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1797 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1798 "This is not an extending conversion!"); 1799 assert(isSCEVable(Ty) && 1800 "This is not a conversion to a SCEVable type!"); 1801 Ty = getEffectiveSCEVType(Ty); 1802 1803 // Fold if the operand is constant. 1804 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1805 return getConstant( 1806 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1807 1808 // sext(sext(x)) --> sext(x) 1809 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1810 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1811 1812 // sext(zext(x)) --> zext(x) 1813 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1814 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1815 1816 // Before doing any expensive analysis, check to see if we've already 1817 // computed a SCEV for this Op and Ty. 1818 FoldingSetNodeID ID; 1819 ID.AddInteger(scSignExtend); 1820 ID.AddPointer(Op); 1821 ID.AddPointer(Ty); 1822 void *IP = nullptr; 1823 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1824 // Limit recursion depth. 1825 if (Depth > MaxExtDepth) { 1826 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1827 Op, Ty); 1828 UniqueSCEVs.InsertNode(S, IP); 1829 addToLoopUseLists(S); 1830 return S; 1831 } 1832 1833 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1834 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1835 // It's possible the bits taken off by the truncate were all sign bits. If 1836 // so, we should be able to simplify this further. 1837 const SCEV *X = ST->getOperand(); 1838 ConstantRange CR = getSignedRange(X); 1839 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1840 unsigned NewBits = getTypeSizeInBits(Ty); 1841 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1842 CR.sextOrTrunc(NewBits))) 1843 return getTruncateOrSignExtend(X, Ty); 1844 } 1845 1846 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1847 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1848 if (SA->getNumOperands() == 2) { 1849 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1850 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1851 if (SMul && SC1) { 1852 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1853 const APInt &C1 = SC1->getAPInt(); 1854 const APInt &C2 = SC2->getAPInt(); 1855 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1856 C2.ugt(C1) && C2.isPowerOf2()) 1857 return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1), 1858 getSignExtendExpr(SMul, Ty, Depth + 1), 1859 SCEV::FlagAnyWrap, Depth + 1); 1860 } 1861 } 1862 } 1863 1864 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1865 if (SA->hasNoSignedWrap()) { 1866 // If the addition does not sign overflow then we can, by definition, 1867 // commute the sign extension with the addition operation. 1868 SmallVector<const SCEV *, 4> Ops; 1869 for (const auto *Op : SA->operands()) 1870 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1871 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1872 } 1873 } 1874 // If the input value is a chrec scev, and we can prove that the value 1875 // did not overflow the old, smaller, value, we can sign extend all of the 1876 // operands (often constants). This allows analysis of something like 1877 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1878 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1879 if (AR->isAffine()) { 1880 const SCEV *Start = AR->getStart(); 1881 const SCEV *Step = AR->getStepRecurrence(*this); 1882 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1883 const Loop *L = AR->getLoop(); 1884 1885 if (!AR->hasNoSignedWrap()) { 1886 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1887 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1888 } 1889 1890 // If we have special knowledge that this addrec won't overflow, 1891 // we don't need to do any further analysis. 1892 if (AR->hasNoSignedWrap()) 1893 return getAddRecExpr( 1894 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1895 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1896 1897 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1898 // Note that this serves two purposes: It filters out loops that are 1899 // simply not analyzable, and it covers the case where this code is 1900 // being called from within backedge-taken count analysis, such that 1901 // attempting to ask for the backedge-taken count would likely result 1902 // in infinite recursion. In the later case, the analysis code will 1903 // cope with a conservative value, and it will take care to purge 1904 // that value once it has finished. 1905 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1906 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1907 // Manually compute the final value for AR, checking for 1908 // overflow. 1909 1910 // Check whether the backedge-taken count can be losslessly casted to 1911 // the addrec's type. The count is always unsigned. 1912 const SCEV *CastedMaxBECount = 1913 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1914 const SCEV *RecastedMaxBECount = 1915 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1916 if (MaxBECount == RecastedMaxBECount) { 1917 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1918 // Check whether Start+Step*MaxBECount has no signed overflow. 1919 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1920 SCEV::FlagAnyWrap, Depth + 1); 1921 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1922 SCEV::FlagAnyWrap, 1923 Depth + 1), 1924 WideTy, Depth + 1); 1925 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1926 const SCEV *WideMaxBECount = 1927 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1928 const SCEV *OperandExtendedAdd = 1929 getAddExpr(WideStart, 1930 getMulExpr(WideMaxBECount, 1931 getSignExtendExpr(Step, WideTy, Depth + 1), 1932 SCEV::FlagAnyWrap, Depth + 1), 1933 SCEV::FlagAnyWrap, Depth + 1); 1934 if (SAdd == OperandExtendedAdd) { 1935 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1936 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1937 // Return the expression with the addrec on the outside. 1938 return getAddRecExpr( 1939 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1940 Depth + 1), 1941 getSignExtendExpr(Step, Ty, Depth + 1), L, 1942 AR->getNoWrapFlags()); 1943 } 1944 // Similar to above, only this time treat the step value as unsigned. 1945 // This covers loops that count up with an unsigned step. 1946 OperandExtendedAdd = 1947 getAddExpr(WideStart, 1948 getMulExpr(WideMaxBECount, 1949 getZeroExtendExpr(Step, WideTy, Depth + 1), 1950 SCEV::FlagAnyWrap, Depth + 1), 1951 SCEV::FlagAnyWrap, Depth + 1); 1952 if (SAdd == OperandExtendedAdd) { 1953 // If AR wraps around then 1954 // 1955 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1956 // => SAdd != OperandExtendedAdd 1957 // 1958 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1959 // (SAdd == OperandExtendedAdd => AR is NW) 1960 1961 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1962 1963 // Return the expression with the addrec on the outside. 1964 return getAddRecExpr( 1965 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1966 Depth + 1), 1967 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1968 AR->getNoWrapFlags()); 1969 } 1970 } 1971 } 1972 1973 // Normally, in the cases we can prove no-overflow via a 1974 // backedge guarding condition, we can also compute a backedge 1975 // taken count for the loop. The exceptions are assumptions and 1976 // guards present in the loop -- SCEV is not great at exploiting 1977 // these to compute max backedge taken counts, but can still use 1978 // these to prove lack of overflow. Use this fact to avoid 1979 // doing extra work that may not pay off. 1980 1981 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1982 !AC.assumptions().empty()) { 1983 // If the backedge is guarded by a comparison with the pre-inc 1984 // value the addrec is safe. Also, if the entry is guarded by 1985 // a comparison with the start value and the backedge is 1986 // guarded by a comparison with the post-inc value, the addrec 1987 // is safe. 1988 ICmpInst::Predicate Pred; 1989 const SCEV *OverflowLimit = 1990 getSignedOverflowLimitForStep(Step, &Pred, this); 1991 if (OverflowLimit && 1992 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1993 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1994 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1995 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1996 return getAddRecExpr( 1997 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1998 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1999 } 2000 } 2001 2002 // If Start and Step are constants, check if we can apply this 2003 // transformation: 2004 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 2005 auto *SC1 = dyn_cast<SCEVConstant>(Start); 2006 auto *SC2 = dyn_cast<SCEVConstant>(Step); 2007 if (SC1 && SC2) { 2008 const APInt &C1 = SC1->getAPInt(); 2009 const APInt &C2 = SC2->getAPInt(); 2010 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 2011 C2.isPowerOf2()) { 2012 Start = getSignExtendExpr(Start, Ty, Depth + 1); 2013 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 2014 AR->getNoWrapFlags()); 2015 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1), 2016 SCEV::FlagAnyWrap, Depth + 1); 2017 } 2018 } 2019 2020 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2021 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2022 return getAddRecExpr( 2023 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2024 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2025 } 2026 } 2027 2028 // If the input value is provably positive and we could not simplify 2029 // away the sext build a zext instead. 2030 if (isKnownNonNegative(Op)) 2031 return getZeroExtendExpr(Op, Ty, Depth + 1); 2032 2033 // The cast wasn't folded; create an explicit cast node. 2034 // Recompute the insert position, as it may have been invalidated. 2035 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2036 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2037 Op, Ty); 2038 UniqueSCEVs.InsertNode(S, IP); 2039 addToLoopUseLists(S); 2040 return S; 2041 } 2042 2043 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2044 /// unspecified bits out to the given type. 2045 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2046 Type *Ty) { 2047 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2048 "This is not an extending conversion!"); 2049 assert(isSCEVable(Ty) && 2050 "This is not a conversion to a SCEVable type!"); 2051 Ty = getEffectiveSCEVType(Ty); 2052 2053 // Sign-extend negative constants. 2054 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2055 if (SC->getAPInt().isNegative()) 2056 return getSignExtendExpr(Op, Ty); 2057 2058 // Peel off a truncate cast. 2059 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2060 const SCEV *NewOp = T->getOperand(); 2061 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2062 return getAnyExtendExpr(NewOp, Ty); 2063 return getTruncateOrNoop(NewOp, Ty); 2064 } 2065 2066 // Next try a zext cast. If the cast is folded, use it. 2067 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2068 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2069 return ZExt; 2070 2071 // Next try a sext cast. If the cast is folded, use it. 2072 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2073 if (!isa<SCEVSignExtendExpr>(SExt)) 2074 return SExt; 2075 2076 // Force the cast to be folded into the operands of an addrec. 2077 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2078 SmallVector<const SCEV *, 4> Ops; 2079 for (const SCEV *Op : AR->operands()) 2080 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2081 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2082 } 2083 2084 // If the expression is obviously signed, use the sext cast value. 2085 if (isa<SCEVSMaxExpr>(Op)) 2086 return SExt; 2087 2088 // Absent any other information, use the zext cast value. 2089 return ZExt; 2090 } 2091 2092 /// Process the given Ops list, which is a list of operands to be added under 2093 /// the given scale, update the given map. This is a helper function for 2094 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2095 /// that would form an add expression like this: 2096 /// 2097 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2098 /// 2099 /// where A and B are constants, update the map with these values: 2100 /// 2101 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2102 /// 2103 /// and add 13 + A*B*29 to AccumulatedConstant. 2104 /// This will allow getAddRecExpr to produce this: 2105 /// 2106 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2107 /// 2108 /// This form often exposes folding opportunities that are hidden in 2109 /// the original operand list. 2110 /// 2111 /// Return true iff it appears that any interesting folding opportunities 2112 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2113 /// the common case where no interesting opportunities are present, and 2114 /// is also used as a check to avoid infinite recursion. 2115 static bool 2116 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2117 SmallVectorImpl<const SCEV *> &NewOps, 2118 APInt &AccumulatedConstant, 2119 const SCEV *const *Ops, size_t NumOperands, 2120 const APInt &Scale, 2121 ScalarEvolution &SE) { 2122 bool Interesting = false; 2123 2124 // Iterate over the add operands. They are sorted, with constants first. 2125 unsigned i = 0; 2126 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2127 ++i; 2128 // Pull a buried constant out to the outside. 2129 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2130 Interesting = true; 2131 AccumulatedConstant += Scale * C->getAPInt(); 2132 } 2133 2134 // Next comes everything else. We're especially interested in multiplies 2135 // here, but they're in the middle, so just visit the rest with one loop. 2136 for (; i != NumOperands; ++i) { 2137 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2138 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2139 APInt NewScale = 2140 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2141 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2142 // A multiplication of a constant with another add; recurse. 2143 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2144 Interesting |= 2145 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2146 Add->op_begin(), Add->getNumOperands(), 2147 NewScale, SE); 2148 } else { 2149 // A multiplication of a constant with some other value. Update 2150 // the map. 2151 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2152 const SCEV *Key = SE.getMulExpr(MulOps); 2153 auto Pair = M.insert({Key, NewScale}); 2154 if (Pair.second) { 2155 NewOps.push_back(Pair.first->first); 2156 } else { 2157 Pair.first->second += NewScale; 2158 // The map already had an entry for this value, which may indicate 2159 // a folding opportunity. 2160 Interesting = true; 2161 } 2162 } 2163 } else { 2164 // An ordinary operand. Update the map. 2165 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2166 M.insert({Ops[i], Scale}); 2167 if (Pair.second) { 2168 NewOps.push_back(Pair.first->first); 2169 } else { 2170 Pair.first->second += Scale; 2171 // The map already had an entry for this value, which may indicate 2172 // a folding opportunity. 2173 Interesting = true; 2174 } 2175 } 2176 } 2177 2178 return Interesting; 2179 } 2180 2181 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2182 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2183 // can't-overflow flags for the operation if possible. 2184 static SCEV::NoWrapFlags 2185 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2186 const SmallVectorImpl<const SCEV *> &Ops, 2187 SCEV::NoWrapFlags Flags) { 2188 using namespace std::placeholders; 2189 2190 using OBO = OverflowingBinaryOperator; 2191 2192 bool CanAnalyze = 2193 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2194 (void)CanAnalyze; 2195 assert(CanAnalyze && "don't call from other places!"); 2196 2197 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2198 SCEV::NoWrapFlags SignOrUnsignWrap = 2199 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2200 2201 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2202 auto IsKnownNonNegative = [&](const SCEV *S) { 2203 return SE->isKnownNonNegative(S); 2204 }; 2205 2206 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2207 Flags = 2208 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2209 2210 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2211 2212 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2213 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2214 2215 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2216 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2217 2218 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2219 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2220 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2221 Instruction::Add, C, OBO::NoSignedWrap); 2222 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2223 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2224 } 2225 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2226 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2227 Instruction::Add, C, OBO::NoUnsignedWrap); 2228 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2229 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2230 } 2231 } 2232 2233 return Flags; 2234 } 2235 2236 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2237 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2238 } 2239 2240 /// Get a canonical add expression, or something simpler if possible. 2241 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2242 SCEV::NoWrapFlags Flags, 2243 unsigned Depth) { 2244 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2245 "only nuw or nsw allowed"); 2246 assert(!Ops.empty() && "Cannot get empty add!"); 2247 if (Ops.size() == 1) return Ops[0]; 2248 #ifndef NDEBUG 2249 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2250 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2251 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2252 "SCEVAddExpr operand types don't match!"); 2253 #endif 2254 2255 // Sort by complexity, this groups all similar expression types together. 2256 GroupByComplexity(Ops, &LI, DT); 2257 2258 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2259 2260 // If there are any constants, fold them together. 2261 unsigned Idx = 0; 2262 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2263 ++Idx; 2264 assert(Idx < Ops.size()); 2265 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2266 // We found two constants, fold them together! 2267 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2268 if (Ops.size() == 2) return Ops[0]; 2269 Ops.erase(Ops.begin()+1); // Erase the folded element 2270 LHSC = cast<SCEVConstant>(Ops[0]); 2271 } 2272 2273 // If we are left with a constant zero being added, strip it off. 2274 if (LHSC->getValue()->isZero()) { 2275 Ops.erase(Ops.begin()); 2276 --Idx; 2277 } 2278 2279 if (Ops.size() == 1) return Ops[0]; 2280 } 2281 2282 // Limit recursion calls depth. 2283 if (Depth > MaxArithDepth) 2284 return getOrCreateAddExpr(Ops, Flags); 2285 2286 // Okay, check to see if the same value occurs in the operand list more than 2287 // once. If so, merge them together into an multiply expression. Since we 2288 // sorted the list, these values are required to be adjacent. 2289 Type *Ty = Ops[0]->getType(); 2290 bool FoundMatch = false; 2291 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2292 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2293 // Scan ahead to count how many equal operands there are. 2294 unsigned Count = 2; 2295 while (i+Count != e && Ops[i+Count] == Ops[i]) 2296 ++Count; 2297 // Merge the values into a multiply. 2298 const SCEV *Scale = getConstant(Ty, Count); 2299 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2300 if (Ops.size() == Count) 2301 return Mul; 2302 Ops[i] = Mul; 2303 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2304 --i; e -= Count - 1; 2305 FoundMatch = true; 2306 } 2307 if (FoundMatch) 2308 return getAddExpr(Ops, Flags, Depth + 1); 2309 2310 // Check for truncates. If all the operands are truncated from the same 2311 // type, see if factoring out the truncate would permit the result to be 2312 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2313 // if the contents of the resulting outer trunc fold to something simple. 2314 auto FindTruncSrcType = [&]() -> Type * { 2315 // We're ultimately looking to fold an addrec of truncs and muls of only 2316 // constants and truncs, so if we find any other types of SCEV 2317 // as operands of the addrec then we bail and return nullptr here. 2318 // Otherwise, we return the type of the operand of a trunc that we find. 2319 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2320 return T->getOperand()->getType(); 2321 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2322 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2323 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2324 return T->getOperand()->getType(); 2325 } 2326 return nullptr; 2327 }; 2328 if (auto *SrcType = FindTruncSrcType()) { 2329 SmallVector<const SCEV *, 8> LargeOps; 2330 bool Ok = true; 2331 // Check all the operands to see if they can be represented in the 2332 // source type of the truncate. 2333 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2334 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2335 if (T->getOperand()->getType() != SrcType) { 2336 Ok = false; 2337 break; 2338 } 2339 LargeOps.push_back(T->getOperand()); 2340 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2341 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2342 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2343 SmallVector<const SCEV *, 8> LargeMulOps; 2344 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2345 if (const SCEVTruncateExpr *T = 2346 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2347 if (T->getOperand()->getType() != SrcType) { 2348 Ok = false; 2349 break; 2350 } 2351 LargeMulOps.push_back(T->getOperand()); 2352 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2353 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2354 } else { 2355 Ok = false; 2356 break; 2357 } 2358 } 2359 if (Ok) 2360 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2361 } else { 2362 Ok = false; 2363 break; 2364 } 2365 } 2366 if (Ok) { 2367 // Evaluate the expression in the larger type. 2368 const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1); 2369 // If it folds to something simple, use it. Otherwise, don't. 2370 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2371 return getTruncateExpr(Fold, Ty); 2372 } 2373 } 2374 2375 // Skip past any other cast SCEVs. 2376 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2377 ++Idx; 2378 2379 // If there are add operands they would be next. 2380 if (Idx < Ops.size()) { 2381 bool DeletedAdd = false; 2382 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2383 if (Ops.size() > AddOpsInlineThreshold || 2384 Add->getNumOperands() > AddOpsInlineThreshold) 2385 break; 2386 // If we have an add, expand the add operands onto the end of the operands 2387 // list. 2388 Ops.erase(Ops.begin()+Idx); 2389 Ops.append(Add->op_begin(), Add->op_end()); 2390 DeletedAdd = true; 2391 } 2392 2393 // If we deleted at least one add, we added operands to the end of the list, 2394 // and they are not necessarily sorted. Recurse to resort and resimplify 2395 // any operands we just acquired. 2396 if (DeletedAdd) 2397 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2398 } 2399 2400 // Skip over the add expression until we get to a multiply. 2401 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2402 ++Idx; 2403 2404 // Check to see if there are any folding opportunities present with 2405 // operands multiplied by constant values. 2406 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2407 uint64_t BitWidth = getTypeSizeInBits(Ty); 2408 DenseMap<const SCEV *, APInt> M; 2409 SmallVector<const SCEV *, 8> NewOps; 2410 APInt AccumulatedConstant(BitWidth, 0); 2411 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2412 Ops.data(), Ops.size(), 2413 APInt(BitWidth, 1), *this)) { 2414 struct APIntCompare { 2415 bool operator()(const APInt &LHS, const APInt &RHS) const { 2416 return LHS.ult(RHS); 2417 } 2418 }; 2419 2420 // Some interesting folding opportunity is present, so its worthwhile to 2421 // re-generate the operands list. Group the operands by constant scale, 2422 // to avoid multiplying by the same constant scale multiple times. 2423 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2424 for (const SCEV *NewOp : NewOps) 2425 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2426 // Re-generate the operands list. 2427 Ops.clear(); 2428 if (AccumulatedConstant != 0) 2429 Ops.push_back(getConstant(AccumulatedConstant)); 2430 for (auto &MulOp : MulOpLists) 2431 if (MulOp.first != 0) 2432 Ops.push_back(getMulExpr( 2433 getConstant(MulOp.first), 2434 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2435 SCEV::FlagAnyWrap, Depth + 1)); 2436 if (Ops.empty()) 2437 return getZero(Ty); 2438 if (Ops.size() == 1) 2439 return Ops[0]; 2440 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2441 } 2442 } 2443 2444 // If we are adding something to a multiply expression, make sure the 2445 // something is not already an operand of the multiply. If so, merge it into 2446 // the multiply. 2447 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2448 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2449 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2450 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2451 if (isa<SCEVConstant>(MulOpSCEV)) 2452 continue; 2453 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2454 if (MulOpSCEV == Ops[AddOp]) { 2455 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2456 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2457 if (Mul->getNumOperands() != 2) { 2458 // If the multiply has more than two operands, we must get the 2459 // Y*Z term. 2460 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2461 Mul->op_begin()+MulOp); 2462 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2463 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2464 } 2465 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2466 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2467 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2468 SCEV::FlagAnyWrap, Depth + 1); 2469 if (Ops.size() == 2) return OuterMul; 2470 if (AddOp < Idx) { 2471 Ops.erase(Ops.begin()+AddOp); 2472 Ops.erase(Ops.begin()+Idx-1); 2473 } else { 2474 Ops.erase(Ops.begin()+Idx); 2475 Ops.erase(Ops.begin()+AddOp-1); 2476 } 2477 Ops.push_back(OuterMul); 2478 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2479 } 2480 2481 // Check this multiply against other multiplies being added together. 2482 for (unsigned OtherMulIdx = Idx+1; 2483 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2484 ++OtherMulIdx) { 2485 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2486 // If MulOp occurs in OtherMul, we can fold the two multiplies 2487 // together. 2488 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2489 OMulOp != e; ++OMulOp) 2490 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2491 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2492 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2493 if (Mul->getNumOperands() != 2) { 2494 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2495 Mul->op_begin()+MulOp); 2496 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2497 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2498 } 2499 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2500 if (OtherMul->getNumOperands() != 2) { 2501 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2502 OtherMul->op_begin()+OMulOp); 2503 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2504 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2505 } 2506 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2507 const SCEV *InnerMulSum = 2508 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2509 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2510 SCEV::FlagAnyWrap, Depth + 1); 2511 if (Ops.size() == 2) return OuterMul; 2512 Ops.erase(Ops.begin()+Idx); 2513 Ops.erase(Ops.begin()+OtherMulIdx-1); 2514 Ops.push_back(OuterMul); 2515 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2516 } 2517 } 2518 } 2519 } 2520 2521 // If there are any add recurrences in the operands list, see if any other 2522 // added values are loop invariant. If so, we can fold them into the 2523 // recurrence. 2524 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2525 ++Idx; 2526 2527 // Scan over all recurrences, trying to fold loop invariants into them. 2528 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2529 // Scan all of the other operands to this add and add them to the vector if 2530 // they are loop invariant w.r.t. the recurrence. 2531 SmallVector<const SCEV *, 8> LIOps; 2532 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2533 const Loop *AddRecLoop = AddRec->getLoop(); 2534 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2535 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2536 LIOps.push_back(Ops[i]); 2537 Ops.erase(Ops.begin()+i); 2538 --i; --e; 2539 } 2540 2541 // If we found some loop invariants, fold them into the recurrence. 2542 if (!LIOps.empty()) { 2543 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2544 LIOps.push_back(AddRec->getStart()); 2545 2546 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2547 AddRec->op_end()); 2548 // This follows from the fact that the no-wrap flags on the outer add 2549 // expression are applicable on the 0th iteration, when the add recurrence 2550 // will be equal to its start value. 2551 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2552 2553 // Build the new addrec. Propagate the NUW and NSW flags if both the 2554 // outer add and the inner addrec are guaranteed to have no overflow. 2555 // Always propagate NW. 2556 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2557 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2558 2559 // If all of the other operands were loop invariant, we are done. 2560 if (Ops.size() == 1) return NewRec; 2561 2562 // Otherwise, add the folded AddRec by the non-invariant parts. 2563 for (unsigned i = 0;; ++i) 2564 if (Ops[i] == AddRec) { 2565 Ops[i] = NewRec; 2566 break; 2567 } 2568 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2569 } 2570 2571 // Okay, if there weren't any loop invariants to be folded, check to see if 2572 // there are multiple AddRec's with the same loop induction variable being 2573 // added together. If so, we can fold them. 2574 for (unsigned OtherIdx = Idx+1; 2575 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2576 ++OtherIdx) { 2577 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2578 // so that the 1st found AddRecExpr is dominated by all others. 2579 assert(DT.dominates( 2580 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2581 AddRec->getLoop()->getHeader()) && 2582 "AddRecExprs are not sorted in reverse dominance order?"); 2583 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2584 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2585 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2586 AddRec->op_end()); 2587 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2588 ++OtherIdx) { 2589 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2590 if (OtherAddRec->getLoop() == AddRecLoop) { 2591 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2592 i != e; ++i) { 2593 if (i >= AddRecOps.size()) { 2594 AddRecOps.append(OtherAddRec->op_begin()+i, 2595 OtherAddRec->op_end()); 2596 break; 2597 } 2598 SmallVector<const SCEV *, 2> TwoOps = { 2599 AddRecOps[i], OtherAddRec->getOperand(i)}; 2600 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2601 } 2602 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2603 } 2604 } 2605 // Step size has changed, so we cannot guarantee no self-wraparound. 2606 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2607 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2608 } 2609 } 2610 2611 // Otherwise couldn't fold anything into this recurrence. Move onto the 2612 // next one. 2613 } 2614 2615 // Okay, it looks like we really DO need an add expr. Check to see if we 2616 // already have one, otherwise create a new one. 2617 return getOrCreateAddExpr(Ops, Flags); 2618 } 2619 2620 const SCEV * 2621 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2622 SCEV::NoWrapFlags Flags) { 2623 FoldingSetNodeID ID; 2624 ID.AddInteger(scAddExpr); 2625 for (const SCEV *Op : Ops) 2626 ID.AddPointer(Op); 2627 void *IP = nullptr; 2628 SCEVAddExpr *S = 2629 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2630 if (!S) { 2631 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2632 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2633 S = new (SCEVAllocator) 2634 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2635 UniqueSCEVs.InsertNode(S, IP); 2636 addToLoopUseLists(S); 2637 } 2638 S->setNoWrapFlags(Flags); 2639 return S; 2640 } 2641 2642 const SCEV * 2643 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2644 SCEV::NoWrapFlags Flags) { 2645 FoldingSetNodeID ID; 2646 ID.AddInteger(scMulExpr); 2647 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2648 ID.AddPointer(Ops[i]); 2649 void *IP = nullptr; 2650 SCEVMulExpr *S = 2651 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2652 if (!S) { 2653 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2654 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2655 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2656 O, Ops.size()); 2657 UniqueSCEVs.InsertNode(S, IP); 2658 addToLoopUseLists(S); 2659 } 2660 S->setNoWrapFlags(Flags); 2661 return S; 2662 } 2663 2664 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2665 uint64_t k = i*j; 2666 if (j > 1 && k / j != i) Overflow = true; 2667 return k; 2668 } 2669 2670 /// Compute the result of "n choose k", the binomial coefficient. If an 2671 /// intermediate computation overflows, Overflow will be set and the return will 2672 /// be garbage. Overflow is not cleared on absence of overflow. 2673 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2674 // We use the multiplicative formula: 2675 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2676 // At each iteration, we take the n-th term of the numeral and divide by the 2677 // (k-n)th term of the denominator. This division will always produce an 2678 // integral result, and helps reduce the chance of overflow in the 2679 // intermediate computations. However, we can still overflow even when the 2680 // final result would fit. 2681 2682 if (n == 0 || n == k) return 1; 2683 if (k > n) return 0; 2684 2685 if (k > n/2) 2686 k = n-k; 2687 2688 uint64_t r = 1; 2689 for (uint64_t i = 1; i <= k; ++i) { 2690 r = umul_ov(r, n-(i-1), Overflow); 2691 r /= i; 2692 } 2693 return r; 2694 } 2695 2696 /// Determine if any of the operands in this SCEV are a constant or if 2697 /// any of the add or multiply expressions in this SCEV contain a constant. 2698 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2699 struct FindConstantInAddMulChain { 2700 bool FoundConstant = false; 2701 2702 bool follow(const SCEV *S) { 2703 FoundConstant |= isa<SCEVConstant>(S); 2704 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2705 } 2706 2707 bool isDone() const { 2708 return FoundConstant; 2709 } 2710 }; 2711 2712 FindConstantInAddMulChain F; 2713 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2714 ST.visitAll(StartExpr); 2715 return F.FoundConstant; 2716 } 2717 2718 /// Get a canonical multiply expression, or something simpler if possible. 2719 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2720 SCEV::NoWrapFlags Flags, 2721 unsigned Depth) { 2722 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2723 "only nuw or nsw allowed"); 2724 assert(!Ops.empty() && "Cannot get empty mul!"); 2725 if (Ops.size() == 1) return Ops[0]; 2726 #ifndef NDEBUG 2727 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2728 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2729 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2730 "SCEVMulExpr operand types don't match!"); 2731 #endif 2732 2733 // Sort by complexity, this groups all similar expression types together. 2734 GroupByComplexity(Ops, &LI, DT); 2735 2736 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2737 2738 // Limit recursion calls depth. 2739 if (Depth > MaxArithDepth) 2740 return getOrCreateMulExpr(Ops, Flags); 2741 2742 // If there are any constants, fold them together. 2743 unsigned Idx = 0; 2744 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2745 2746 // C1*(C2+V) -> C1*C2 + C1*V 2747 if (Ops.size() == 2) 2748 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2749 // If any of Add's ops are Adds or Muls with a constant, 2750 // apply this transformation as well. 2751 if (Add->getNumOperands() == 2) 2752 // TODO: There are some cases where this transformation is not 2753 // profitable, for example: 2754 // Add = (C0 + X) * Y + Z. 2755 // Maybe the scope of this transformation should be narrowed down. 2756 if (containsConstantInAddMulChain(Add)) 2757 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2758 SCEV::FlagAnyWrap, Depth + 1), 2759 getMulExpr(LHSC, Add->getOperand(1), 2760 SCEV::FlagAnyWrap, Depth + 1), 2761 SCEV::FlagAnyWrap, Depth + 1); 2762 2763 ++Idx; 2764 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2765 // We found two constants, fold them together! 2766 ConstantInt *Fold = 2767 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2768 Ops[0] = getConstant(Fold); 2769 Ops.erase(Ops.begin()+1); // Erase the folded element 2770 if (Ops.size() == 1) return Ops[0]; 2771 LHSC = cast<SCEVConstant>(Ops[0]); 2772 } 2773 2774 // If we are left with a constant one being multiplied, strip it off. 2775 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2776 Ops.erase(Ops.begin()); 2777 --Idx; 2778 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2779 // If we have a multiply of zero, it will always be zero. 2780 return Ops[0]; 2781 } else if (Ops[0]->isAllOnesValue()) { 2782 // If we have a mul by -1 of an add, try distributing the -1 among the 2783 // add operands. 2784 if (Ops.size() == 2) { 2785 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2786 SmallVector<const SCEV *, 4> NewOps; 2787 bool AnyFolded = false; 2788 for (const SCEV *AddOp : Add->operands()) { 2789 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2790 Depth + 1); 2791 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2792 NewOps.push_back(Mul); 2793 } 2794 if (AnyFolded) 2795 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2796 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2797 // Negation preserves a recurrence's no self-wrap property. 2798 SmallVector<const SCEV *, 4> Operands; 2799 for (const SCEV *AddRecOp : AddRec->operands()) 2800 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2801 Depth + 1)); 2802 2803 return getAddRecExpr(Operands, AddRec->getLoop(), 2804 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2805 } 2806 } 2807 } 2808 2809 if (Ops.size() == 1) 2810 return Ops[0]; 2811 } 2812 2813 // Skip over the add expression until we get to a multiply. 2814 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2815 ++Idx; 2816 2817 // If there are mul operands inline them all into this expression. 2818 if (Idx < Ops.size()) { 2819 bool DeletedMul = false; 2820 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2821 if (Ops.size() > MulOpsInlineThreshold) 2822 break; 2823 // If we have an mul, expand the mul operands onto the end of the 2824 // operands list. 2825 Ops.erase(Ops.begin()+Idx); 2826 Ops.append(Mul->op_begin(), Mul->op_end()); 2827 DeletedMul = true; 2828 } 2829 2830 // If we deleted at least one mul, we added operands to the end of the 2831 // list, and they are not necessarily sorted. Recurse to resort and 2832 // resimplify any operands we just acquired. 2833 if (DeletedMul) 2834 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2835 } 2836 2837 // If there are any add recurrences in the operands list, see if any other 2838 // added values are loop invariant. If so, we can fold them into the 2839 // recurrence. 2840 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2841 ++Idx; 2842 2843 // Scan over all recurrences, trying to fold loop invariants into them. 2844 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2845 // Scan all of the other operands to this mul and add them to the vector 2846 // if they are loop invariant w.r.t. the recurrence. 2847 SmallVector<const SCEV *, 8> LIOps; 2848 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2849 const Loop *AddRecLoop = AddRec->getLoop(); 2850 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2851 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2852 LIOps.push_back(Ops[i]); 2853 Ops.erase(Ops.begin()+i); 2854 --i; --e; 2855 } 2856 2857 // If we found some loop invariants, fold them into the recurrence. 2858 if (!LIOps.empty()) { 2859 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2860 SmallVector<const SCEV *, 4> NewOps; 2861 NewOps.reserve(AddRec->getNumOperands()); 2862 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2863 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2864 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2865 SCEV::FlagAnyWrap, Depth + 1)); 2866 2867 // Build the new addrec. Propagate the NUW and NSW flags if both the 2868 // outer mul and the inner addrec are guaranteed to have no overflow. 2869 // 2870 // No self-wrap cannot be guaranteed after changing the step size, but 2871 // will be inferred if either NUW or NSW is true. 2872 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2873 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2874 2875 // If all of the other operands were loop invariant, we are done. 2876 if (Ops.size() == 1) return NewRec; 2877 2878 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2879 for (unsigned i = 0;; ++i) 2880 if (Ops[i] == AddRec) { 2881 Ops[i] = NewRec; 2882 break; 2883 } 2884 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2885 } 2886 2887 // Okay, if there weren't any loop invariants to be folded, check to see 2888 // if there are multiple AddRec's with the same loop induction variable 2889 // being multiplied together. If so, we can fold them. 2890 2891 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2892 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2893 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2894 // ]]],+,...up to x=2n}. 2895 // Note that the arguments to choose() are always integers with values 2896 // known at compile time, never SCEV objects. 2897 // 2898 // The implementation avoids pointless extra computations when the two 2899 // addrec's are of different length (mathematically, it's equivalent to 2900 // an infinite stream of zeros on the right). 2901 bool OpsModified = false; 2902 for (unsigned OtherIdx = Idx+1; 2903 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2904 ++OtherIdx) { 2905 const SCEVAddRecExpr *OtherAddRec = 2906 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2907 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2908 continue; 2909 2910 // Limit max number of arguments to avoid creation of unreasonably big 2911 // SCEVAddRecs with very complex operands. 2912 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2913 MaxAddRecSize) 2914 continue; 2915 2916 bool Overflow = false; 2917 Type *Ty = AddRec->getType(); 2918 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2919 SmallVector<const SCEV*, 7> AddRecOps; 2920 for (int x = 0, xe = AddRec->getNumOperands() + 2921 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2922 const SCEV *Term = getZero(Ty); 2923 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2924 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2925 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2926 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2927 z < ze && !Overflow; ++z) { 2928 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2929 uint64_t Coeff; 2930 if (LargerThan64Bits) 2931 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2932 else 2933 Coeff = Coeff1*Coeff2; 2934 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2935 const SCEV *Term1 = AddRec->getOperand(y-z); 2936 const SCEV *Term2 = OtherAddRec->getOperand(z); 2937 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2, 2938 SCEV::FlagAnyWrap, Depth + 1), 2939 SCEV::FlagAnyWrap, Depth + 1); 2940 } 2941 } 2942 AddRecOps.push_back(Term); 2943 } 2944 if (!Overflow) { 2945 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2946 SCEV::FlagAnyWrap); 2947 if (Ops.size() == 2) return NewAddRec; 2948 Ops[Idx] = NewAddRec; 2949 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2950 OpsModified = true; 2951 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2952 if (!AddRec) 2953 break; 2954 } 2955 } 2956 if (OpsModified) 2957 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2958 2959 // Otherwise couldn't fold anything into this recurrence. Move onto the 2960 // next one. 2961 } 2962 2963 // Okay, it looks like we really DO need an mul expr. Check to see if we 2964 // already have one, otherwise create a new one. 2965 return getOrCreateMulExpr(Ops, Flags); 2966 } 2967 2968 /// Represents an unsigned remainder expression based on unsigned division. 2969 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2970 const SCEV *RHS) { 2971 assert(getEffectiveSCEVType(LHS->getType()) == 2972 getEffectiveSCEVType(RHS->getType()) && 2973 "SCEVURemExpr operand types don't match!"); 2974 2975 // Short-circuit easy cases 2976 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2977 // If constant is one, the result is trivial 2978 if (RHSC->getValue()->isOne()) 2979 return getZero(LHS->getType()); // X urem 1 --> 0 2980 2981 // If constant is a power of two, fold into a zext(trunc(LHS)). 2982 if (RHSC->getAPInt().isPowerOf2()) { 2983 Type *FullTy = LHS->getType(); 2984 Type *TruncTy = 2985 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2986 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2987 } 2988 } 2989 2990 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2991 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2992 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2993 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2994 } 2995 2996 /// Get a canonical unsigned division expression, or something simpler if 2997 /// possible. 2998 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2999 const SCEV *RHS) { 3000 assert(getEffectiveSCEVType(LHS->getType()) == 3001 getEffectiveSCEVType(RHS->getType()) && 3002 "SCEVUDivExpr operand types don't match!"); 3003 3004 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3005 if (RHSC->getValue()->isOne()) 3006 return LHS; // X udiv 1 --> x 3007 // If the denominator is zero, the result of the udiv is undefined. Don't 3008 // try to analyze it, because the resolution chosen here may differ from 3009 // the resolution chosen in other parts of the compiler. 3010 if (!RHSC->getValue()->isZero()) { 3011 // Determine if the division can be folded into the operands of 3012 // its operands. 3013 // TODO: Generalize this to non-constants by using known-bits information. 3014 Type *Ty = LHS->getType(); 3015 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3016 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3017 // For non-power-of-two values, effectively round the value up to the 3018 // nearest power of two. 3019 if (!RHSC->getAPInt().isPowerOf2()) 3020 ++MaxShiftAmt; 3021 IntegerType *ExtTy = 3022 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3024 if (const SCEVConstant *Step = 3025 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3026 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3027 const APInt &StepInt = Step->getAPInt(); 3028 const APInt &DivInt = RHSC->getAPInt(); 3029 if (!StepInt.urem(DivInt) && 3030 getZeroExtendExpr(AR, ExtTy) == 3031 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3032 getZeroExtendExpr(Step, ExtTy), 3033 AR->getLoop(), SCEV::FlagAnyWrap)) { 3034 SmallVector<const SCEV *, 4> Operands; 3035 for (const SCEV *Op : AR->operands()) 3036 Operands.push_back(getUDivExpr(Op, RHS)); 3037 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3038 } 3039 /// Get a canonical UDivExpr for a recurrence. 3040 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3041 // We can currently only fold X%N if X is constant. 3042 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3043 if (StartC && !DivInt.urem(StepInt) && 3044 getZeroExtendExpr(AR, ExtTy) == 3045 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3046 getZeroExtendExpr(Step, ExtTy), 3047 AR->getLoop(), SCEV::FlagAnyWrap)) { 3048 const APInt &StartInt = StartC->getAPInt(); 3049 const APInt &StartRem = StartInt.urem(StepInt); 3050 if (StartRem != 0) 3051 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3052 AR->getLoop(), SCEV::FlagNW); 3053 } 3054 } 3055 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3056 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3057 SmallVector<const SCEV *, 4> Operands; 3058 for (const SCEV *Op : M->operands()) 3059 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3060 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3061 // Find an operand that's safely divisible. 3062 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3063 const SCEV *Op = M->getOperand(i); 3064 const SCEV *Div = getUDivExpr(Op, RHSC); 3065 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3066 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3067 M->op_end()); 3068 Operands[i] = Div; 3069 return getMulExpr(Operands); 3070 } 3071 } 3072 } 3073 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3074 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3075 SmallVector<const SCEV *, 4> Operands; 3076 for (const SCEV *Op : A->operands()) 3077 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3078 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3079 Operands.clear(); 3080 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3081 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3082 if (isa<SCEVUDivExpr>(Op) || 3083 getMulExpr(Op, RHS) != A->getOperand(i)) 3084 break; 3085 Operands.push_back(Op); 3086 } 3087 if (Operands.size() == A->getNumOperands()) 3088 return getAddExpr(Operands); 3089 } 3090 } 3091 3092 // Fold if both operands are constant. 3093 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3094 Constant *LHSCV = LHSC->getValue(); 3095 Constant *RHSCV = RHSC->getValue(); 3096 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3097 RHSCV))); 3098 } 3099 } 3100 } 3101 3102 FoldingSetNodeID ID; 3103 ID.AddInteger(scUDivExpr); 3104 ID.AddPointer(LHS); 3105 ID.AddPointer(RHS); 3106 void *IP = nullptr; 3107 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3108 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3109 LHS, RHS); 3110 UniqueSCEVs.InsertNode(S, IP); 3111 addToLoopUseLists(S); 3112 return S; 3113 } 3114 3115 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3116 APInt A = C1->getAPInt().abs(); 3117 APInt B = C2->getAPInt().abs(); 3118 uint32_t ABW = A.getBitWidth(); 3119 uint32_t BBW = B.getBitWidth(); 3120 3121 if (ABW > BBW) 3122 B = B.zext(ABW); 3123 else if (ABW < BBW) 3124 A = A.zext(BBW); 3125 3126 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3127 } 3128 3129 /// Get a canonical unsigned division expression, or something simpler if 3130 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3131 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3132 /// it's not exact because the udiv may be clearing bits. 3133 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3134 const SCEV *RHS) { 3135 // TODO: we could try to find factors in all sorts of things, but for now we 3136 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3137 // end of this file for inspiration. 3138 3139 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3140 if (!Mul || !Mul->hasNoUnsignedWrap()) 3141 return getUDivExpr(LHS, RHS); 3142 3143 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3144 // If the mulexpr multiplies by a constant, then that constant must be the 3145 // first element of the mulexpr. 3146 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3147 if (LHSCst == RHSCst) { 3148 SmallVector<const SCEV *, 2> Operands; 3149 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3150 return getMulExpr(Operands); 3151 } 3152 3153 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3154 // that there's a factor provided by one of the other terms. We need to 3155 // check. 3156 APInt Factor = gcd(LHSCst, RHSCst); 3157 if (!Factor.isIntN(1)) { 3158 LHSCst = 3159 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3160 RHSCst = 3161 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3162 SmallVector<const SCEV *, 2> Operands; 3163 Operands.push_back(LHSCst); 3164 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3165 LHS = getMulExpr(Operands); 3166 RHS = RHSCst; 3167 Mul = dyn_cast<SCEVMulExpr>(LHS); 3168 if (!Mul) 3169 return getUDivExactExpr(LHS, RHS); 3170 } 3171 } 3172 } 3173 3174 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3175 if (Mul->getOperand(i) == RHS) { 3176 SmallVector<const SCEV *, 2> Operands; 3177 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3178 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3179 return getMulExpr(Operands); 3180 } 3181 } 3182 3183 return getUDivExpr(LHS, RHS); 3184 } 3185 3186 /// Get an add recurrence expression for the specified loop. Simplify the 3187 /// expression as much as possible. 3188 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3189 const Loop *L, 3190 SCEV::NoWrapFlags Flags) { 3191 SmallVector<const SCEV *, 4> Operands; 3192 Operands.push_back(Start); 3193 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3194 if (StepChrec->getLoop() == L) { 3195 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3196 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3197 } 3198 3199 Operands.push_back(Step); 3200 return getAddRecExpr(Operands, L, Flags); 3201 } 3202 3203 /// Get an add recurrence expression for the specified loop. Simplify the 3204 /// expression as much as possible. 3205 const SCEV * 3206 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3207 const Loop *L, SCEV::NoWrapFlags Flags) { 3208 if (Operands.size() == 1) return Operands[0]; 3209 #ifndef NDEBUG 3210 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3211 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3212 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3213 "SCEVAddRecExpr operand types don't match!"); 3214 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3215 assert(isLoopInvariant(Operands[i], L) && 3216 "SCEVAddRecExpr operand is not loop-invariant!"); 3217 #endif 3218 3219 if (Operands.back()->isZero()) { 3220 Operands.pop_back(); 3221 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3222 } 3223 3224 // It's tempting to want to call getMaxBackedgeTakenCount count here and 3225 // use that information to infer NUW and NSW flags. However, computing a 3226 // BE count requires calling getAddRecExpr, so we may not yet have a 3227 // meaningful BE count at this point (and if we don't, we'd be stuck 3228 // with a SCEVCouldNotCompute as the cached BE count). 3229 3230 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3231 3232 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3233 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3234 const Loop *NestedLoop = NestedAR->getLoop(); 3235 if (L->contains(NestedLoop) 3236 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3237 : (!NestedLoop->contains(L) && 3238 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3239 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3240 NestedAR->op_end()); 3241 Operands[0] = NestedAR->getStart(); 3242 // AddRecs require their operands be loop-invariant with respect to their 3243 // loops. Don't perform this transformation if it would break this 3244 // requirement. 3245 bool AllInvariant = all_of( 3246 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3247 3248 if (AllInvariant) { 3249 // Create a recurrence for the outer loop with the same step size. 3250 // 3251 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3252 // inner recurrence has the same property. 3253 SCEV::NoWrapFlags OuterFlags = 3254 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3255 3256 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3257 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3258 return isLoopInvariant(Op, NestedLoop); 3259 }); 3260 3261 if (AllInvariant) { 3262 // Ok, both add recurrences are valid after the transformation. 3263 // 3264 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3265 // the outer recurrence has the same property. 3266 SCEV::NoWrapFlags InnerFlags = 3267 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3268 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3269 } 3270 } 3271 // Reset Operands to its original state. 3272 Operands[0] = NestedAR; 3273 } 3274 } 3275 3276 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3277 // already have one, otherwise create a new one. 3278 FoldingSetNodeID ID; 3279 ID.AddInteger(scAddRecExpr); 3280 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3281 ID.AddPointer(Operands[i]); 3282 ID.AddPointer(L); 3283 void *IP = nullptr; 3284 SCEVAddRecExpr *S = 3285 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3286 if (!S) { 3287 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3288 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3289 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3290 O, Operands.size(), L); 3291 UniqueSCEVs.InsertNode(S, IP); 3292 addToLoopUseLists(S); 3293 } 3294 S->setNoWrapFlags(Flags); 3295 return S; 3296 } 3297 3298 const SCEV * 3299 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3300 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3301 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3302 // getSCEV(Base)->getType() has the same address space as Base->getType() 3303 // because SCEV::getType() preserves the address space. 3304 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3305 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3306 // instruction to its SCEV, because the Instruction may be guarded by control 3307 // flow and the no-overflow bits may not be valid for the expression in any 3308 // context. This can be fixed similarly to how these flags are handled for 3309 // adds. 3310 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3311 : SCEV::FlagAnyWrap; 3312 3313 const SCEV *TotalOffset = getZero(IntPtrTy); 3314 // The array size is unimportant. The first thing we do on CurTy is getting 3315 // its element type. 3316 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3317 for (const SCEV *IndexExpr : IndexExprs) { 3318 // Compute the (potentially symbolic) offset in bytes for this index. 3319 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3320 // For a struct, add the member offset. 3321 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3322 unsigned FieldNo = Index->getZExtValue(); 3323 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3324 3325 // Add the field offset to the running total offset. 3326 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3327 3328 // Update CurTy to the type of the field at Index. 3329 CurTy = STy->getTypeAtIndex(Index); 3330 } else { 3331 // Update CurTy to its element type. 3332 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3333 // For an array, add the element offset, explicitly scaled. 3334 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3335 // Getelementptr indices are signed. 3336 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3337 3338 // Multiply the index by the element size to compute the element offset. 3339 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3340 3341 // Add the element offset to the running total offset. 3342 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3343 } 3344 } 3345 3346 // Add the total offset from all the GEP indices to the base. 3347 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3348 } 3349 3350 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3351 const SCEV *RHS) { 3352 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3353 return getSMaxExpr(Ops); 3354 } 3355 3356 const SCEV * 3357 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3358 assert(!Ops.empty() && "Cannot get empty smax!"); 3359 if (Ops.size() == 1) return Ops[0]; 3360 #ifndef NDEBUG 3361 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3362 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3363 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3364 "SCEVSMaxExpr operand types don't match!"); 3365 #endif 3366 3367 // Sort by complexity, this groups all similar expression types together. 3368 GroupByComplexity(Ops, &LI, DT); 3369 3370 // If there are any constants, fold them together. 3371 unsigned Idx = 0; 3372 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3373 ++Idx; 3374 assert(Idx < Ops.size()); 3375 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3376 // We found two constants, fold them together! 3377 ConstantInt *Fold = ConstantInt::get( 3378 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3379 Ops[0] = getConstant(Fold); 3380 Ops.erase(Ops.begin()+1); // Erase the folded element 3381 if (Ops.size() == 1) return Ops[0]; 3382 LHSC = cast<SCEVConstant>(Ops[0]); 3383 } 3384 3385 // If we are left with a constant minimum-int, strip it off. 3386 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3387 Ops.erase(Ops.begin()); 3388 --Idx; 3389 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3390 // If we have an smax with a constant maximum-int, it will always be 3391 // maximum-int. 3392 return Ops[0]; 3393 } 3394 3395 if (Ops.size() == 1) return Ops[0]; 3396 } 3397 3398 // Find the first SMax 3399 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3400 ++Idx; 3401 3402 // Check to see if one of the operands is an SMax. If so, expand its operands 3403 // onto our operand list, and recurse to simplify. 3404 if (Idx < Ops.size()) { 3405 bool DeletedSMax = false; 3406 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3407 Ops.erase(Ops.begin()+Idx); 3408 Ops.append(SMax->op_begin(), SMax->op_end()); 3409 DeletedSMax = true; 3410 } 3411 3412 if (DeletedSMax) 3413 return getSMaxExpr(Ops); 3414 } 3415 3416 // Okay, check to see if the same value occurs in the operand list twice. If 3417 // so, delete one. Since we sorted the list, these values are required to 3418 // be adjacent. 3419 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3420 // X smax Y smax Y --> X smax Y 3421 // X smax Y --> X, if X is always greater than Y 3422 if (Ops[i] == Ops[i+1] || 3423 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3424 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3425 --i; --e; 3426 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3427 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3428 --i; --e; 3429 } 3430 3431 if (Ops.size() == 1) return Ops[0]; 3432 3433 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3434 3435 // Okay, it looks like we really DO need an smax expr. Check to see if we 3436 // already have one, otherwise create a new one. 3437 FoldingSetNodeID ID; 3438 ID.AddInteger(scSMaxExpr); 3439 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3440 ID.AddPointer(Ops[i]); 3441 void *IP = nullptr; 3442 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3443 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3444 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3445 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3446 O, Ops.size()); 3447 UniqueSCEVs.InsertNode(S, IP); 3448 addToLoopUseLists(S); 3449 return S; 3450 } 3451 3452 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3453 const SCEV *RHS) { 3454 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3455 return getUMaxExpr(Ops); 3456 } 3457 3458 const SCEV * 3459 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3460 assert(!Ops.empty() && "Cannot get empty umax!"); 3461 if (Ops.size() == 1) return Ops[0]; 3462 #ifndef NDEBUG 3463 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3464 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3465 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3466 "SCEVUMaxExpr operand types don't match!"); 3467 #endif 3468 3469 // Sort by complexity, this groups all similar expression types together. 3470 GroupByComplexity(Ops, &LI, DT); 3471 3472 // If there are any constants, fold them together. 3473 unsigned Idx = 0; 3474 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3475 ++Idx; 3476 assert(Idx < Ops.size()); 3477 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3478 // We found two constants, fold them together! 3479 ConstantInt *Fold = ConstantInt::get( 3480 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3481 Ops[0] = getConstant(Fold); 3482 Ops.erase(Ops.begin()+1); // Erase the folded element 3483 if (Ops.size() == 1) return Ops[0]; 3484 LHSC = cast<SCEVConstant>(Ops[0]); 3485 } 3486 3487 // If we are left with a constant minimum-int, strip it off. 3488 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3489 Ops.erase(Ops.begin()); 3490 --Idx; 3491 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3492 // If we have an umax with a constant maximum-int, it will always be 3493 // maximum-int. 3494 return Ops[0]; 3495 } 3496 3497 if (Ops.size() == 1) return Ops[0]; 3498 } 3499 3500 // Find the first UMax 3501 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3502 ++Idx; 3503 3504 // Check to see if one of the operands is a UMax. If so, expand its operands 3505 // onto our operand list, and recurse to simplify. 3506 if (Idx < Ops.size()) { 3507 bool DeletedUMax = false; 3508 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3509 Ops.erase(Ops.begin()+Idx); 3510 Ops.append(UMax->op_begin(), UMax->op_end()); 3511 DeletedUMax = true; 3512 } 3513 3514 if (DeletedUMax) 3515 return getUMaxExpr(Ops); 3516 } 3517 3518 // Okay, check to see if the same value occurs in the operand list twice. If 3519 // so, delete one. Since we sorted the list, these values are required to 3520 // be adjacent. 3521 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3522 // X umax Y umax Y --> X umax Y 3523 // X umax Y --> X, if X is always greater than Y 3524 if (Ops[i] == Ops[i+1] || 3525 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3526 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3527 --i; --e; 3528 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3529 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3530 --i; --e; 3531 } 3532 3533 if (Ops.size() == 1) return Ops[0]; 3534 3535 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3536 3537 // Okay, it looks like we really DO need a umax expr. Check to see if we 3538 // already have one, otherwise create a new one. 3539 FoldingSetNodeID ID; 3540 ID.AddInteger(scUMaxExpr); 3541 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3542 ID.AddPointer(Ops[i]); 3543 void *IP = nullptr; 3544 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3545 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3546 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3547 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3548 O, Ops.size()); 3549 UniqueSCEVs.InsertNode(S, IP); 3550 addToLoopUseLists(S); 3551 return S; 3552 } 3553 3554 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3555 const SCEV *RHS) { 3556 // ~smax(~x, ~y) == smin(x, y). 3557 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3558 } 3559 3560 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3561 const SCEV *RHS) { 3562 // ~umax(~x, ~y) == umin(x, y) 3563 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3564 } 3565 3566 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3567 // We can bypass creating a target-independent 3568 // constant expression and then folding it back into a ConstantInt. 3569 // This is just a compile-time optimization. 3570 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3571 } 3572 3573 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3574 StructType *STy, 3575 unsigned FieldNo) { 3576 // We can bypass creating a target-independent 3577 // constant expression and then folding it back into a ConstantInt. 3578 // This is just a compile-time optimization. 3579 return getConstant( 3580 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3581 } 3582 3583 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3584 // Don't attempt to do anything other than create a SCEVUnknown object 3585 // here. createSCEV only calls getUnknown after checking for all other 3586 // interesting possibilities, and any other code that calls getUnknown 3587 // is doing so in order to hide a value from SCEV canonicalization. 3588 3589 FoldingSetNodeID ID; 3590 ID.AddInteger(scUnknown); 3591 ID.AddPointer(V); 3592 void *IP = nullptr; 3593 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3594 assert(cast<SCEVUnknown>(S)->getValue() == V && 3595 "Stale SCEVUnknown in uniquing map!"); 3596 return S; 3597 } 3598 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3599 FirstUnknown); 3600 FirstUnknown = cast<SCEVUnknown>(S); 3601 UniqueSCEVs.InsertNode(S, IP); 3602 return S; 3603 } 3604 3605 //===----------------------------------------------------------------------===// 3606 // Basic SCEV Analysis and PHI Idiom Recognition Code 3607 // 3608 3609 /// Test if values of the given type are analyzable within the SCEV 3610 /// framework. This primarily includes integer types, and it can optionally 3611 /// include pointer types if the ScalarEvolution class has access to 3612 /// target-specific information. 3613 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3614 // Integers and pointers are always SCEVable. 3615 return Ty->isIntegerTy() || Ty->isPointerTy(); 3616 } 3617 3618 /// Return the size in bits of the specified type, for which isSCEVable must 3619 /// return true. 3620 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3621 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3622 if (Ty->isPointerTy()) 3623 return getDataLayout().getIndexTypeSizeInBits(Ty); 3624 return getDataLayout().getTypeSizeInBits(Ty); 3625 } 3626 3627 /// Return a type with the same bitwidth as the given type and which represents 3628 /// how SCEV will treat the given type, for which isSCEVable must return 3629 /// true. For pointer types, this is the pointer-sized integer type. 3630 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3631 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3632 3633 if (Ty->isIntegerTy()) 3634 return Ty; 3635 3636 // The only other support type is pointer. 3637 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3638 return getDataLayout().getIntPtrType(Ty); 3639 } 3640 3641 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3642 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3643 } 3644 3645 const SCEV *ScalarEvolution::getCouldNotCompute() { 3646 return CouldNotCompute.get(); 3647 } 3648 3649 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3650 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3651 auto *SU = dyn_cast<SCEVUnknown>(S); 3652 return SU && SU->getValue() == nullptr; 3653 }); 3654 3655 return !ContainsNulls; 3656 } 3657 3658 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3659 HasRecMapType::iterator I = HasRecMap.find(S); 3660 if (I != HasRecMap.end()) 3661 return I->second; 3662 3663 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3664 HasRecMap.insert({S, FoundAddRec}); 3665 return FoundAddRec; 3666 } 3667 3668 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3669 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3670 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3671 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3672 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3673 if (!Add) 3674 return {S, nullptr}; 3675 3676 if (Add->getNumOperands() != 2) 3677 return {S, nullptr}; 3678 3679 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3680 if (!ConstOp) 3681 return {S, nullptr}; 3682 3683 return {Add->getOperand(1), ConstOp->getValue()}; 3684 } 3685 3686 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3687 /// by the value and offset from any ValueOffsetPair in the set. 3688 SetVector<ScalarEvolution::ValueOffsetPair> * 3689 ScalarEvolution::getSCEVValues(const SCEV *S) { 3690 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3691 if (SI == ExprValueMap.end()) 3692 return nullptr; 3693 #ifndef NDEBUG 3694 if (VerifySCEVMap) { 3695 // Check there is no dangling Value in the set returned. 3696 for (const auto &VE : SI->second) 3697 assert(ValueExprMap.count(VE.first)); 3698 } 3699 #endif 3700 return &SI->second; 3701 } 3702 3703 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3704 /// cannot be used separately. eraseValueFromMap should be used to remove 3705 /// V from ValueExprMap and ExprValueMap at the same time. 3706 void ScalarEvolution::eraseValueFromMap(Value *V) { 3707 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3708 if (I != ValueExprMap.end()) { 3709 const SCEV *S = I->second; 3710 // Remove {V, 0} from the set of ExprValueMap[S] 3711 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3712 SV->remove({V, nullptr}); 3713 3714 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3715 const SCEV *Stripped; 3716 ConstantInt *Offset; 3717 std::tie(Stripped, Offset) = splitAddExpr(S); 3718 if (Offset != nullptr) { 3719 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3720 SV->remove({V, Offset}); 3721 } 3722 ValueExprMap.erase(V); 3723 } 3724 } 3725 3726 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3727 /// TODO: In reality it is better to check the poison recursevely 3728 /// but this is better than nothing. 3729 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3730 if (auto *I = dyn_cast<Instruction>(V)) { 3731 if (isa<OverflowingBinaryOperator>(I)) { 3732 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3733 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3734 return true; 3735 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3736 return true; 3737 } 3738 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3739 return true; 3740 } 3741 return false; 3742 } 3743 3744 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3745 /// create a new one. 3746 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3747 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3748 3749 const SCEV *S = getExistingSCEV(V); 3750 if (S == nullptr) { 3751 S = createSCEV(V); 3752 // During PHI resolution, it is possible to create two SCEVs for the same 3753 // V, so it is needed to double check whether V->S is inserted into 3754 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3755 std::pair<ValueExprMapType::iterator, bool> Pair = 3756 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3757 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3758 ExprValueMap[S].insert({V, nullptr}); 3759 3760 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3761 // ExprValueMap. 3762 const SCEV *Stripped = S; 3763 ConstantInt *Offset = nullptr; 3764 std::tie(Stripped, Offset) = splitAddExpr(S); 3765 // If stripped is SCEVUnknown, don't bother to save 3766 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3767 // increase the complexity of the expansion code. 3768 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3769 // because it may generate add/sub instead of GEP in SCEV expansion. 3770 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3771 !isa<GetElementPtrInst>(V)) 3772 ExprValueMap[Stripped].insert({V, Offset}); 3773 } 3774 } 3775 return S; 3776 } 3777 3778 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3779 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3780 3781 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3782 if (I != ValueExprMap.end()) { 3783 const SCEV *S = I->second; 3784 if (checkValidity(S)) 3785 return S; 3786 eraseValueFromMap(V); 3787 forgetMemoizedResults(S); 3788 } 3789 return nullptr; 3790 } 3791 3792 /// Return a SCEV corresponding to -V = -1*V 3793 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3794 SCEV::NoWrapFlags Flags) { 3795 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3796 return getConstant( 3797 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3798 3799 Type *Ty = V->getType(); 3800 Ty = getEffectiveSCEVType(Ty); 3801 return getMulExpr( 3802 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3803 } 3804 3805 /// Return a SCEV corresponding to ~V = -1-V 3806 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3807 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3808 return getConstant( 3809 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3810 3811 Type *Ty = V->getType(); 3812 Ty = getEffectiveSCEVType(Ty); 3813 const SCEV *AllOnes = 3814 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3815 return getMinusSCEV(AllOnes, V); 3816 } 3817 3818 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3819 SCEV::NoWrapFlags Flags, 3820 unsigned Depth) { 3821 // Fast path: X - X --> 0. 3822 if (LHS == RHS) 3823 return getZero(LHS->getType()); 3824 3825 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3826 // makes it so that we cannot make much use of NUW. 3827 auto AddFlags = SCEV::FlagAnyWrap; 3828 const bool RHSIsNotMinSigned = 3829 !getSignedRangeMin(RHS).isMinSignedValue(); 3830 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3831 // Let M be the minimum representable signed value. Then (-1)*RHS 3832 // signed-wraps if and only if RHS is M. That can happen even for 3833 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3834 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3835 // (-1)*RHS, we need to prove that RHS != M. 3836 // 3837 // If LHS is non-negative and we know that LHS - RHS does not 3838 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3839 // either by proving that RHS > M or that LHS >= 0. 3840 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3841 AddFlags = SCEV::FlagNSW; 3842 } 3843 } 3844 3845 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3846 // RHS is NSW and LHS >= 0. 3847 // 3848 // The difficulty here is that the NSW flag may have been proven 3849 // relative to a loop that is to be found in a recurrence in LHS and 3850 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3851 // larger scope than intended. 3852 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3853 3854 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3855 } 3856 3857 const SCEV * 3858 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3859 Type *SrcTy = V->getType(); 3860 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3861 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3862 "Cannot truncate or zero extend with non-integer arguments!"); 3863 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3864 return V; // No conversion 3865 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3866 return getTruncateExpr(V, Ty); 3867 return getZeroExtendExpr(V, Ty); 3868 } 3869 3870 const SCEV * 3871 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3872 Type *Ty) { 3873 Type *SrcTy = V->getType(); 3874 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3875 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3876 "Cannot truncate or zero extend with non-integer arguments!"); 3877 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3878 return V; // No conversion 3879 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3880 return getTruncateExpr(V, Ty); 3881 return getSignExtendExpr(V, Ty); 3882 } 3883 3884 const SCEV * 3885 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3886 Type *SrcTy = V->getType(); 3887 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3888 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3889 "Cannot noop or zero extend with non-integer arguments!"); 3890 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3891 "getNoopOrZeroExtend cannot truncate!"); 3892 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3893 return V; // No conversion 3894 return getZeroExtendExpr(V, Ty); 3895 } 3896 3897 const SCEV * 3898 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3899 Type *SrcTy = V->getType(); 3900 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3901 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3902 "Cannot noop or sign extend with non-integer arguments!"); 3903 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3904 "getNoopOrSignExtend cannot truncate!"); 3905 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3906 return V; // No conversion 3907 return getSignExtendExpr(V, Ty); 3908 } 3909 3910 const SCEV * 3911 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3912 Type *SrcTy = V->getType(); 3913 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3914 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3915 "Cannot noop or any extend with non-integer arguments!"); 3916 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3917 "getNoopOrAnyExtend cannot truncate!"); 3918 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3919 return V; // No conversion 3920 return getAnyExtendExpr(V, Ty); 3921 } 3922 3923 const SCEV * 3924 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3925 Type *SrcTy = V->getType(); 3926 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3927 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3928 "Cannot truncate or noop with non-integer arguments!"); 3929 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3930 "getTruncateOrNoop cannot extend!"); 3931 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3932 return V; // No conversion 3933 return getTruncateExpr(V, Ty); 3934 } 3935 3936 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3937 const SCEV *RHS) { 3938 const SCEV *PromotedLHS = LHS; 3939 const SCEV *PromotedRHS = RHS; 3940 3941 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3942 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3943 else 3944 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3945 3946 return getUMaxExpr(PromotedLHS, PromotedRHS); 3947 } 3948 3949 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3950 const SCEV *RHS) { 3951 const SCEV *PromotedLHS = LHS; 3952 const SCEV *PromotedRHS = RHS; 3953 3954 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3955 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3956 else 3957 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3958 3959 return getUMinExpr(PromotedLHS, PromotedRHS); 3960 } 3961 3962 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3963 // A pointer operand may evaluate to a nonpointer expression, such as null. 3964 if (!V->getType()->isPointerTy()) 3965 return V; 3966 3967 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3968 return getPointerBase(Cast->getOperand()); 3969 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3970 const SCEV *PtrOp = nullptr; 3971 for (const SCEV *NAryOp : NAry->operands()) { 3972 if (NAryOp->getType()->isPointerTy()) { 3973 // Cannot find the base of an expression with multiple pointer operands. 3974 if (PtrOp) 3975 return V; 3976 PtrOp = NAryOp; 3977 } 3978 } 3979 if (!PtrOp) 3980 return V; 3981 return getPointerBase(PtrOp); 3982 } 3983 return V; 3984 } 3985 3986 /// Push users of the given Instruction onto the given Worklist. 3987 static void 3988 PushDefUseChildren(Instruction *I, 3989 SmallVectorImpl<Instruction *> &Worklist) { 3990 // Push the def-use children onto the Worklist stack. 3991 for (User *U : I->users()) 3992 Worklist.push_back(cast<Instruction>(U)); 3993 } 3994 3995 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3996 SmallVector<Instruction *, 16> Worklist; 3997 PushDefUseChildren(PN, Worklist); 3998 3999 SmallPtrSet<Instruction *, 8> Visited; 4000 Visited.insert(PN); 4001 while (!Worklist.empty()) { 4002 Instruction *I = Worklist.pop_back_val(); 4003 if (!Visited.insert(I).second) 4004 continue; 4005 4006 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4007 if (It != ValueExprMap.end()) { 4008 const SCEV *Old = It->second; 4009 4010 // Short-circuit the def-use traversal if the symbolic name 4011 // ceases to appear in expressions. 4012 if (Old != SymName && !hasOperand(Old, SymName)) 4013 continue; 4014 4015 // SCEVUnknown for a PHI either means that it has an unrecognized 4016 // structure, it's a PHI that's in the progress of being computed 4017 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4018 // additional loop trip count information isn't going to change anything. 4019 // In the second case, createNodeForPHI will perform the necessary 4020 // updates on its own when it gets to that point. In the third, we do 4021 // want to forget the SCEVUnknown. 4022 if (!isa<PHINode>(I) || 4023 !isa<SCEVUnknown>(Old) || 4024 (I != PN && Old == SymName)) { 4025 eraseValueFromMap(It->first); 4026 forgetMemoizedResults(Old); 4027 } 4028 } 4029 4030 PushDefUseChildren(I, Worklist); 4031 } 4032 } 4033 4034 namespace { 4035 4036 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4037 /// expression in case its Loop is L. If it is not L then 4038 /// if IgnoreOtherLoops is true then use AddRec itself 4039 /// otherwise rewrite cannot be done. 4040 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4041 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4042 public: 4043 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4044 bool IgnoreOtherLoops = true) { 4045 SCEVInitRewriter Rewriter(L, SE); 4046 const SCEV *Result = Rewriter.visit(S); 4047 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4048 return SE.getCouldNotCompute(); 4049 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4050 ? SE.getCouldNotCompute() 4051 : Result; 4052 } 4053 4054 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4055 if (!SE.isLoopInvariant(Expr, L)) 4056 SeenLoopVariantSCEVUnknown = true; 4057 return Expr; 4058 } 4059 4060 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4061 // Only re-write AddRecExprs for this loop. 4062 if (Expr->getLoop() == L) 4063 return Expr->getStart(); 4064 SeenOtherLoops = true; 4065 return Expr; 4066 } 4067 4068 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4069 4070 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4071 4072 private: 4073 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4074 : SCEVRewriteVisitor(SE), L(L) {} 4075 4076 const Loop *L; 4077 bool SeenLoopVariantSCEVUnknown = false; 4078 bool SeenOtherLoops = false; 4079 }; 4080 4081 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4082 /// increment expression in case its Loop is L. If it is not L then 4083 /// use AddRec itself. 4084 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4085 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4086 public: 4087 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4088 SCEVPostIncRewriter Rewriter(L, SE); 4089 const SCEV *Result = Rewriter.visit(S); 4090 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4091 ? SE.getCouldNotCompute() 4092 : Result; 4093 } 4094 4095 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4096 if (!SE.isLoopInvariant(Expr, L)) 4097 SeenLoopVariantSCEVUnknown = true; 4098 return Expr; 4099 } 4100 4101 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4102 // Only re-write AddRecExprs for this loop. 4103 if (Expr->getLoop() == L) 4104 return Expr->getPostIncExpr(SE); 4105 SeenOtherLoops = true; 4106 return Expr; 4107 } 4108 4109 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4110 4111 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4112 4113 private: 4114 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4115 : SCEVRewriteVisitor(SE), L(L) {} 4116 4117 const Loop *L; 4118 bool SeenLoopVariantSCEVUnknown = false; 4119 bool SeenOtherLoops = false; 4120 }; 4121 4122 /// This class evaluates the compare condition by matching it against the 4123 /// condition of loop latch. If there is a match we assume a true value 4124 /// for the condition while building SCEV nodes. 4125 class SCEVBackedgeConditionFolder 4126 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4127 public: 4128 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4129 ScalarEvolution &SE) { 4130 bool IsPosBECond = false; 4131 Value *BECond = nullptr; 4132 if (BasicBlock *Latch = L->getLoopLatch()) { 4133 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4134 if (BI && BI->isConditional()) { 4135 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4136 "Both outgoing branches should not target same header!"); 4137 BECond = BI->getCondition(); 4138 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4139 } else { 4140 return S; 4141 } 4142 } 4143 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4144 return Rewriter.visit(S); 4145 } 4146 4147 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4148 const SCEV *Result = Expr; 4149 bool InvariantF = SE.isLoopInvariant(Expr, L); 4150 4151 if (!InvariantF) { 4152 Instruction *I = cast<Instruction>(Expr->getValue()); 4153 switch (I->getOpcode()) { 4154 case Instruction::Select: { 4155 SelectInst *SI = cast<SelectInst>(I); 4156 Optional<const SCEV *> Res = 4157 compareWithBackedgeCondition(SI->getCondition()); 4158 if (Res.hasValue()) { 4159 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4160 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4161 } 4162 break; 4163 } 4164 default: { 4165 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4166 if (Res.hasValue()) 4167 Result = Res.getValue(); 4168 break; 4169 } 4170 } 4171 } 4172 return Result; 4173 } 4174 4175 private: 4176 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4177 bool IsPosBECond, ScalarEvolution &SE) 4178 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4179 IsPositiveBECond(IsPosBECond) {} 4180 4181 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4182 4183 const Loop *L; 4184 /// Loop back condition. 4185 Value *BackedgeCond = nullptr; 4186 /// Set to true if loop back is on positive branch condition. 4187 bool IsPositiveBECond; 4188 }; 4189 4190 Optional<const SCEV *> 4191 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4192 4193 // If value matches the backedge condition for loop latch, 4194 // then return a constant evolution node based on loopback 4195 // branch taken. 4196 if (BackedgeCond == IC) 4197 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4198 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4199 return None; 4200 } 4201 4202 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4203 public: 4204 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4205 ScalarEvolution &SE) { 4206 SCEVShiftRewriter Rewriter(L, SE); 4207 const SCEV *Result = Rewriter.visit(S); 4208 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4209 } 4210 4211 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4212 // Only allow AddRecExprs for this loop. 4213 if (!SE.isLoopInvariant(Expr, L)) 4214 Valid = false; 4215 return Expr; 4216 } 4217 4218 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4219 if (Expr->getLoop() == L && Expr->isAffine()) 4220 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4221 Valid = false; 4222 return Expr; 4223 } 4224 4225 bool isValid() { return Valid; } 4226 4227 private: 4228 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4229 : SCEVRewriteVisitor(SE), L(L) {} 4230 4231 const Loop *L; 4232 bool Valid = true; 4233 }; 4234 4235 } // end anonymous namespace 4236 4237 SCEV::NoWrapFlags 4238 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4239 if (!AR->isAffine()) 4240 return SCEV::FlagAnyWrap; 4241 4242 using OBO = OverflowingBinaryOperator; 4243 4244 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4245 4246 if (!AR->hasNoSignedWrap()) { 4247 ConstantRange AddRecRange = getSignedRange(AR); 4248 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4249 4250 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4251 Instruction::Add, IncRange, OBO::NoSignedWrap); 4252 if (NSWRegion.contains(AddRecRange)) 4253 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4254 } 4255 4256 if (!AR->hasNoUnsignedWrap()) { 4257 ConstantRange AddRecRange = getUnsignedRange(AR); 4258 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4259 4260 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4261 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4262 if (NUWRegion.contains(AddRecRange)) 4263 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4264 } 4265 4266 return Result; 4267 } 4268 4269 namespace { 4270 4271 /// Represents an abstract binary operation. This may exist as a 4272 /// normal instruction or constant expression, or may have been 4273 /// derived from an expression tree. 4274 struct BinaryOp { 4275 unsigned Opcode; 4276 Value *LHS; 4277 Value *RHS; 4278 bool IsNSW = false; 4279 bool IsNUW = false; 4280 4281 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4282 /// constant expression. 4283 Operator *Op = nullptr; 4284 4285 explicit BinaryOp(Operator *Op) 4286 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4287 Op(Op) { 4288 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4289 IsNSW = OBO->hasNoSignedWrap(); 4290 IsNUW = OBO->hasNoUnsignedWrap(); 4291 } 4292 } 4293 4294 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4295 bool IsNUW = false) 4296 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4297 }; 4298 4299 } // end anonymous namespace 4300 4301 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4302 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4303 auto *Op = dyn_cast<Operator>(V); 4304 if (!Op) 4305 return None; 4306 4307 // Implementation detail: all the cleverness here should happen without 4308 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4309 // SCEV expressions when possible, and we should not break that. 4310 4311 switch (Op->getOpcode()) { 4312 case Instruction::Add: 4313 case Instruction::Sub: 4314 case Instruction::Mul: 4315 case Instruction::UDiv: 4316 case Instruction::URem: 4317 case Instruction::And: 4318 case Instruction::Or: 4319 case Instruction::AShr: 4320 case Instruction::Shl: 4321 return BinaryOp(Op); 4322 4323 case Instruction::Xor: 4324 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4325 // If the RHS of the xor is a signmask, then this is just an add. 4326 // Instcombine turns add of signmask into xor as a strength reduction step. 4327 if (RHSC->getValue().isSignMask()) 4328 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4329 return BinaryOp(Op); 4330 4331 case Instruction::LShr: 4332 // Turn logical shift right of a constant into a unsigned divide. 4333 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4334 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4335 4336 // If the shift count is not less than the bitwidth, the result of 4337 // the shift is undefined. Don't try to analyze it, because the 4338 // resolution chosen here may differ from the resolution chosen in 4339 // other parts of the compiler. 4340 if (SA->getValue().ult(BitWidth)) { 4341 Constant *X = 4342 ConstantInt::get(SA->getContext(), 4343 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4344 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4345 } 4346 } 4347 return BinaryOp(Op); 4348 4349 case Instruction::ExtractValue: { 4350 auto *EVI = cast<ExtractValueInst>(Op); 4351 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4352 break; 4353 4354 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 4355 if (!CI) 4356 break; 4357 4358 if (auto *F = CI->getCalledFunction()) 4359 switch (F->getIntrinsicID()) { 4360 case Intrinsic::sadd_with_overflow: 4361 case Intrinsic::uadd_with_overflow: 4362 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4363 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4364 CI->getArgOperand(1)); 4365 4366 // Now that we know that all uses of the arithmetic-result component of 4367 // CI are guarded by the overflow check, we can go ahead and pretend 4368 // that the arithmetic is non-overflowing. 4369 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 4370 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4371 CI->getArgOperand(1), /* IsNSW = */ true, 4372 /* IsNUW = */ false); 4373 else 4374 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 4375 CI->getArgOperand(1), /* IsNSW = */ false, 4376 /* IsNUW*/ true); 4377 case Intrinsic::ssub_with_overflow: 4378 case Intrinsic::usub_with_overflow: 4379 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 4380 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4381 CI->getArgOperand(1)); 4382 4383 // The same reasoning as sadd/uadd above. 4384 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow) 4385 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4386 CI->getArgOperand(1), /* IsNSW = */ true, 4387 /* IsNUW = */ false); 4388 else 4389 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 4390 CI->getArgOperand(1), /* IsNSW = */ false, 4391 /* IsNUW = */ true); 4392 case Intrinsic::smul_with_overflow: 4393 case Intrinsic::umul_with_overflow: 4394 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 4395 CI->getArgOperand(1)); 4396 default: 4397 break; 4398 } 4399 break; 4400 } 4401 4402 default: 4403 break; 4404 } 4405 4406 return None; 4407 } 4408 4409 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4410 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4411 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4412 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4413 /// follows one of the following patterns: 4414 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4415 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4416 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4417 /// we return the type of the truncation operation, and indicate whether the 4418 /// truncated type should be treated as signed/unsigned by setting 4419 /// \p Signed to true/false, respectively. 4420 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4421 bool &Signed, ScalarEvolution &SE) { 4422 // The case where Op == SymbolicPHI (that is, with no type conversions on 4423 // the way) is handled by the regular add recurrence creating logic and 4424 // would have already been triggered in createAddRecForPHI. Reaching it here 4425 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4426 // because one of the other operands of the SCEVAddExpr updating this PHI is 4427 // not invariant). 4428 // 4429 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4430 // this case predicates that allow us to prove that Op == SymbolicPHI will 4431 // be added. 4432 if (Op == SymbolicPHI) 4433 return nullptr; 4434 4435 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4436 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4437 if (SourceBits != NewBits) 4438 return nullptr; 4439 4440 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4441 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4442 if (!SExt && !ZExt) 4443 return nullptr; 4444 const SCEVTruncateExpr *Trunc = 4445 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4446 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4447 if (!Trunc) 4448 return nullptr; 4449 const SCEV *X = Trunc->getOperand(); 4450 if (X != SymbolicPHI) 4451 return nullptr; 4452 Signed = SExt != nullptr; 4453 return Trunc->getType(); 4454 } 4455 4456 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4457 if (!PN->getType()->isIntegerTy()) 4458 return nullptr; 4459 const Loop *L = LI.getLoopFor(PN->getParent()); 4460 if (!L || L->getHeader() != PN->getParent()) 4461 return nullptr; 4462 return L; 4463 } 4464 4465 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4466 // computation that updates the phi follows the following pattern: 4467 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4468 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4469 // If so, try to see if it can be rewritten as an AddRecExpr under some 4470 // Predicates. If successful, return them as a pair. Also cache the results 4471 // of the analysis. 4472 // 4473 // Example usage scenario: 4474 // Say the Rewriter is called for the following SCEV: 4475 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4476 // where: 4477 // %X = phi i64 (%Start, %BEValue) 4478 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4479 // and call this function with %SymbolicPHI = %X. 4480 // 4481 // The analysis will find that the value coming around the backedge has 4482 // the following SCEV: 4483 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4484 // Upon concluding that this matches the desired pattern, the function 4485 // will return the pair {NewAddRec, SmallPredsVec} where: 4486 // NewAddRec = {%Start,+,%Step} 4487 // SmallPredsVec = {P1, P2, P3} as follows: 4488 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4489 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4490 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4491 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4492 // under the predicates {P1,P2,P3}. 4493 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4494 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4495 // 4496 // TODO's: 4497 // 4498 // 1) Extend the Induction descriptor to also support inductions that involve 4499 // casts: When needed (namely, when we are called in the context of the 4500 // vectorizer induction analysis), a Set of cast instructions will be 4501 // populated by this method, and provided back to isInductionPHI. This is 4502 // needed to allow the vectorizer to properly record them to be ignored by 4503 // the cost model and to avoid vectorizing them (otherwise these casts, 4504 // which are redundant under the runtime overflow checks, will be 4505 // vectorized, which can be costly). 4506 // 4507 // 2) Support additional induction/PHISCEV patterns: We also want to support 4508 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4509 // after the induction update operation (the induction increment): 4510 // 4511 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4512 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4513 // 4514 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4515 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4516 // 4517 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4518 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4519 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4520 SmallVector<const SCEVPredicate *, 3> Predicates; 4521 4522 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4523 // return an AddRec expression under some predicate. 4524 4525 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4526 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4527 assert(L && "Expecting an integer loop header phi"); 4528 4529 // The loop may have multiple entrances or multiple exits; we can analyze 4530 // this phi as an addrec if it has a unique entry value and a unique 4531 // backedge value. 4532 Value *BEValueV = nullptr, *StartValueV = nullptr; 4533 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4534 Value *V = PN->getIncomingValue(i); 4535 if (L->contains(PN->getIncomingBlock(i))) { 4536 if (!BEValueV) { 4537 BEValueV = V; 4538 } else if (BEValueV != V) { 4539 BEValueV = nullptr; 4540 break; 4541 } 4542 } else if (!StartValueV) { 4543 StartValueV = V; 4544 } else if (StartValueV != V) { 4545 StartValueV = nullptr; 4546 break; 4547 } 4548 } 4549 if (!BEValueV || !StartValueV) 4550 return None; 4551 4552 const SCEV *BEValue = getSCEV(BEValueV); 4553 4554 // If the value coming around the backedge is an add with the symbolic 4555 // value we just inserted, possibly with casts that we can ignore under 4556 // an appropriate runtime guard, then we found a simple induction variable! 4557 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4558 if (!Add) 4559 return None; 4560 4561 // If there is a single occurrence of the symbolic value, possibly 4562 // casted, replace it with a recurrence. 4563 unsigned FoundIndex = Add->getNumOperands(); 4564 Type *TruncTy = nullptr; 4565 bool Signed; 4566 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4567 if ((TruncTy = 4568 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4569 if (FoundIndex == e) { 4570 FoundIndex = i; 4571 break; 4572 } 4573 4574 if (FoundIndex == Add->getNumOperands()) 4575 return None; 4576 4577 // Create an add with everything but the specified operand. 4578 SmallVector<const SCEV *, 8> Ops; 4579 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4580 if (i != FoundIndex) 4581 Ops.push_back(Add->getOperand(i)); 4582 const SCEV *Accum = getAddExpr(Ops); 4583 4584 // The runtime checks will not be valid if the step amount is 4585 // varying inside the loop. 4586 if (!isLoopInvariant(Accum, L)) 4587 return None; 4588 4589 // *** Part2: Create the predicates 4590 4591 // Analysis was successful: we have a phi-with-cast pattern for which we 4592 // can return an AddRec expression under the following predicates: 4593 // 4594 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4595 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4596 // P2: An Equal predicate that guarantees that 4597 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4598 // P3: An Equal predicate that guarantees that 4599 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4600 // 4601 // As we next prove, the above predicates guarantee that: 4602 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4603 // 4604 // 4605 // More formally, we want to prove that: 4606 // Expr(i+1) = Start + (i+1) * Accum 4607 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4608 // 4609 // Given that: 4610 // 1) Expr(0) = Start 4611 // 2) Expr(1) = Start + Accum 4612 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4613 // 3) Induction hypothesis (step i): 4614 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4615 // 4616 // Proof: 4617 // Expr(i+1) = 4618 // = Start + (i+1)*Accum 4619 // = (Start + i*Accum) + Accum 4620 // = Expr(i) + Accum 4621 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4622 // :: from step i 4623 // 4624 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4625 // 4626 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4627 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4628 // + Accum :: from P3 4629 // 4630 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4631 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4632 // 4633 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4634 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4635 // 4636 // By induction, the same applies to all iterations 1<=i<n: 4637 // 4638 4639 // Create a truncated addrec for which we will add a no overflow check (P1). 4640 const SCEV *StartVal = getSCEV(StartValueV); 4641 const SCEV *PHISCEV = 4642 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4643 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4644 4645 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4646 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4647 // will be constant. 4648 // 4649 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4650 // add P1. 4651 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4652 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4653 Signed ? SCEVWrapPredicate::IncrementNSSW 4654 : SCEVWrapPredicate::IncrementNUSW; 4655 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4656 Predicates.push_back(AddRecPred); 4657 } 4658 4659 // Create the Equal Predicates P2,P3: 4660 4661 // It is possible that the predicates P2 and/or P3 are computable at 4662 // compile time due to StartVal and/or Accum being constants. 4663 // If either one is, then we can check that now and escape if either P2 4664 // or P3 is false. 4665 4666 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4667 // for each of StartVal and Accum 4668 auto getExtendedExpr = [&](const SCEV *Expr, 4669 bool CreateSignExtend) -> const SCEV * { 4670 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4671 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4672 const SCEV *ExtendedExpr = 4673 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4674 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4675 return ExtendedExpr; 4676 }; 4677 4678 // Given: 4679 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4680 // = getExtendedExpr(Expr) 4681 // Determine whether the predicate P: Expr == ExtendedExpr 4682 // is known to be false at compile time 4683 auto PredIsKnownFalse = [&](const SCEV *Expr, 4684 const SCEV *ExtendedExpr) -> bool { 4685 return Expr != ExtendedExpr && 4686 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4687 }; 4688 4689 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4690 if (PredIsKnownFalse(StartVal, StartExtended)) { 4691 DEBUG(dbgs() << "P2 is compile-time false\n";); 4692 return None; 4693 } 4694 4695 // The Step is always Signed (because the overflow checks are either 4696 // NSSW or NUSW) 4697 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4698 if (PredIsKnownFalse(Accum, AccumExtended)) { 4699 DEBUG(dbgs() << "P3 is compile-time false\n";); 4700 return None; 4701 } 4702 4703 auto AppendPredicate = [&](const SCEV *Expr, 4704 const SCEV *ExtendedExpr) -> void { 4705 if (Expr != ExtendedExpr && 4706 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4707 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4708 DEBUG (dbgs() << "Added Predicate: " << *Pred); 4709 Predicates.push_back(Pred); 4710 } 4711 }; 4712 4713 AppendPredicate(StartVal, StartExtended); 4714 AppendPredicate(Accum, AccumExtended); 4715 4716 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4717 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4718 // into NewAR if it will also add the runtime overflow checks specified in 4719 // Predicates. 4720 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4721 4722 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4723 std::make_pair(NewAR, Predicates); 4724 // Remember the result of the analysis for this SCEV at this locayyytion. 4725 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4726 return PredRewrite; 4727 } 4728 4729 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4730 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4731 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4732 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4733 if (!L) 4734 return None; 4735 4736 // Check to see if we already analyzed this PHI. 4737 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4738 if (I != PredicatedSCEVRewrites.end()) { 4739 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4740 I->second; 4741 // Analysis was done before and failed to create an AddRec: 4742 if (Rewrite.first == SymbolicPHI) 4743 return None; 4744 // Analysis was done before and succeeded to create an AddRec under 4745 // a predicate: 4746 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4747 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4748 return Rewrite; 4749 } 4750 4751 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4752 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4753 4754 // Record in the cache that the analysis failed 4755 if (!Rewrite) { 4756 SmallVector<const SCEVPredicate *, 3> Predicates; 4757 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4758 return None; 4759 } 4760 4761 return Rewrite; 4762 } 4763 4764 // FIXME: This utility is currently required because the Rewriter currently 4765 // does not rewrite this expression: 4766 // {0, +, (sext ix (trunc iy to ix) to iy)} 4767 // into {0, +, %step}, 4768 // even when the following Equal predicate exists: 4769 // "%step == (sext ix (trunc iy to ix) to iy)". 4770 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4771 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4772 if (AR1 == AR2) 4773 return true; 4774 4775 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4776 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4777 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4778 return false; 4779 return true; 4780 }; 4781 4782 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4783 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4784 return false; 4785 return true; 4786 } 4787 4788 /// A helper function for createAddRecFromPHI to handle simple cases. 4789 /// 4790 /// This function tries to find an AddRec expression for the simplest (yet most 4791 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4792 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4793 /// technique for finding the AddRec expression. 4794 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4795 Value *BEValueV, 4796 Value *StartValueV) { 4797 const Loop *L = LI.getLoopFor(PN->getParent()); 4798 assert(L && L->getHeader() == PN->getParent()); 4799 assert(BEValueV && StartValueV); 4800 4801 auto BO = MatchBinaryOp(BEValueV, DT); 4802 if (!BO) 4803 return nullptr; 4804 4805 if (BO->Opcode != Instruction::Add) 4806 return nullptr; 4807 4808 const SCEV *Accum = nullptr; 4809 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4810 Accum = getSCEV(BO->RHS); 4811 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4812 Accum = getSCEV(BO->LHS); 4813 4814 if (!Accum) 4815 return nullptr; 4816 4817 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4818 if (BO->IsNUW) 4819 Flags = setFlags(Flags, SCEV::FlagNUW); 4820 if (BO->IsNSW) 4821 Flags = setFlags(Flags, SCEV::FlagNSW); 4822 4823 const SCEV *StartVal = getSCEV(StartValueV); 4824 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4825 4826 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4827 4828 // We can add Flags to the post-inc expression only if we 4829 // know that it is *undefined behavior* for BEValueV to 4830 // overflow. 4831 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4832 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4833 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4834 4835 return PHISCEV; 4836 } 4837 4838 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4839 const Loop *L = LI.getLoopFor(PN->getParent()); 4840 if (!L || L->getHeader() != PN->getParent()) 4841 return nullptr; 4842 4843 // The loop may have multiple entrances or multiple exits; we can analyze 4844 // this phi as an addrec if it has a unique entry value and a unique 4845 // backedge value. 4846 Value *BEValueV = nullptr, *StartValueV = nullptr; 4847 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4848 Value *V = PN->getIncomingValue(i); 4849 if (L->contains(PN->getIncomingBlock(i))) { 4850 if (!BEValueV) { 4851 BEValueV = V; 4852 } else if (BEValueV != V) { 4853 BEValueV = nullptr; 4854 break; 4855 } 4856 } else if (!StartValueV) { 4857 StartValueV = V; 4858 } else if (StartValueV != V) { 4859 StartValueV = nullptr; 4860 break; 4861 } 4862 } 4863 if (!BEValueV || !StartValueV) 4864 return nullptr; 4865 4866 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4867 "PHI node already processed?"); 4868 4869 // First, try to find AddRec expression without creating a fictituos symbolic 4870 // value for PN. 4871 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4872 return S; 4873 4874 // Handle PHI node value symbolically. 4875 const SCEV *SymbolicName = getUnknown(PN); 4876 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4877 4878 // Using this symbolic name for the PHI, analyze the value coming around 4879 // the back-edge. 4880 const SCEV *BEValue = getSCEV(BEValueV); 4881 4882 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4883 // has a special value for the first iteration of the loop. 4884 4885 // If the value coming around the backedge is an add with the symbolic 4886 // value we just inserted, then we found a simple induction variable! 4887 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4888 // If there is a single occurrence of the symbolic value, replace it 4889 // with a recurrence. 4890 unsigned FoundIndex = Add->getNumOperands(); 4891 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4892 if (Add->getOperand(i) == SymbolicName) 4893 if (FoundIndex == e) { 4894 FoundIndex = i; 4895 break; 4896 } 4897 4898 if (FoundIndex != Add->getNumOperands()) { 4899 // Create an add with everything but the specified operand. 4900 SmallVector<const SCEV *, 8> Ops; 4901 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4902 if (i != FoundIndex) 4903 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4904 L, *this)); 4905 const SCEV *Accum = getAddExpr(Ops); 4906 4907 // This is not a valid addrec if the step amount is varying each 4908 // loop iteration, but is not itself an addrec in this loop. 4909 if (isLoopInvariant(Accum, L) || 4910 (isa<SCEVAddRecExpr>(Accum) && 4911 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4912 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4913 4914 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4915 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4916 if (BO->IsNUW) 4917 Flags = setFlags(Flags, SCEV::FlagNUW); 4918 if (BO->IsNSW) 4919 Flags = setFlags(Flags, SCEV::FlagNSW); 4920 } 4921 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4922 // If the increment is an inbounds GEP, then we know the address 4923 // space cannot be wrapped around. We cannot make any guarantee 4924 // about signed or unsigned overflow because pointers are 4925 // unsigned but we may have a negative index from the base 4926 // pointer. We can guarantee that no unsigned wrap occurs if the 4927 // indices form a positive value. 4928 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4929 Flags = setFlags(Flags, SCEV::FlagNW); 4930 4931 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4932 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4933 Flags = setFlags(Flags, SCEV::FlagNUW); 4934 } 4935 4936 // We cannot transfer nuw and nsw flags from subtraction 4937 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4938 // for instance. 4939 } 4940 4941 const SCEV *StartVal = getSCEV(StartValueV); 4942 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4943 4944 // Okay, for the entire analysis of this edge we assumed the PHI 4945 // to be symbolic. We now need to go back and purge all of the 4946 // entries for the scalars that use the symbolic expression. 4947 forgetSymbolicName(PN, SymbolicName); 4948 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4949 4950 // We can add Flags to the post-inc expression only if we 4951 // know that it is *undefined behavior* for BEValueV to 4952 // overflow. 4953 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4954 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4955 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4956 4957 return PHISCEV; 4958 } 4959 } 4960 } else { 4961 // Otherwise, this could be a loop like this: 4962 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4963 // In this case, j = {1,+,1} and BEValue is j. 4964 // Because the other in-value of i (0) fits the evolution of BEValue 4965 // i really is an addrec evolution. 4966 // 4967 // We can generalize this saying that i is the shifted value of BEValue 4968 // by one iteration: 4969 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4970 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4971 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4972 if (Shifted != getCouldNotCompute() && 4973 Start != getCouldNotCompute()) { 4974 const SCEV *StartVal = getSCEV(StartValueV); 4975 if (Start == StartVal) { 4976 // Okay, for the entire analysis of this edge we assumed the PHI 4977 // to be symbolic. We now need to go back and purge all of the 4978 // entries for the scalars that use the symbolic expression. 4979 forgetSymbolicName(PN, SymbolicName); 4980 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4981 return Shifted; 4982 } 4983 } 4984 } 4985 4986 // Remove the temporary PHI node SCEV that has been inserted while intending 4987 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4988 // as it will prevent later (possibly simpler) SCEV expressions to be added 4989 // to the ValueExprMap. 4990 eraseValueFromMap(PN); 4991 4992 return nullptr; 4993 } 4994 4995 // Checks if the SCEV S is available at BB. S is considered available at BB 4996 // if S can be materialized at BB without introducing a fault. 4997 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4998 BasicBlock *BB) { 4999 struct CheckAvailable { 5000 bool TraversalDone = false; 5001 bool Available = true; 5002 5003 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5004 BasicBlock *BB = nullptr; 5005 DominatorTree &DT; 5006 5007 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5008 : L(L), BB(BB), DT(DT) {} 5009 5010 bool setUnavailable() { 5011 TraversalDone = true; 5012 Available = false; 5013 return false; 5014 } 5015 5016 bool follow(const SCEV *S) { 5017 switch (S->getSCEVType()) { 5018 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5019 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5020 // These expressions are available if their operand(s) is/are. 5021 return true; 5022 5023 case scAddRecExpr: { 5024 // We allow add recurrences that are on the loop BB is in, or some 5025 // outer loop. This guarantees availability because the value of the 5026 // add recurrence at BB is simply the "current" value of the induction 5027 // variable. We can relax this in the future; for instance an add 5028 // recurrence on a sibling dominating loop is also available at BB. 5029 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5030 if (L && (ARLoop == L || ARLoop->contains(L))) 5031 return true; 5032 5033 return setUnavailable(); 5034 } 5035 5036 case scUnknown: { 5037 // For SCEVUnknown, we check for simple dominance. 5038 const auto *SU = cast<SCEVUnknown>(S); 5039 Value *V = SU->getValue(); 5040 5041 if (isa<Argument>(V)) 5042 return false; 5043 5044 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5045 return false; 5046 5047 return setUnavailable(); 5048 } 5049 5050 case scUDivExpr: 5051 case scCouldNotCompute: 5052 // We do not try to smart about these at all. 5053 return setUnavailable(); 5054 } 5055 llvm_unreachable("switch should be fully covered!"); 5056 } 5057 5058 bool isDone() { return TraversalDone; } 5059 }; 5060 5061 CheckAvailable CA(L, BB, DT); 5062 SCEVTraversal<CheckAvailable> ST(CA); 5063 5064 ST.visitAll(S); 5065 return CA.Available; 5066 } 5067 5068 // Try to match a control flow sequence that branches out at BI and merges back 5069 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5070 // match. 5071 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5072 Value *&C, Value *&LHS, Value *&RHS) { 5073 C = BI->getCondition(); 5074 5075 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5076 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5077 5078 if (!LeftEdge.isSingleEdge()) 5079 return false; 5080 5081 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5082 5083 Use &LeftUse = Merge->getOperandUse(0); 5084 Use &RightUse = Merge->getOperandUse(1); 5085 5086 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5087 LHS = LeftUse; 5088 RHS = RightUse; 5089 return true; 5090 } 5091 5092 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5093 LHS = RightUse; 5094 RHS = LeftUse; 5095 return true; 5096 } 5097 5098 return false; 5099 } 5100 5101 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5102 auto IsReachable = 5103 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5104 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5105 const Loop *L = LI.getLoopFor(PN->getParent()); 5106 5107 // We don't want to break LCSSA, even in a SCEV expression tree. 5108 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5109 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5110 return nullptr; 5111 5112 // Try to match 5113 // 5114 // br %cond, label %left, label %right 5115 // left: 5116 // br label %merge 5117 // right: 5118 // br label %merge 5119 // merge: 5120 // V = phi [ %x, %left ], [ %y, %right ] 5121 // 5122 // as "select %cond, %x, %y" 5123 5124 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5125 assert(IDom && "At least the entry block should dominate PN"); 5126 5127 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5128 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5129 5130 if (BI && BI->isConditional() && 5131 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5132 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5133 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5134 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5135 } 5136 5137 return nullptr; 5138 } 5139 5140 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5141 if (const SCEV *S = createAddRecFromPHI(PN)) 5142 return S; 5143 5144 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5145 return S; 5146 5147 // If the PHI has a single incoming value, follow that value, unless the 5148 // PHI's incoming blocks are in a different loop, in which case doing so 5149 // risks breaking LCSSA form. Instcombine would normally zap these, but 5150 // it doesn't have DominatorTree information, so it may miss cases. 5151 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5152 if (LI.replacementPreservesLCSSAForm(PN, V)) 5153 return getSCEV(V); 5154 5155 // If it's not a loop phi, we can't handle it yet. 5156 return getUnknown(PN); 5157 } 5158 5159 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5160 Value *Cond, 5161 Value *TrueVal, 5162 Value *FalseVal) { 5163 // Handle "constant" branch or select. This can occur for instance when a 5164 // loop pass transforms an inner loop and moves on to process the outer loop. 5165 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5166 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5167 5168 // Try to match some simple smax or umax patterns. 5169 auto *ICI = dyn_cast<ICmpInst>(Cond); 5170 if (!ICI) 5171 return getUnknown(I); 5172 5173 Value *LHS = ICI->getOperand(0); 5174 Value *RHS = ICI->getOperand(1); 5175 5176 switch (ICI->getPredicate()) { 5177 case ICmpInst::ICMP_SLT: 5178 case ICmpInst::ICMP_SLE: 5179 std::swap(LHS, RHS); 5180 LLVM_FALLTHROUGH; 5181 case ICmpInst::ICMP_SGT: 5182 case ICmpInst::ICMP_SGE: 5183 // a >s b ? a+x : b+x -> smax(a, b)+x 5184 // a >s b ? b+x : a+x -> smin(a, b)+x 5185 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5186 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5187 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5188 const SCEV *LA = getSCEV(TrueVal); 5189 const SCEV *RA = getSCEV(FalseVal); 5190 const SCEV *LDiff = getMinusSCEV(LA, LS); 5191 const SCEV *RDiff = getMinusSCEV(RA, RS); 5192 if (LDiff == RDiff) 5193 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5194 LDiff = getMinusSCEV(LA, RS); 5195 RDiff = getMinusSCEV(RA, LS); 5196 if (LDiff == RDiff) 5197 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5198 } 5199 break; 5200 case ICmpInst::ICMP_ULT: 5201 case ICmpInst::ICMP_ULE: 5202 std::swap(LHS, RHS); 5203 LLVM_FALLTHROUGH; 5204 case ICmpInst::ICMP_UGT: 5205 case ICmpInst::ICMP_UGE: 5206 // a >u b ? a+x : b+x -> umax(a, b)+x 5207 // a >u b ? b+x : a+x -> umin(a, b)+x 5208 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5209 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5210 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5211 const SCEV *LA = getSCEV(TrueVal); 5212 const SCEV *RA = getSCEV(FalseVal); 5213 const SCEV *LDiff = getMinusSCEV(LA, LS); 5214 const SCEV *RDiff = getMinusSCEV(RA, RS); 5215 if (LDiff == RDiff) 5216 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5217 LDiff = getMinusSCEV(LA, RS); 5218 RDiff = getMinusSCEV(RA, LS); 5219 if (LDiff == RDiff) 5220 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5221 } 5222 break; 5223 case ICmpInst::ICMP_NE: 5224 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5225 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5226 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5227 const SCEV *One = getOne(I->getType()); 5228 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5229 const SCEV *LA = getSCEV(TrueVal); 5230 const SCEV *RA = getSCEV(FalseVal); 5231 const SCEV *LDiff = getMinusSCEV(LA, LS); 5232 const SCEV *RDiff = getMinusSCEV(RA, One); 5233 if (LDiff == RDiff) 5234 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5235 } 5236 break; 5237 case ICmpInst::ICMP_EQ: 5238 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5239 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5240 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5241 const SCEV *One = getOne(I->getType()); 5242 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5243 const SCEV *LA = getSCEV(TrueVal); 5244 const SCEV *RA = getSCEV(FalseVal); 5245 const SCEV *LDiff = getMinusSCEV(LA, One); 5246 const SCEV *RDiff = getMinusSCEV(RA, LS); 5247 if (LDiff == RDiff) 5248 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5249 } 5250 break; 5251 default: 5252 break; 5253 } 5254 5255 return getUnknown(I); 5256 } 5257 5258 /// Expand GEP instructions into add and multiply operations. This allows them 5259 /// to be analyzed by regular SCEV code. 5260 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5261 // Don't attempt to analyze GEPs over unsized objects. 5262 if (!GEP->getSourceElementType()->isSized()) 5263 return getUnknown(GEP); 5264 5265 SmallVector<const SCEV *, 4> IndexExprs; 5266 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5267 IndexExprs.push_back(getSCEV(*Index)); 5268 return getGEPExpr(GEP, IndexExprs); 5269 } 5270 5271 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5272 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5273 return C->getAPInt().countTrailingZeros(); 5274 5275 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5276 return std::min(GetMinTrailingZeros(T->getOperand()), 5277 (uint32_t)getTypeSizeInBits(T->getType())); 5278 5279 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5280 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5281 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5282 ? getTypeSizeInBits(E->getType()) 5283 : OpRes; 5284 } 5285 5286 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5287 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5288 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5289 ? getTypeSizeInBits(E->getType()) 5290 : OpRes; 5291 } 5292 5293 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5294 // The result is the min of all operands results. 5295 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5296 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5297 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5298 return MinOpRes; 5299 } 5300 5301 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5302 // The result is the sum of all operands results. 5303 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5304 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5305 for (unsigned i = 1, e = M->getNumOperands(); 5306 SumOpRes != BitWidth && i != e; ++i) 5307 SumOpRes = 5308 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5309 return SumOpRes; 5310 } 5311 5312 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5313 // The result is the min of all operands results. 5314 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5315 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5316 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5317 return MinOpRes; 5318 } 5319 5320 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5321 // The result is the min of all operands results. 5322 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5323 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5324 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5325 return MinOpRes; 5326 } 5327 5328 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5329 // The result is the min of all operands results. 5330 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5331 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5332 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5333 return MinOpRes; 5334 } 5335 5336 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5337 // For a SCEVUnknown, ask ValueTracking. 5338 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5339 return Known.countMinTrailingZeros(); 5340 } 5341 5342 // SCEVUDivExpr 5343 return 0; 5344 } 5345 5346 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5347 auto I = MinTrailingZerosCache.find(S); 5348 if (I != MinTrailingZerosCache.end()) 5349 return I->second; 5350 5351 uint32_t Result = GetMinTrailingZerosImpl(S); 5352 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5353 assert(InsertPair.second && "Should insert a new key"); 5354 return InsertPair.first->second; 5355 } 5356 5357 /// Helper method to assign a range to V from metadata present in the IR. 5358 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5359 if (Instruction *I = dyn_cast<Instruction>(V)) 5360 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5361 return getConstantRangeFromMetadata(*MD); 5362 5363 return None; 5364 } 5365 5366 /// Determine the range for a particular SCEV. If SignHint is 5367 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5368 /// with a "cleaner" unsigned (resp. signed) representation. 5369 const ConstantRange & 5370 ScalarEvolution::getRangeRef(const SCEV *S, 5371 ScalarEvolution::RangeSignHint SignHint) { 5372 DenseMap<const SCEV *, ConstantRange> &Cache = 5373 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5374 : SignedRanges; 5375 5376 // See if we've computed this range already. 5377 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5378 if (I != Cache.end()) 5379 return I->second; 5380 5381 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5382 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5383 5384 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5385 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5386 5387 // If the value has known zeros, the maximum value will have those known zeros 5388 // as well. 5389 uint32_t TZ = GetMinTrailingZeros(S); 5390 if (TZ != 0) { 5391 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5392 ConservativeResult = 5393 ConstantRange(APInt::getMinValue(BitWidth), 5394 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5395 else 5396 ConservativeResult = ConstantRange( 5397 APInt::getSignedMinValue(BitWidth), 5398 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5399 } 5400 5401 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5402 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5403 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5404 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5405 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 5406 } 5407 5408 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5409 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5410 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5411 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5412 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 5413 } 5414 5415 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5416 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5417 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5418 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5419 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 5420 } 5421 5422 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5423 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5424 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5425 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5426 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 5427 } 5428 5429 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5430 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5431 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5432 return setRange(UDiv, SignHint, 5433 ConservativeResult.intersectWith(X.udiv(Y))); 5434 } 5435 5436 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5437 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5438 return setRange(ZExt, SignHint, 5439 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 5440 } 5441 5442 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5443 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5444 return setRange(SExt, SignHint, 5445 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 5446 } 5447 5448 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5449 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5450 return setRange(Trunc, SignHint, 5451 ConservativeResult.intersectWith(X.truncate(BitWidth))); 5452 } 5453 5454 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5455 // If there's no unsigned wrap, the value will never be less than its 5456 // initial value. 5457 if (AddRec->hasNoUnsignedWrap()) 5458 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5459 if (!C->getValue()->isZero()) 5460 ConservativeResult = ConservativeResult.intersectWith( 5461 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 5462 5463 // If there's no signed wrap, and all the operands have the same sign or 5464 // zero, the value won't ever change sign. 5465 if (AddRec->hasNoSignedWrap()) { 5466 bool AllNonNeg = true; 5467 bool AllNonPos = true; 5468 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5469 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5470 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5471 } 5472 if (AllNonNeg) 5473 ConservativeResult = ConservativeResult.intersectWith( 5474 ConstantRange(APInt(BitWidth, 0), 5475 APInt::getSignedMinValue(BitWidth))); 5476 else if (AllNonPos) 5477 ConservativeResult = ConservativeResult.intersectWith( 5478 ConstantRange(APInt::getSignedMinValue(BitWidth), 5479 APInt(BitWidth, 1))); 5480 } 5481 5482 // TODO: non-affine addrec 5483 if (AddRec->isAffine()) { 5484 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 5485 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5486 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5487 auto RangeFromAffine = getRangeForAffineAR( 5488 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5489 BitWidth); 5490 if (!RangeFromAffine.isFullSet()) 5491 ConservativeResult = 5492 ConservativeResult.intersectWith(RangeFromAffine); 5493 5494 auto RangeFromFactoring = getRangeViaFactoring( 5495 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5496 BitWidth); 5497 if (!RangeFromFactoring.isFullSet()) 5498 ConservativeResult = 5499 ConservativeResult.intersectWith(RangeFromFactoring); 5500 } 5501 } 5502 5503 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5504 } 5505 5506 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5507 // Check if the IR explicitly contains !range metadata. 5508 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5509 if (MDRange.hasValue()) 5510 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 5511 5512 // Split here to avoid paying the compile-time cost of calling both 5513 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5514 // if needed. 5515 const DataLayout &DL = getDataLayout(); 5516 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5517 // For a SCEVUnknown, ask ValueTracking. 5518 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5519 if (Known.One != ~Known.Zero + 1) 5520 ConservativeResult = 5521 ConservativeResult.intersectWith(ConstantRange(Known.One, 5522 ~Known.Zero + 1)); 5523 } else { 5524 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5525 "generalize as needed!"); 5526 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5527 if (NS > 1) 5528 ConservativeResult = ConservativeResult.intersectWith( 5529 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5530 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 5531 } 5532 5533 // A range of Phi is a subset of union of all ranges of its input. 5534 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5535 // Make sure that we do not run over cycled Phis. 5536 if (PendingPhiRanges.insert(Phi).second) { 5537 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5538 for (auto &Op : Phi->operands()) { 5539 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5540 RangeFromOps = RangeFromOps.unionWith(OpRange); 5541 // No point to continue if we already have a full set. 5542 if (RangeFromOps.isFullSet()) 5543 break; 5544 } 5545 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps); 5546 bool Erased = PendingPhiRanges.erase(Phi); 5547 assert(Erased && "Failed to erase Phi properly?"); 5548 (void) Erased; 5549 } 5550 } 5551 5552 return setRange(U, SignHint, std::move(ConservativeResult)); 5553 } 5554 5555 return setRange(S, SignHint, std::move(ConservativeResult)); 5556 } 5557 5558 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5559 // values that the expression can take. Initially, the expression has a value 5560 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5561 // argument defines if we treat Step as signed or unsigned. 5562 static ConstantRange getRangeForAffineARHelper(APInt Step, 5563 const ConstantRange &StartRange, 5564 const APInt &MaxBECount, 5565 unsigned BitWidth, bool Signed) { 5566 // If either Step or MaxBECount is 0, then the expression won't change, and we 5567 // just need to return the initial range. 5568 if (Step == 0 || MaxBECount == 0) 5569 return StartRange; 5570 5571 // If we don't know anything about the initial value (i.e. StartRange is 5572 // FullRange), then we don't know anything about the final range either. 5573 // Return FullRange. 5574 if (StartRange.isFullSet()) 5575 return ConstantRange(BitWidth, /* isFullSet = */ true); 5576 5577 // If Step is signed and negative, then we use its absolute value, but we also 5578 // note that we're moving in the opposite direction. 5579 bool Descending = Signed && Step.isNegative(); 5580 5581 if (Signed) 5582 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5583 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5584 // This equations hold true due to the well-defined wrap-around behavior of 5585 // APInt. 5586 Step = Step.abs(); 5587 5588 // Check if Offset is more than full span of BitWidth. If it is, the 5589 // expression is guaranteed to overflow. 5590 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5591 return ConstantRange(BitWidth, /* isFullSet = */ true); 5592 5593 // Offset is by how much the expression can change. Checks above guarantee no 5594 // overflow here. 5595 APInt Offset = Step * MaxBECount; 5596 5597 // Minimum value of the final range will match the minimal value of StartRange 5598 // if the expression is increasing and will be decreased by Offset otherwise. 5599 // Maximum value of the final range will match the maximal value of StartRange 5600 // if the expression is decreasing and will be increased by Offset otherwise. 5601 APInt StartLower = StartRange.getLower(); 5602 APInt StartUpper = StartRange.getUpper() - 1; 5603 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5604 : (StartUpper + std::move(Offset)); 5605 5606 // It's possible that the new minimum/maximum value will fall into the initial 5607 // range (due to wrap around). This means that the expression can take any 5608 // value in this bitwidth, and we have to return full range. 5609 if (StartRange.contains(MovedBoundary)) 5610 return ConstantRange(BitWidth, /* isFullSet = */ true); 5611 5612 APInt NewLower = 5613 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5614 APInt NewUpper = 5615 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5616 NewUpper += 1; 5617 5618 // If we end up with full range, return a proper full range. 5619 if (NewLower == NewUpper) 5620 return ConstantRange(BitWidth, /* isFullSet = */ true); 5621 5622 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5623 return ConstantRange(std::move(NewLower), std::move(NewUpper)); 5624 } 5625 5626 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5627 const SCEV *Step, 5628 const SCEV *MaxBECount, 5629 unsigned BitWidth) { 5630 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5631 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5632 "Precondition!"); 5633 5634 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5635 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5636 5637 // First, consider step signed. 5638 ConstantRange StartSRange = getSignedRange(Start); 5639 ConstantRange StepSRange = getSignedRange(Step); 5640 5641 // If Step can be both positive and negative, we need to find ranges for the 5642 // maximum absolute step values in both directions and union them. 5643 ConstantRange SR = 5644 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5645 MaxBECountValue, BitWidth, /* Signed = */ true); 5646 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5647 StartSRange, MaxBECountValue, 5648 BitWidth, /* Signed = */ true)); 5649 5650 // Next, consider step unsigned. 5651 ConstantRange UR = getRangeForAffineARHelper( 5652 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5653 MaxBECountValue, BitWidth, /* Signed = */ false); 5654 5655 // Finally, intersect signed and unsigned ranges. 5656 return SR.intersectWith(UR); 5657 } 5658 5659 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5660 const SCEV *Step, 5661 const SCEV *MaxBECount, 5662 unsigned BitWidth) { 5663 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5664 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5665 5666 struct SelectPattern { 5667 Value *Condition = nullptr; 5668 APInt TrueValue; 5669 APInt FalseValue; 5670 5671 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5672 const SCEV *S) { 5673 Optional<unsigned> CastOp; 5674 APInt Offset(BitWidth, 0); 5675 5676 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5677 "Should be!"); 5678 5679 // Peel off a constant offset: 5680 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5681 // In the future we could consider being smarter here and handle 5682 // {Start+Step,+,Step} too. 5683 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5684 return; 5685 5686 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5687 S = SA->getOperand(1); 5688 } 5689 5690 // Peel off a cast operation 5691 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5692 CastOp = SCast->getSCEVType(); 5693 S = SCast->getOperand(); 5694 } 5695 5696 using namespace llvm::PatternMatch; 5697 5698 auto *SU = dyn_cast<SCEVUnknown>(S); 5699 const APInt *TrueVal, *FalseVal; 5700 if (!SU || 5701 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5702 m_APInt(FalseVal)))) { 5703 Condition = nullptr; 5704 return; 5705 } 5706 5707 TrueValue = *TrueVal; 5708 FalseValue = *FalseVal; 5709 5710 // Re-apply the cast we peeled off earlier 5711 if (CastOp.hasValue()) 5712 switch (*CastOp) { 5713 default: 5714 llvm_unreachable("Unknown SCEV cast type!"); 5715 5716 case scTruncate: 5717 TrueValue = TrueValue.trunc(BitWidth); 5718 FalseValue = FalseValue.trunc(BitWidth); 5719 break; 5720 case scZeroExtend: 5721 TrueValue = TrueValue.zext(BitWidth); 5722 FalseValue = FalseValue.zext(BitWidth); 5723 break; 5724 case scSignExtend: 5725 TrueValue = TrueValue.sext(BitWidth); 5726 FalseValue = FalseValue.sext(BitWidth); 5727 break; 5728 } 5729 5730 // Re-apply the constant offset we peeled off earlier 5731 TrueValue += Offset; 5732 FalseValue += Offset; 5733 } 5734 5735 bool isRecognized() { return Condition != nullptr; } 5736 }; 5737 5738 SelectPattern StartPattern(*this, BitWidth, Start); 5739 if (!StartPattern.isRecognized()) 5740 return ConstantRange(BitWidth, /* isFullSet = */ true); 5741 5742 SelectPattern StepPattern(*this, BitWidth, Step); 5743 if (!StepPattern.isRecognized()) 5744 return ConstantRange(BitWidth, /* isFullSet = */ true); 5745 5746 if (StartPattern.Condition != StepPattern.Condition) { 5747 // We don't handle this case today; but we could, by considering four 5748 // possibilities below instead of two. I'm not sure if there are cases where 5749 // that will help over what getRange already does, though. 5750 return ConstantRange(BitWidth, /* isFullSet = */ true); 5751 } 5752 5753 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5754 // construct arbitrary general SCEV expressions here. This function is called 5755 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5756 // say) can end up caching a suboptimal value. 5757 5758 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5759 // C2352 and C2512 (otherwise it isn't needed). 5760 5761 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5762 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5763 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5764 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5765 5766 ConstantRange TrueRange = 5767 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5768 ConstantRange FalseRange = 5769 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5770 5771 return TrueRange.unionWith(FalseRange); 5772 } 5773 5774 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5775 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5776 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5777 5778 // Return early if there are no flags to propagate to the SCEV. 5779 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5780 if (BinOp->hasNoUnsignedWrap()) 5781 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5782 if (BinOp->hasNoSignedWrap()) 5783 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5784 if (Flags == SCEV::FlagAnyWrap) 5785 return SCEV::FlagAnyWrap; 5786 5787 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5788 } 5789 5790 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5791 // Here we check that I is in the header of the innermost loop containing I, 5792 // since we only deal with instructions in the loop header. The actual loop we 5793 // need to check later will come from an add recurrence, but getting that 5794 // requires computing the SCEV of the operands, which can be expensive. This 5795 // check we can do cheaply to rule out some cases early. 5796 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5797 if (InnermostContainingLoop == nullptr || 5798 InnermostContainingLoop->getHeader() != I->getParent()) 5799 return false; 5800 5801 // Only proceed if we can prove that I does not yield poison. 5802 if (!programUndefinedIfFullPoison(I)) 5803 return false; 5804 5805 // At this point we know that if I is executed, then it does not wrap 5806 // according to at least one of NSW or NUW. If I is not executed, then we do 5807 // not know if the calculation that I represents would wrap. Multiple 5808 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5809 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5810 // derived from other instructions that map to the same SCEV. We cannot make 5811 // that guarantee for cases where I is not executed. So we need to find the 5812 // loop that I is considered in relation to and prove that I is executed for 5813 // every iteration of that loop. That implies that the value that I 5814 // calculates does not wrap anywhere in the loop, so then we can apply the 5815 // flags to the SCEV. 5816 // 5817 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5818 // from different loops, so that we know which loop to prove that I is 5819 // executed in. 5820 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5821 // I could be an extractvalue from a call to an overflow intrinsic. 5822 // TODO: We can do better here in some cases. 5823 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5824 return false; 5825 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5826 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5827 bool AllOtherOpsLoopInvariant = true; 5828 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5829 ++OtherOpIndex) { 5830 if (OtherOpIndex != OpIndex) { 5831 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5832 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5833 AllOtherOpsLoopInvariant = false; 5834 break; 5835 } 5836 } 5837 } 5838 if (AllOtherOpsLoopInvariant && 5839 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5840 return true; 5841 } 5842 } 5843 return false; 5844 } 5845 5846 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5847 // If we know that \c I can never be poison period, then that's enough. 5848 if (isSCEVExprNeverPoison(I)) 5849 return true; 5850 5851 // For an add recurrence specifically, we assume that infinite loops without 5852 // side effects are undefined behavior, and then reason as follows: 5853 // 5854 // If the add recurrence is poison in any iteration, it is poison on all 5855 // future iterations (since incrementing poison yields poison). If the result 5856 // of the add recurrence is fed into the loop latch condition and the loop 5857 // does not contain any throws or exiting blocks other than the latch, we now 5858 // have the ability to "choose" whether the backedge is taken or not (by 5859 // choosing a sufficiently evil value for the poison feeding into the branch) 5860 // for every iteration including and after the one in which \p I first became 5861 // poison. There are two possibilities (let's call the iteration in which \p 5862 // I first became poison as K): 5863 // 5864 // 1. In the set of iterations including and after K, the loop body executes 5865 // no side effects. In this case executing the backege an infinte number 5866 // of times will yield undefined behavior. 5867 // 5868 // 2. In the set of iterations including and after K, the loop body executes 5869 // at least one side effect. In this case, that specific instance of side 5870 // effect is control dependent on poison, which also yields undefined 5871 // behavior. 5872 5873 auto *ExitingBB = L->getExitingBlock(); 5874 auto *LatchBB = L->getLoopLatch(); 5875 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5876 return false; 5877 5878 SmallPtrSet<const Instruction *, 16> Pushed; 5879 SmallVector<const Instruction *, 8> PoisonStack; 5880 5881 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5882 // things that are known to be fully poison under that assumption go on the 5883 // PoisonStack. 5884 Pushed.insert(I); 5885 PoisonStack.push_back(I); 5886 5887 bool LatchControlDependentOnPoison = false; 5888 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5889 const Instruction *Poison = PoisonStack.pop_back_val(); 5890 5891 for (auto *PoisonUser : Poison->users()) { 5892 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 5893 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5894 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5895 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5896 assert(BI->isConditional() && "Only possibility!"); 5897 if (BI->getParent() == LatchBB) { 5898 LatchControlDependentOnPoison = true; 5899 break; 5900 } 5901 } 5902 } 5903 } 5904 5905 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5906 } 5907 5908 ScalarEvolution::LoopProperties 5909 ScalarEvolution::getLoopProperties(const Loop *L) { 5910 using LoopProperties = ScalarEvolution::LoopProperties; 5911 5912 auto Itr = LoopPropertiesCache.find(L); 5913 if (Itr == LoopPropertiesCache.end()) { 5914 auto HasSideEffects = [](Instruction *I) { 5915 if (auto *SI = dyn_cast<StoreInst>(I)) 5916 return !SI->isSimple(); 5917 5918 return I->mayHaveSideEffects(); 5919 }; 5920 5921 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5922 /*HasNoSideEffects*/ true}; 5923 5924 for (auto *BB : L->getBlocks()) 5925 for (auto &I : *BB) { 5926 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5927 LP.HasNoAbnormalExits = false; 5928 if (HasSideEffects(&I)) 5929 LP.HasNoSideEffects = false; 5930 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5931 break; // We're already as pessimistic as we can get. 5932 } 5933 5934 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5935 assert(InsertPair.second && "We just checked!"); 5936 Itr = InsertPair.first; 5937 } 5938 5939 return Itr->second; 5940 } 5941 5942 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5943 if (!isSCEVable(V->getType())) 5944 return getUnknown(V); 5945 5946 if (Instruction *I = dyn_cast<Instruction>(V)) { 5947 // Don't attempt to analyze instructions in blocks that aren't 5948 // reachable. Such instructions don't matter, and they aren't required 5949 // to obey basic rules for definitions dominating uses which this 5950 // analysis depends on. 5951 if (!DT.isReachableFromEntry(I->getParent())) 5952 return getUnknown(V); 5953 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5954 return getConstant(CI); 5955 else if (isa<ConstantPointerNull>(V)) 5956 return getZero(V->getType()); 5957 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5958 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5959 else if (!isa<ConstantExpr>(V)) 5960 return getUnknown(V); 5961 5962 Operator *U = cast<Operator>(V); 5963 if (auto BO = MatchBinaryOp(U, DT)) { 5964 switch (BO->Opcode) { 5965 case Instruction::Add: { 5966 // The simple thing to do would be to just call getSCEV on both operands 5967 // and call getAddExpr with the result. However if we're looking at a 5968 // bunch of things all added together, this can be quite inefficient, 5969 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5970 // Instead, gather up all the operands and make a single getAddExpr call. 5971 // LLVM IR canonical form means we need only traverse the left operands. 5972 SmallVector<const SCEV *, 4> AddOps; 5973 do { 5974 if (BO->Op) { 5975 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5976 AddOps.push_back(OpSCEV); 5977 break; 5978 } 5979 5980 // If a NUW or NSW flag can be applied to the SCEV for this 5981 // addition, then compute the SCEV for this addition by itself 5982 // with a separate call to getAddExpr. We need to do that 5983 // instead of pushing the operands of the addition onto AddOps, 5984 // since the flags are only known to apply to this particular 5985 // addition - they may not apply to other additions that can be 5986 // formed with operands from AddOps. 5987 const SCEV *RHS = getSCEV(BO->RHS); 5988 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5989 if (Flags != SCEV::FlagAnyWrap) { 5990 const SCEV *LHS = getSCEV(BO->LHS); 5991 if (BO->Opcode == Instruction::Sub) 5992 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5993 else 5994 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5995 break; 5996 } 5997 } 5998 5999 if (BO->Opcode == Instruction::Sub) 6000 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6001 else 6002 AddOps.push_back(getSCEV(BO->RHS)); 6003 6004 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6005 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6006 NewBO->Opcode != Instruction::Sub)) { 6007 AddOps.push_back(getSCEV(BO->LHS)); 6008 break; 6009 } 6010 BO = NewBO; 6011 } while (true); 6012 6013 return getAddExpr(AddOps); 6014 } 6015 6016 case Instruction::Mul: { 6017 SmallVector<const SCEV *, 4> MulOps; 6018 do { 6019 if (BO->Op) { 6020 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6021 MulOps.push_back(OpSCEV); 6022 break; 6023 } 6024 6025 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6026 if (Flags != SCEV::FlagAnyWrap) { 6027 MulOps.push_back( 6028 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6029 break; 6030 } 6031 } 6032 6033 MulOps.push_back(getSCEV(BO->RHS)); 6034 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6035 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6036 MulOps.push_back(getSCEV(BO->LHS)); 6037 break; 6038 } 6039 BO = NewBO; 6040 } while (true); 6041 6042 return getMulExpr(MulOps); 6043 } 6044 case Instruction::UDiv: 6045 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6046 case Instruction::URem: 6047 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6048 case Instruction::Sub: { 6049 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6050 if (BO->Op) 6051 Flags = getNoWrapFlagsFromUB(BO->Op); 6052 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6053 } 6054 case Instruction::And: 6055 // For an expression like x&255 that merely masks off the high bits, 6056 // use zext(trunc(x)) as the SCEV expression. 6057 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6058 if (CI->isZero()) 6059 return getSCEV(BO->RHS); 6060 if (CI->isMinusOne()) 6061 return getSCEV(BO->LHS); 6062 const APInt &A = CI->getValue(); 6063 6064 // Instcombine's ShrinkDemandedConstant may strip bits out of 6065 // constants, obscuring what would otherwise be a low-bits mask. 6066 // Use computeKnownBits to compute what ShrinkDemandedConstant 6067 // knew about to reconstruct a low-bits mask value. 6068 unsigned LZ = A.countLeadingZeros(); 6069 unsigned TZ = A.countTrailingZeros(); 6070 unsigned BitWidth = A.getBitWidth(); 6071 KnownBits Known(BitWidth); 6072 computeKnownBits(BO->LHS, Known, getDataLayout(), 6073 0, &AC, nullptr, &DT); 6074 6075 APInt EffectiveMask = 6076 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6077 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6078 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6079 const SCEV *LHS = getSCEV(BO->LHS); 6080 const SCEV *ShiftedLHS = nullptr; 6081 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6082 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6083 // For an expression like (x * 8) & 8, simplify the multiply. 6084 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6085 unsigned GCD = std::min(MulZeros, TZ); 6086 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6087 SmallVector<const SCEV*, 4> MulOps; 6088 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6089 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6090 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6091 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6092 } 6093 } 6094 if (!ShiftedLHS) 6095 ShiftedLHS = getUDivExpr(LHS, MulCount); 6096 return getMulExpr( 6097 getZeroExtendExpr( 6098 getTruncateExpr(ShiftedLHS, 6099 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6100 BO->LHS->getType()), 6101 MulCount); 6102 } 6103 } 6104 break; 6105 6106 case Instruction::Or: 6107 // If the RHS of the Or is a constant, we may have something like: 6108 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6109 // optimizations will transparently handle this case. 6110 // 6111 // In order for this transformation to be safe, the LHS must be of the 6112 // form X*(2^n) and the Or constant must be less than 2^n. 6113 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6114 const SCEV *LHS = getSCEV(BO->LHS); 6115 const APInt &CIVal = CI->getValue(); 6116 if (GetMinTrailingZeros(LHS) >= 6117 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6118 // Build a plain add SCEV. 6119 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6120 // If the LHS of the add was an addrec and it has no-wrap flags, 6121 // transfer the no-wrap flags, since an or won't introduce a wrap. 6122 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6123 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6124 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6125 OldAR->getNoWrapFlags()); 6126 } 6127 return S; 6128 } 6129 } 6130 break; 6131 6132 case Instruction::Xor: 6133 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6134 // If the RHS of xor is -1, then this is a not operation. 6135 if (CI->isMinusOne()) 6136 return getNotSCEV(getSCEV(BO->LHS)); 6137 6138 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6139 // This is a variant of the check for xor with -1, and it handles 6140 // the case where instcombine has trimmed non-demanded bits out 6141 // of an xor with -1. 6142 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6143 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6144 if (LBO->getOpcode() == Instruction::And && 6145 LCI->getValue() == CI->getValue()) 6146 if (const SCEVZeroExtendExpr *Z = 6147 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6148 Type *UTy = BO->LHS->getType(); 6149 const SCEV *Z0 = Z->getOperand(); 6150 Type *Z0Ty = Z0->getType(); 6151 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6152 6153 // If C is a low-bits mask, the zero extend is serving to 6154 // mask off the high bits. Complement the operand and 6155 // re-apply the zext. 6156 if (CI->getValue().isMask(Z0TySize)) 6157 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6158 6159 // If C is a single bit, it may be in the sign-bit position 6160 // before the zero-extend. In this case, represent the xor 6161 // using an add, which is equivalent, and re-apply the zext. 6162 APInt Trunc = CI->getValue().trunc(Z0TySize); 6163 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6164 Trunc.isSignMask()) 6165 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6166 UTy); 6167 } 6168 } 6169 break; 6170 6171 case Instruction::Shl: 6172 // Turn shift left of a constant amount into a multiply. 6173 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6174 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6175 6176 // If the shift count is not less than the bitwidth, the result of 6177 // the shift is undefined. Don't try to analyze it, because the 6178 // resolution chosen here may differ from the resolution chosen in 6179 // other parts of the compiler. 6180 if (SA->getValue().uge(BitWidth)) 6181 break; 6182 6183 // It is currently not resolved how to interpret NSW for left 6184 // shift by BitWidth - 1, so we avoid applying flags in that 6185 // case. Remove this check (or this comment) once the situation 6186 // is resolved. See 6187 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6188 // and http://reviews.llvm.org/D8890 . 6189 auto Flags = SCEV::FlagAnyWrap; 6190 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6191 Flags = getNoWrapFlagsFromUB(BO->Op); 6192 6193 Constant *X = ConstantInt::get(getContext(), 6194 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6195 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6196 } 6197 break; 6198 6199 case Instruction::AShr: { 6200 // AShr X, C, where C is a constant. 6201 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6202 if (!CI) 6203 break; 6204 6205 Type *OuterTy = BO->LHS->getType(); 6206 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6207 // If the shift count is not less than the bitwidth, the result of 6208 // the shift is undefined. Don't try to analyze it, because the 6209 // resolution chosen here may differ from the resolution chosen in 6210 // other parts of the compiler. 6211 if (CI->getValue().uge(BitWidth)) 6212 break; 6213 6214 if (CI->isZero()) 6215 return getSCEV(BO->LHS); // shift by zero --> noop 6216 6217 uint64_t AShrAmt = CI->getZExtValue(); 6218 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6219 6220 Operator *L = dyn_cast<Operator>(BO->LHS); 6221 if (L && L->getOpcode() == Instruction::Shl) { 6222 // X = Shl A, n 6223 // Y = AShr X, m 6224 // Both n and m are constant. 6225 6226 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6227 if (L->getOperand(1) == BO->RHS) 6228 // For a two-shift sext-inreg, i.e. n = m, 6229 // use sext(trunc(x)) as the SCEV expression. 6230 return getSignExtendExpr( 6231 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6232 6233 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6234 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6235 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6236 if (ShlAmt > AShrAmt) { 6237 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6238 // expression. We already checked that ShlAmt < BitWidth, so 6239 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6240 // ShlAmt - AShrAmt < Amt. 6241 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6242 ShlAmt - AShrAmt); 6243 return getSignExtendExpr( 6244 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6245 getConstant(Mul)), OuterTy); 6246 } 6247 } 6248 } 6249 break; 6250 } 6251 } 6252 } 6253 6254 switch (U->getOpcode()) { 6255 case Instruction::Trunc: 6256 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6257 6258 case Instruction::ZExt: 6259 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6260 6261 case Instruction::SExt: 6262 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6263 // The NSW flag of a subtract does not always survive the conversion to 6264 // A + (-1)*B. By pushing sign extension onto its operands we are much 6265 // more likely to preserve NSW and allow later AddRec optimisations. 6266 // 6267 // NOTE: This is effectively duplicating this logic from getSignExtend: 6268 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6269 // but by that point the NSW information has potentially been lost. 6270 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6271 Type *Ty = U->getType(); 6272 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6273 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6274 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6275 } 6276 } 6277 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6278 6279 case Instruction::BitCast: 6280 // BitCasts are no-op casts so we just eliminate the cast. 6281 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6282 return getSCEV(U->getOperand(0)); 6283 break; 6284 6285 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6286 // lead to pointer expressions which cannot safely be expanded to GEPs, 6287 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6288 // simplifying integer expressions. 6289 6290 case Instruction::GetElementPtr: 6291 return createNodeForGEP(cast<GEPOperator>(U)); 6292 6293 case Instruction::PHI: 6294 return createNodeForPHI(cast<PHINode>(U)); 6295 6296 case Instruction::Select: 6297 // U can also be a select constant expr, which let fall through. Since 6298 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6299 // constant expressions cannot have instructions as operands, we'd have 6300 // returned getUnknown for a select constant expressions anyway. 6301 if (isa<Instruction>(U)) 6302 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6303 U->getOperand(1), U->getOperand(2)); 6304 break; 6305 6306 case Instruction::Call: 6307 case Instruction::Invoke: 6308 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6309 return getSCEV(RV); 6310 break; 6311 } 6312 6313 return getUnknown(V); 6314 } 6315 6316 //===----------------------------------------------------------------------===// 6317 // Iteration Count Computation Code 6318 // 6319 6320 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6321 if (!ExitCount) 6322 return 0; 6323 6324 ConstantInt *ExitConst = ExitCount->getValue(); 6325 6326 // Guard against huge trip counts. 6327 if (ExitConst->getValue().getActiveBits() > 32) 6328 return 0; 6329 6330 // In case of integer overflow, this returns 0, which is correct. 6331 return ((unsigned)ExitConst->getZExtValue()) + 1; 6332 } 6333 6334 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6335 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6336 return getSmallConstantTripCount(L, ExitingBB); 6337 6338 // No trip count information for multiple exits. 6339 return 0; 6340 } 6341 6342 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6343 BasicBlock *ExitingBlock) { 6344 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6345 assert(L->isLoopExiting(ExitingBlock) && 6346 "Exiting block must actually branch out of the loop!"); 6347 const SCEVConstant *ExitCount = 6348 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6349 return getConstantTripCount(ExitCount); 6350 } 6351 6352 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6353 const auto *MaxExitCount = 6354 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 6355 return getConstantTripCount(MaxExitCount); 6356 } 6357 6358 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6359 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6360 return getSmallConstantTripMultiple(L, ExitingBB); 6361 6362 // No trip multiple information for multiple exits. 6363 return 0; 6364 } 6365 6366 /// Returns the largest constant divisor of the trip count of this loop as a 6367 /// normal unsigned value, if possible. This means that the actual trip count is 6368 /// always a multiple of the returned value (don't forget the trip count could 6369 /// very well be zero as well!). 6370 /// 6371 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6372 /// multiple of a constant (which is also the case if the trip count is simply 6373 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6374 /// if the trip count is very large (>= 2^32). 6375 /// 6376 /// As explained in the comments for getSmallConstantTripCount, this assumes 6377 /// that control exits the loop via ExitingBlock. 6378 unsigned 6379 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6380 BasicBlock *ExitingBlock) { 6381 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6382 assert(L->isLoopExiting(ExitingBlock) && 6383 "Exiting block must actually branch out of the loop!"); 6384 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6385 if (ExitCount == getCouldNotCompute()) 6386 return 1; 6387 6388 // Get the trip count from the BE count by adding 1. 6389 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6390 6391 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6392 if (!TC) 6393 // Attempt to factor more general cases. Returns the greatest power of 6394 // two divisor. If overflow happens, the trip count expression is still 6395 // divisible by the greatest power of 2 divisor returned. 6396 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6397 6398 ConstantInt *Result = TC->getValue(); 6399 6400 // Guard against huge trip counts (this requires checking 6401 // for zero to handle the case where the trip count == -1 and the 6402 // addition wraps). 6403 if (!Result || Result->getValue().getActiveBits() > 32 || 6404 Result->getValue().getActiveBits() == 0) 6405 return 1; 6406 6407 return (unsigned)Result->getZExtValue(); 6408 } 6409 6410 /// Get the expression for the number of loop iterations for which this loop is 6411 /// guaranteed not to exit via ExitingBlock. Otherwise return 6412 /// SCEVCouldNotCompute. 6413 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6414 BasicBlock *ExitingBlock) { 6415 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6416 } 6417 6418 const SCEV * 6419 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6420 SCEVUnionPredicate &Preds) { 6421 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 6422 } 6423 6424 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 6425 return getBackedgeTakenInfo(L).getExact(this); 6426 } 6427 6428 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 6429 /// known never to be less than the actual backedge taken count. 6430 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 6431 return getBackedgeTakenInfo(L).getMax(this); 6432 } 6433 6434 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6435 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6436 } 6437 6438 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6439 static void 6440 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6441 BasicBlock *Header = L->getHeader(); 6442 6443 // Push all Loop-header PHIs onto the Worklist stack. 6444 for (PHINode &PN : Header->phis()) 6445 Worklist.push_back(&PN); 6446 } 6447 6448 const ScalarEvolution::BackedgeTakenInfo & 6449 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6450 auto &BTI = getBackedgeTakenInfo(L); 6451 if (BTI.hasFullInfo()) 6452 return BTI; 6453 6454 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6455 6456 if (!Pair.second) 6457 return Pair.first->second; 6458 6459 BackedgeTakenInfo Result = 6460 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6461 6462 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6463 } 6464 6465 const ScalarEvolution::BackedgeTakenInfo & 6466 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6467 // Initially insert an invalid entry for this loop. If the insertion 6468 // succeeds, proceed to actually compute a backedge-taken count and 6469 // update the value. The temporary CouldNotCompute value tells SCEV 6470 // code elsewhere that it shouldn't attempt to request a new 6471 // backedge-taken count, which could result in infinite recursion. 6472 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6473 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6474 if (!Pair.second) 6475 return Pair.first->second; 6476 6477 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6478 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6479 // must be cleared in this scope. 6480 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6481 6482 if (Result.getExact(this) != getCouldNotCompute()) { 6483 assert(isLoopInvariant(Result.getExact(this), L) && 6484 isLoopInvariant(Result.getMax(this), L) && 6485 "Computed backedge-taken count isn't loop invariant for loop!"); 6486 ++NumTripCountsComputed; 6487 } 6488 else if (Result.getMax(this) == getCouldNotCompute() && 6489 isa<PHINode>(L->getHeader()->begin())) { 6490 // Only count loops that have phi nodes as not being computable. 6491 ++NumTripCountsNotComputed; 6492 } 6493 6494 // Now that we know more about the trip count for this loop, forget any 6495 // existing SCEV values for PHI nodes in this loop since they are only 6496 // conservative estimates made without the benefit of trip count 6497 // information. This is similar to the code in forgetLoop, except that 6498 // it handles SCEVUnknown PHI nodes specially. 6499 if (Result.hasAnyInfo()) { 6500 SmallVector<Instruction *, 16> Worklist; 6501 PushLoopPHIs(L, Worklist); 6502 6503 SmallPtrSet<Instruction *, 8> Discovered; 6504 while (!Worklist.empty()) { 6505 Instruction *I = Worklist.pop_back_val(); 6506 6507 ValueExprMapType::iterator It = 6508 ValueExprMap.find_as(static_cast<Value *>(I)); 6509 if (It != ValueExprMap.end()) { 6510 const SCEV *Old = It->second; 6511 6512 // SCEVUnknown for a PHI either means that it has an unrecognized 6513 // structure, or it's a PHI that's in the progress of being computed 6514 // by createNodeForPHI. In the former case, additional loop trip 6515 // count information isn't going to change anything. In the later 6516 // case, createNodeForPHI will perform the necessary updates on its 6517 // own when it gets to that point. 6518 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6519 eraseValueFromMap(It->first); 6520 forgetMemoizedResults(Old); 6521 } 6522 if (PHINode *PN = dyn_cast<PHINode>(I)) 6523 ConstantEvolutionLoopExitValue.erase(PN); 6524 } 6525 6526 // Since we don't need to invalidate anything for correctness and we're 6527 // only invalidating to make SCEV's results more precise, we get to stop 6528 // early to avoid invalidating too much. This is especially important in 6529 // cases like: 6530 // 6531 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6532 // loop0: 6533 // %pn0 = phi 6534 // ... 6535 // loop1: 6536 // %pn1 = phi 6537 // ... 6538 // 6539 // where both loop0 and loop1's backedge taken count uses the SCEV 6540 // expression for %v. If we don't have the early stop below then in cases 6541 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6542 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6543 // count for loop1, effectively nullifying SCEV's trip count cache. 6544 for (auto *U : I->users()) 6545 if (auto *I = dyn_cast<Instruction>(U)) { 6546 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6547 if (LoopForUser && L->contains(LoopForUser) && 6548 Discovered.insert(I).second) 6549 Worklist.push_back(I); 6550 } 6551 } 6552 } 6553 6554 // Re-lookup the insert position, since the call to 6555 // computeBackedgeTakenCount above could result in a 6556 // recusive call to getBackedgeTakenInfo (on a different 6557 // loop), which would invalidate the iterator computed 6558 // earlier. 6559 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6560 } 6561 6562 void ScalarEvolution::forgetLoop(const Loop *L) { 6563 // Drop any stored trip count value. 6564 auto RemoveLoopFromBackedgeMap = 6565 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6566 auto BTCPos = Map.find(L); 6567 if (BTCPos != Map.end()) { 6568 BTCPos->second.clear(); 6569 Map.erase(BTCPos); 6570 } 6571 }; 6572 6573 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6574 SmallVector<Instruction *, 32> Worklist; 6575 SmallPtrSet<Instruction *, 16> Visited; 6576 6577 // Iterate over all the loops and sub-loops to drop SCEV information. 6578 while (!LoopWorklist.empty()) { 6579 auto *CurrL = LoopWorklist.pop_back_val(); 6580 6581 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6582 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6583 6584 // Drop information about predicated SCEV rewrites for this loop. 6585 for (auto I = PredicatedSCEVRewrites.begin(); 6586 I != PredicatedSCEVRewrites.end();) { 6587 std::pair<const SCEV *, const Loop *> Entry = I->first; 6588 if (Entry.second == CurrL) 6589 PredicatedSCEVRewrites.erase(I++); 6590 else 6591 ++I; 6592 } 6593 6594 auto LoopUsersItr = LoopUsers.find(CurrL); 6595 if (LoopUsersItr != LoopUsers.end()) { 6596 for (auto *S : LoopUsersItr->second) 6597 forgetMemoizedResults(S); 6598 LoopUsers.erase(LoopUsersItr); 6599 } 6600 6601 // Drop information about expressions based on loop-header PHIs. 6602 PushLoopPHIs(CurrL, Worklist); 6603 6604 while (!Worklist.empty()) { 6605 Instruction *I = Worklist.pop_back_val(); 6606 if (!Visited.insert(I).second) 6607 continue; 6608 6609 ValueExprMapType::iterator It = 6610 ValueExprMap.find_as(static_cast<Value *>(I)); 6611 if (It != ValueExprMap.end()) { 6612 eraseValueFromMap(It->first); 6613 forgetMemoizedResults(It->second); 6614 if (PHINode *PN = dyn_cast<PHINode>(I)) 6615 ConstantEvolutionLoopExitValue.erase(PN); 6616 } 6617 6618 PushDefUseChildren(I, Worklist); 6619 } 6620 6621 LoopPropertiesCache.erase(CurrL); 6622 // Forget all contained loops too, to avoid dangling entries in the 6623 // ValuesAtScopes map. 6624 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6625 } 6626 } 6627 6628 void ScalarEvolution::forgetValue(Value *V) { 6629 Instruction *I = dyn_cast<Instruction>(V); 6630 if (!I) return; 6631 6632 // Drop information about expressions based on loop-header PHIs. 6633 SmallVector<Instruction *, 16> Worklist; 6634 Worklist.push_back(I); 6635 6636 SmallPtrSet<Instruction *, 8> Visited; 6637 while (!Worklist.empty()) { 6638 I = Worklist.pop_back_val(); 6639 if (!Visited.insert(I).second) 6640 continue; 6641 6642 ValueExprMapType::iterator It = 6643 ValueExprMap.find_as(static_cast<Value *>(I)); 6644 if (It != ValueExprMap.end()) { 6645 eraseValueFromMap(It->first); 6646 forgetMemoizedResults(It->second); 6647 if (PHINode *PN = dyn_cast<PHINode>(I)) 6648 ConstantEvolutionLoopExitValue.erase(PN); 6649 } 6650 6651 PushDefUseChildren(I, Worklist); 6652 } 6653 } 6654 6655 /// Get the exact loop backedge taken count considering all loop exits. A 6656 /// computable result can only be returned for loops with a single exit. 6657 /// Returning the minimum taken count among all exits is incorrect because one 6658 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 6659 /// the limit of each loop test is never skipped. This is a valid assumption as 6660 /// long as the loop exits via that test. For precise results, it is the 6661 /// caller's responsibility to specify the relevant loop exit using 6662 /// getExact(ExitingBlock, SE). 6663 const SCEV * 6664 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 6665 SCEVUnionPredicate *Preds) const { 6666 // If any exits were not computable, the loop is not computable. 6667 if (!isComplete() || ExitNotTaken.empty()) 6668 return SE->getCouldNotCompute(); 6669 6670 const SCEV *BECount = nullptr; 6671 for (auto &ENT : ExitNotTaken) { 6672 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 6673 6674 if (!BECount) 6675 BECount = ENT.ExactNotTaken; 6676 else if (BECount != ENT.ExactNotTaken) 6677 return SE->getCouldNotCompute(); 6678 if (Preds && !ENT.hasAlwaysTruePredicate()) 6679 Preds->add(ENT.Predicate.get()); 6680 6681 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6682 "Predicate should be always true!"); 6683 } 6684 6685 assert(BECount && "Invalid not taken count for loop exit"); 6686 return BECount; 6687 } 6688 6689 /// Get the exact not taken count for this loop exit. 6690 const SCEV * 6691 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6692 ScalarEvolution *SE) const { 6693 for (auto &ENT : ExitNotTaken) 6694 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6695 return ENT.ExactNotTaken; 6696 6697 return SE->getCouldNotCompute(); 6698 } 6699 6700 /// getMax - Get the max backedge taken count for the loop. 6701 const SCEV * 6702 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6703 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6704 return !ENT.hasAlwaysTruePredicate(); 6705 }; 6706 6707 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6708 return SE->getCouldNotCompute(); 6709 6710 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6711 "No point in having a non-constant max backedge taken count!"); 6712 return getMax(); 6713 } 6714 6715 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6716 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6717 return !ENT.hasAlwaysTruePredicate(); 6718 }; 6719 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6720 } 6721 6722 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6723 ScalarEvolution *SE) const { 6724 if (getMax() && getMax() != SE->getCouldNotCompute() && 6725 SE->hasOperand(getMax(), S)) 6726 return true; 6727 6728 for (auto &ENT : ExitNotTaken) 6729 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6730 SE->hasOperand(ENT.ExactNotTaken, S)) 6731 return true; 6732 6733 return false; 6734 } 6735 6736 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6737 : ExactNotTaken(E), MaxNotTaken(E) { 6738 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6739 isa<SCEVConstant>(MaxNotTaken)) && 6740 "No point in having a non-constant max backedge taken count!"); 6741 } 6742 6743 ScalarEvolution::ExitLimit::ExitLimit( 6744 const SCEV *E, const SCEV *M, bool MaxOrZero, 6745 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6746 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6747 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6748 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6749 "Exact is not allowed to be less precise than Max"); 6750 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6751 isa<SCEVConstant>(MaxNotTaken)) && 6752 "No point in having a non-constant max backedge taken count!"); 6753 for (auto *PredSet : PredSetList) 6754 for (auto *P : *PredSet) 6755 addPredicate(P); 6756 } 6757 6758 ScalarEvolution::ExitLimit::ExitLimit( 6759 const SCEV *E, const SCEV *M, bool MaxOrZero, 6760 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6761 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6762 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6763 isa<SCEVConstant>(MaxNotTaken)) && 6764 "No point in having a non-constant max backedge taken count!"); 6765 } 6766 6767 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6768 bool MaxOrZero) 6769 : ExitLimit(E, M, MaxOrZero, None) { 6770 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6771 isa<SCEVConstant>(MaxNotTaken)) && 6772 "No point in having a non-constant max backedge taken count!"); 6773 } 6774 6775 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6776 /// computable exit into a persistent ExitNotTakenInfo array. 6777 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6778 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6779 &&ExitCounts, 6780 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6781 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6782 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6783 6784 ExitNotTaken.reserve(ExitCounts.size()); 6785 std::transform( 6786 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6787 [&](const EdgeExitInfo &EEI) { 6788 BasicBlock *ExitBB = EEI.first; 6789 const ExitLimit &EL = EEI.second; 6790 if (EL.Predicates.empty()) 6791 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 6792 6793 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6794 for (auto *Pred : EL.Predicates) 6795 Predicate->add(Pred); 6796 6797 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 6798 }); 6799 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6800 "No point in having a non-constant max backedge taken count!"); 6801 } 6802 6803 /// Invalidate this result and free the ExitNotTakenInfo array. 6804 void ScalarEvolution::BackedgeTakenInfo::clear() { 6805 ExitNotTaken.clear(); 6806 } 6807 6808 /// Compute the number of times the backedge of the specified loop will execute. 6809 ScalarEvolution::BackedgeTakenInfo 6810 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6811 bool AllowPredicates) { 6812 SmallVector<BasicBlock *, 8> ExitingBlocks; 6813 L->getExitingBlocks(ExitingBlocks); 6814 6815 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6816 6817 SmallVector<EdgeExitInfo, 4> ExitCounts; 6818 bool CouldComputeBECount = true; 6819 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6820 const SCEV *MustExitMaxBECount = nullptr; 6821 const SCEV *MayExitMaxBECount = nullptr; 6822 bool MustExitMaxOrZero = false; 6823 6824 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6825 // and compute maxBECount. 6826 // Do a union of all the predicates here. 6827 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6828 BasicBlock *ExitBB = ExitingBlocks[i]; 6829 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6830 6831 assert((AllowPredicates || EL.Predicates.empty()) && 6832 "Predicated exit limit when predicates are not allowed!"); 6833 6834 // 1. For each exit that can be computed, add an entry to ExitCounts. 6835 // CouldComputeBECount is true only if all exits can be computed. 6836 if (EL.ExactNotTaken == getCouldNotCompute()) 6837 // We couldn't compute an exact value for this exit, so 6838 // we won't be able to compute an exact value for the loop. 6839 CouldComputeBECount = false; 6840 else 6841 ExitCounts.emplace_back(ExitBB, EL); 6842 6843 // 2. Derive the loop's MaxBECount from each exit's max number of 6844 // non-exiting iterations. Partition the loop exits into two kinds: 6845 // LoopMustExits and LoopMayExits. 6846 // 6847 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6848 // is a LoopMayExit. If any computable LoopMustExit is found, then 6849 // MaxBECount is the minimum EL.MaxNotTaken of computable 6850 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6851 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6852 // computable EL.MaxNotTaken. 6853 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6854 DT.dominates(ExitBB, Latch)) { 6855 if (!MustExitMaxBECount) { 6856 MustExitMaxBECount = EL.MaxNotTaken; 6857 MustExitMaxOrZero = EL.MaxOrZero; 6858 } else { 6859 MustExitMaxBECount = 6860 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6861 } 6862 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6863 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6864 MayExitMaxBECount = EL.MaxNotTaken; 6865 else { 6866 MayExitMaxBECount = 6867 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6868 } 6869 } 6870 } 6871 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6872 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6873 // The loop backedge will be taken the maximum or zero times if there's 6874 // a single exit that must be taken the maximum or zero times. 6875 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6876 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6877 MaxBECount, MaxOrZero); 6878 } 6879 6880 ScalarEvolution::ExitLimit 6881 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6882 bool AllowPredicates) { 6883 // Okay, we've chosen an exiting block. See what condition causes us to exit 6884 // at this block and remember the exit block and whether all other targets 6885 // lead to the loop header. 6886 bool MustExecuteLoopHeader = true; 6887 BasicBlock *Exit = nullptr; 6888 for (auto *SBB : successors(ExitingBlock)) 6889 if (!L->contains(SBB)) { 6890 if (Exit) // Multiple exit successors. 6891 return getCouldNotCompute(); 6892 Exit = SBB; 6893 } else if (SBB != L->getHeader()) { 6894 MustExecuteLoopHeader = false; 6895 } 6896 6897 // At this point, we know we have a conditional branch that determines whether 6898 // the loop is exited. However, we don't know if the branch is executed each 6899 // time through the loop. If not, then the execution count of the branch will 6900 // not be equal to the trip count of the loop. 6901 // 6902 // Currently we check for this by checking to see if the Exit branch goes to 6903 // the loop header. If so, we know it will always execute the same number of 6904 // times as the loop. We also handle the case where the exit block *is* the 6905 // loop header. This is common for un-rotated loops. 6906 // 6907 // If both of those tests fail, walk up the unique predecessor chain to the 6908 // header, stopping if there is an edge that doesn't exit the loop. If the 6909 // header is reached, the execution count of the branch will be equal to the 6910 // trip count of the loop. 6911 // 6912 // More extensive analysis could be done to handle more cases here. 6913 // 6914 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 6915 // The simple checks failed, try climbing the unique predecessor chain 6916 // up to the header. 6917 bool Ok = false; 6918 for (BasicBlock *BB = ExitingBlock; BB; ) { 6919 BasicBlock *Pred = BB->getUniquePredecessor(); 6920 if (!Pred) 6921 return getCouldNotCompute(); 6922 TerminatorInst *PredTerm = Pred->getTerminator(); 6923 for (const BasicBlock *PredSucc : PredTerm->successors()) { 6924 if (PredSucc == BB) 6925 continue; 6926 // If the predecessor has a successor that isn't BB and isn't 6927 // outside the loop, assume the worst. 6928 if (L->contains(PredSucc)) 6929 return getCouldNotCompute(); 6930 } 6931 if (Pred == L->getHeader()) { 6932 Ok = true; 6933 break; 6934 } 6935 BB = Pred; 6936 } 6937 if (!Ok) 6938 return getCouldNotCompute(); 6939 } 6940 6941 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6942 TerminatorInst *Term = ExitingBlock->getTerminator(); 6943 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6944 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6945 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6946 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 6947 "It should have one successor in loop and one exit block!"); 6948 // Proceed to the next level to examine the exit condition expression. 6949 return computeExitLimitFromCond( 6950 L, BI->getCondition(), ExitIfTrue, 6951 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6952 } 6953 6954 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 6955 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 6956 /*ControlsExit=*/IsOnlyExit); 6957 6958 return getCouldNotCompute(); 6959 } 6960 6961 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 6962 const Loop *L, Value *ExitCond, bool ExitIfTrue, 6963 bool ControlsExit, bool AllowPredicates) { 6964 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 6965 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 6966 ControlsExit, AllowPredicates); 6967 } 6968 6969 Optional<ScalarEvolution::ExitLimit> 6970 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 6971 bool ExitIfTrue, bool ControlsExit, 6972 bool AllowPredicates) { 6973 (void)this->L; 6974 (void)this->ExitIfTrue; 6975 (void)this->AllowPredicates; 6976 6977 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 6978 this->AllowPredicates == AllowPredicates && 6979 "Variance in assumed invariant key components!"); 6980 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 6981 if (Itr == TripCountMap.end()) 6982 return None; 6983 return Itr->second; 6984 } 6985 6986 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 6987 bool ExitIfTrue, 6988 bool ControlsExit, 6989 bool AllowPredicates, 6990 const ExitLimit &EL) { 6991 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 6992 this->AllowPredicates == AllowPredicates && 6993 "Variance in assumed invariant key components!"); 6994 6995 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 6996 assert(InsertResult.second && "Expected successful insertion!"); 6997 (void)InsertResult; 6998 (void)ExitIfTrue; 6999 } 7000 7001 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7002 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7003 bool ControlsExit, bool AllowPredicates) { 7004 7005 if (auto MaybeEL = 7006 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7007 return *MaybeEL; 7008 7009 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7010 ControlsExit, AllowPredicates); 7011 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7012 return EL; 7013 } 7014 7015 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7016 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7017 bool ControlsExit, bool AllowPredicates) { 7018 // Check if the controlling expression for this loop is an And or Or. 7019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7020 if (BO->getOpcode() == Instruction::And) { 7021 // Recurse on the operands of the and. 7022 bool EitherMayExit = !ExitIfTrue; 7023 ExitLimit EL0 = computeExitLimitFromCondCached( 7024 Cache, L, BO->getOperand(0), ExitIfTrue, 7025 ControlsExit && !EitherMayExit, AllowPredicates); 7026 ExitLimit EL1 = computeExitLimitFromCondCached( 7027 Cache, L, BO->getOperand(1), ExitIfTrue, 7028 ControlsExit && !EitherMayExit, AllowPredicates); 7029 const SCEV *BECount = getCouldNotCompute(); 7030 const SCEV *MaxBECount = getCouldNotCompute(); 7031 if (EitherMayExit) { 7032 // Both conditions must be true for the loop to continue executing. 7033 // Choose the less conservative count. 7034 if (EL0.ExactNotTaken == getCouldNotCompute() || 7035 EL1.ExactNotTaken == getCouldNotCompute()) 7036 BECount = getCouldNotCompute(); 7037 else 7038 BECount = 7039 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7040 if (EL0.MaxNotTaken == getCouldNotCompute()) 7041 MaxBECount = EL1.MaxNotTaken; 7042 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7043 MaxBECount = EL0.MaxNotTaken; 7044 else 7045 MaxBECount = 7046 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7047 } else { 7048 // Both conditions must be true at the same time for the loop to exit. 7049 // For now, be conservative. 7050 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7051 MaxBECount = EL0.MaxNotTaken; 7052 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7053 BECount = EL0.ExactNotTaken; 7054 } 7055 7056 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7057 // to be more aggressive when computing BECount than when computing 7058 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7059 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7060 // to not. 7061 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7062 !isa<SCEVCouldNotCompute>(BECount)) 7063 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7064 7065 return ExitLimit(BECount, MaxBECount, false, 7066 {&EL0.Predicates, &EL1.Predicates}); 7067 } 7068 if (BO->getOpcode() == Instruction::Or) { 7069 // Recurse on the operands of the or. 7070 bool EitherMayExit = ExitIfTrue; 7071 ExitLimit EL0 = computeExitLimitFromCondCached( 7072 Cache, L, BO->getOperand(0), ExitIfTrue, 7073 ControlsExit && !EitherMayExit, AllowPredicates); 7074 ExitLimit EL1 = computeExitLimitFromCondCached( 7075 Cache, L, BO->getOperand(1), ExitIfTrue, 7076 ControlsExit && !EitherMayExit, AllowPredicates); 7077 const SCEV *BECount = getCouldNotCompute(); 7078 const SCEV *MaxBECount = getCouldNotCompute(); 7079 if (EitherMayExit) { 7080 // Both conditions must be false for the loop to continue executing. 7081 // Choose the less conservative count. 7082 if (EL0.ExactNotTaken == getCouldNotCompute() || 7083 EL1.ExactNotTaken == getCouldNotCompute()) 7084 BECount = getCouldNotCompute(); 7085 else 7086 BECount = 7087 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7088 if (EL0.MaxNotTaken == getCouldNotCompute()) 7089 MaxBECount = EL1.MaxNotTaken; 7090 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7091 MaxBECount = EL0.MaxNotTaken; 7092 else 7093 MaxBECount = 7094 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7095 } else { 7096 // Both conditions must be false at the same time for the loop to exit. 7097 // For now, be conservative. 7098 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7099 MaxBECount = EL0.MaxNotTaken; 7100 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7101 BECount = EL0.ExactNotTaken; 7102 } 7103 7104 return ExitLimit(BECount, MaxBECount, false, 7105 {&EL0.Predicates, &EL1.Predicates}); 7106 } 7107 } 7108 7109 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7110 // Proceed to the next level to examine the icmp. 7111 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7112 ExitLimit EL = 7113 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7114 if (EL.hasFullInfo() || !AllowPredicates) 7115 return EL; 7116 7117 // Try again, but use SCEV predicates this time. 7118 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7119 /*AllowPredicates=*/true); 7120 } 7121 7122 // Check for a constant condition. These are normally stripped out by 7123 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7124 // preserve the CFG and is temporarily leaving constant conditions 7125 // in place. 7126 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7127 if (ExitIfTrue == !CI->getZExtValue()) 7128 // The backedge is always taken. 7129 return getCouldNotCompute(); 7130 else 7131 // The backedge is never taken. 7132 return getZero(CI->getType()); 7133 } 7134 7135 // If it's not an integer or pointer comparison then compute it the hard way. 7136 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7137 } 7138 7139 ScalarEvolution::ExitLimit 7140 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7141 ICmpInst *ExitCond, 7142 bool ExitIfTrue, 7143 bool ControlsExit, 7144 bool AllowPredicates) { 7145 // If the condition was exit on true, convert the condition to exit on false 7146 ICmpInst::Predicate Pred; 7147 if (!ExitIfTrue) 7148 Pred = ExitCond->getPredicate(); 7149 else 7150 Pred = ExitCond->getInversePredicate(); 7151 const ICmpInst::Predicate OriginalPred = Pred; 7152 7153 // Handle common loops like: for (X = "string"; *X; ++X) 7154 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7155 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7156 ExitLimit ItCnt = 7157 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7158 if (ItCnt.hasAnyInfo()) 7159 return ItCnt; 7160 } 7161 7162 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7163 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7164 7165 // Try to evaluate any dependencies out of the loop. 7166 LHS = getSCEVAtScope(LHS, L); 7167 RHS = getSCEVAtScope(RHS, L); 7168 7169 // At this point, we would like to compute how many iterations of the 7170 // loop the predicate will return true for these inputs. 7171 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7172 // If there is a loop-invariant, force it into the RHS. 7173 std::swap(LHS, RHS); 7174 Pred = ICmpInst::getSwappedPredicate(Pred); 7175 } 7176 7177 // Simplify the operands before analyzing them. 7178 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7179 7180 // If we have a comparison of a chrec against a constant, try to use value 7181 // ranges to answer this query. 7182 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7183 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7184 if (AddRec->getLoop() == L) { 7185 // Form the constant range. 7186 ConstantRange CompRange = 7187 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7188 7189 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7190 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7191 } 7192 7193 switch (Pred) { 7194 case ICmpInst::ICMP_NE: { // while (X != Y) 7195 // Convert to: while (X-Y != 0) 7196 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7197 AllowPredicates); 7198 if (EL.hasAnyInfo()) return EL; 7199 break; 7200 } 7201 case ICmpInst::ICMP_EQ: { // while (X == Y) 7202 // Convert to: while (X-Y == 0) 7203 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7204 if (EL.hasAnyInfo()) return EL; 7205 break; 7206 } 7207 case ICmpInst::ICMP_SLT: 7208 case ICmpInst::ICMP_ULT: { // while (X < Y) 7209 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7210 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7211 AllowPredicates); 7212 if (EL.hasAnyInfo()) return EL; 7213 break; 7214 } 7215 case ICmpInst::ICMP_SGT: 7216 case ICmpInst::ICMP_UGT: { // while (X > Y) 7217 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7218 ExitLimit EL = 7219 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7220 AllowPredicates); 7221 if (EL.hasAnyInfo()) return EL; 7222 break; 7223 } 7224 default: 7225 break; 7226 } 7227 7228 auto *ExhaustiveCount = 7229 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7230 7231 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7232 return ExhaustiveCount; 7233 7234 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7235 ExitCond->getOperand(1), L, OriginalPred); 7236 } 7237 7238 ScalarEvolution::ExitLimit 7239 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7240 SwitchInst *Switch, 7241 BasicBlock *ExitingBlock, 7242 bool ControlsExit) { 7243 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7244 7245 // Give up if the exit is the default dest of a switch. 7246 if (Switch->getDefaultDest() == ExitingBlock) 7247 return getCouldNotCompute(); 7248 7249 assert(L->contains(Switch->getDefaultDest()) && 7250 "Default case must not exit the loop!"); 7251 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7252 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7253 7254 // while (X != Y) --> while (X-Y != 0) 7255 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7256 if (EL.hasAnyInfo()) 7257 return EL; 7258 7259 return getCouldNotCompute(); 7260 } 7261 7262 static ConstantInt * 7263 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7264 ScalarEvolution &SE) { 7265 const SCEV *InVal = SE.getConstant(C); 7266 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7267 assert(isa<SCEVConstant>(Val) && 7268 "Evaluation of SCEV at constant didn't fold correctly?"); 7269 return cast<SCEVConstant>(Val)->getValue(); 7270 } 7271 7272 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7273 /// compute the backedge execution count. 7274 ScalarEvolution::ExitLimit 7275 ScalarEvolution::computeLoadConstantCompareExitLimit( 7276 LoadInst *LI, 7277 Constant *RHS, 7278 const Loop *L, 7279 ICmpInst::Predicate predicate) { 7280 if (LI->isVolatile()) return getCouldNotCompute(); 7281 7282 // Check to see if the loaded pointer is a getelementptr of a global. 7283 // TODO: Use SCEV instead of manually grubbing with GEPs. 7284 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7285 if (!GEP) return getCouldNotCompute(); 7286 7287 // Make sure that it is really a constant global we are gepping, with an 7288 // initializer, and make sure the first IDX is really 0. 7289 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7290 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7291 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7292 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7293 return getCouldNotCompute(); 7294 7295 // Okay, we allow one non-constant index into the GEP instruction. 7296 Value *VarIdx = nullptr; 7297 std::vector<Constant*> Indexes; 7298 unsigned VarIdxNum = 0; 7299 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7300 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7301 Indexes.push_back(CI); 7302 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7303 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7304 VarIdx = GEP->getOperand(i); 7305 VarIdxNum = i-2; 7306 Indexes.push_back(nullptr); 7307 } 7308 7309 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7310 if (!VarIdx) 7311 return getCouldNotCompute(); 7312 7313 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7314 // Check to see if X is a loop variant variable value now. 7315 const SCEV *Idx = getSCEV(VarIdx); 7316 Idx = getSCEVAtScope(Idx, L); 7317 7318 // We can only recognize very limited forms of loop index expressions, in 7319 // particular, only affine AddRec's like {C1,+,C2}. 7320 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7321 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7322 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7323 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7324 return getCouldNotCompute(); 7325 7326 unsigned MaxSteps = MaxBruteForceIterations; 7327 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7328 ConstantInt *ItCst = ConstantInt::get( 7329 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7330 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7331 7332 // Form the GEP offset. 7333 Indexes[VarIdxNum] = Val; 7334 7335 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7336 Indexes); 7337 if (!Result) break; // Cannot compute! 7338 7339 // Evaluate the condition for this iteration. 7340 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7341 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7342 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7343 ++NumArrayLenItCounts; 7344 return getConstant(ItCst); // Found terminating iteration! 7345 } 7346 } 7347 return getCouldNotCompute(); 7348 } 7349 7350 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7351 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7352 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7353 if (!RHS) 7354 return getCouldNotCompute(); 7355 7356 const BasicBlock *Latch = L->getLoopLatch(); 7357 if (!Latch) 7358 return getCouldNotCompute(); 7359 7360 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7361 if (!Predecessor) 7362 return getCouldNotCompute(); 7363 7364 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7365 // Return LHS in OutLHS and shift_opt in OutOpCode. 7366 auto MatchPositiveShift = 7367 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7368 7369 using namespace PatternMatch; 7370 7371 ConstantInt *ShiftAmt; 7372 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7373 OutOpCode = Instruction::LShr; 7374 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7375 OutOpCode = Instruction::AShr; 7376 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7377 OutOpCode = Instruction::Shl; 7378 else 7379 return false; 7380 7381 return ShiftAmt->getValue().isStrictlyPositive(); 7382 }; 7383 7384 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7385 // 7386 // loop: 7387 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7388 // %iv.shifted = lshr i32 %iv, <positive constant> 7389 // 7390 // Return true on a successful match. Return the corresponding PHI node (%iv 7391 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7392 auto MatchShiftRecurrence = 7393 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7394 Optional<Instruction::BinaryOps> PostShiftOpCode; 7395 7396 { 7397 Instruction::BinaryOps OpC; 7398 Value *V; 7399 7400 // If we encounter a shift instruction, "peel off" the shift operation, 7401 // and remember that we did so. Later when we inspect %iv's backedge 7402 // value, we will make sure that the backedge value uses the same 7403 // operation. 7404 // 7405 // Note: the peeled shift operation does not have to be the same 7406 // instruction as the one feeding into the PHI's backedge value. We only 7407 // really care about it being the same *kind* of shift instruction -- 7408 // that's all that is required for our later inferences to hold. 7409 if (MatchPositiveShift(LHS, V, OpC)) { 7410 PostShiftOpCode = OpC; 7411 LHS = V; 7412 } 7413 } 7414 7415 PNOut = dyn_cast<PHINode>(LHS); 7416 if (!PNOut || PNOut->getParent() != L->getHeader()) 7417 return false; 7418 7419 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7420 Value *OpLHS; 7421 7422 return 7423 // The backedge value for the PHI node must be a shift by a positive 7424 // amount 7425 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7426 7427 // of the PHI node itself 7428 OpLHS == PNOut && 7429 7430 // and the kind of shift should be match the kind of shift we peeled 7431 // off, if any. 7432 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7433 }; 7434 7435 PHINode *PN; 7436 Instruction::BinaryOps OpCode; 7437 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7438 return getCouldNotCompute(); 7439 7440 const DataLayout &DL = getDataLayout(); 7441 7442 // The key rationale for this optimization is that for some kinds of shift 7443 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7444 // within a finite number of iterations. If the condition guarding the 7445 // backedge (in the sense that the backedge is taken if the condition is true) 7446 // is false for the value the shift recurrence stabilizes to, then we know 7447 // that the backedge is taken only a finite number of times. 7448 7449 ConstantInt *StableValue = nullptr; 7450 switch (OpCode) { 7451 default: 7452 llvm_unreachable("Impossible case!"); 7453 7454 case Instruction::AShr: { 7455 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7456 // bitwidth(K) iterations. 7457 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7458 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7459 Predecessor->getTerminator(), &DT); 7460 auto *Ty = cast<IntegerType>(RHS->getType()); 7461 if (Known.isNonNegative()) 7462 StableValue = ConstantInt::get(Ty, 0); 7463 else if (Known.isNegative()) 7464 StableValue = ConstantInt::get(Ty, -1, true); 7465 else 7466 return getCouldNotCompute(); 7467 7468 break; 7469 } 7470 case Instruction::LShr: 7471 case Instruction::Shl: 7472 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7473 // stabilize to 0 in at most bitwidth(K) iterations. 7474 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7475 break; 7476 } 7477 7478 auto *Result = 7479 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7480 assert(Result->getType()->isIntegerTy(1) && 7481 "Otherwise cannot be an operand to a branch instruction"); 7482 7483 if (Result->isZeroValue()) { 7484 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7485 const SCEV *UpperBound = 7486 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7487 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7488 } 7489 7490 return getCouldNotCompute(); 7491 } 7492 7493 /// Return true if we can constant fold an instruction of the specified type, 7494 /// assuming that all operands were constants. 7495 static bool CanConstantFold(const Instruction *I) { 7496 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7497 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7498 isa<LoadInst>(I)) 7499 return true; 7500 7501 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7502 if (const Function *F = CI->getCalledFunction()) 7503 return canConstantFoldCallTo(CI, F); 7504 return false; 7505 } 7506 7507 /// Determine whether this instruction can constant evolve within this loop 7508 /// assuming its operands can all constant evolve. 7509 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7510 // An instruction outside of the loop can't be derived from a loop PHI. 7511 if (!L->contains(I)) return false; 7512 7513 if (isa<PHINode>(I)) { 7514 // We don't currently keep track of the control flow needed to evaluate 7515 // PHIs, so we cannot handle PHIs inside of loops. 7516 return L->getHeader() == I->getParent(); 7517 } 7518 7519 // If we won't be able to constant fold this expression even if the operands 7520 // are constants, bail early. 7521 return CanConstantFold(I); 7522 } 7523 7524 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7525 /// recursing through each instruction operand until reaching a loop header phi. 7526 static PHINode * 7527 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7528 DenseMap<Instruction *, PHINode *> &PHIMap, 7529 unsigned Depth) { 7530 if (Depth > MaxConstantEvolvingDepth) 7531 return nullptr; 7532 7533 // Otherwise, we can evaluate this instruction if all of its operands are 7534 // constant or derived from a PHI node themselves. 7535 PHINode *PHI = nullptr; 7536 for (Value *Op : UseInst->operands()) { 7537 if (isa<Constant>(Op)) continue; 7538 7539 Instruction *OpInst = dyn_cast<Instruction>(Op); 7540 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7541 7542 PHINode *P = dyn_cast<PHINode>(OpInst); 7543 if (!P) 7544 // If this operand is already visited, reuse the prior result. 7545 // We may have P != PHI if this is the deepest point at which the 7546 // inconsistent paths meet. 7547 P = PHIMap.lookup(OpInst); 7548 if (!P) { 7549 // Recurse and memoize the results, whether a phi is found or not. 7550 // This recursive call invalidates pointers into PHIMap. 7551 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7552 PHIMap[OpInst] = P; 7553 } 7554 if (!P) 7555 return nullptr; // Not evolving from PHI 7556 if (PHI && PHI != P) 7557 return nullptr; // Evolving from multiple different PHIs. 7558 PHI = P; 7559 } 7560 // This is a expression evolving from a constant PHI! 7561 return PHI; 7562 } 7563 7564 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7565 /// in the loop that V is derived from. We allow arbitrary operations along the 7566 /// way, but the operands of an operation must either be constants or a value 7567 /// derived from a constant PHI. If this expression does not fit with these 7568 /// constraints, return null. 7569 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7570 Instruction *I = dyn_cast<Instruction>(V); 7571 if (!I || !canConstantEvolve(I, L)) return nullptr; 7572 7573 if (PHINode *PN = dyn_cast<PHINode>(I)) 7574 return PN; 7575 7576 // Record non-constant instructions contained by the loop. 7577 DenseMap<Instruction *, PHINode *> PHIMap; 7578 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7579 } 7580 7581 /// EvaluateExpression - Given an expression that passes the 7582 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7583 /// in the loop has the value PHIVal. If we can't fold this expression for some 7584 /// reason, return null. 7585 static Constant *EvaluateExpression(Value *V, const Loop *L, 7586 DenseMap<Instruction *, Constant *> &Vals, 7587 const DataLayout &DL, 7588 const TargetLibraryInfo *TLI) { 7589 // Convenient constant check, but redundant for recursive calls. 7590 if (Constant *C = dyn_cast<Constant>(V)) return C; 7591 Instruction *I = dyn_cast<Instruction>(V); 7592 if (!I) return nullptr; 7593 7594 if (Constant *C = Vals.lookup(I)) return C; 7595 7596 // An instruction inside the loop depends on a value outside the loop that we 7597 // weren't given a mapping for, or a value such as a call inside the loop. 7598 if (!canConstantEvolve(I, L)) return nullptr; 7599 7600 // An unmapped PHI can be due to a branch or another loop inside this loop, 7601 // or due to this not being the initial iteration through a loop where we 7602 // couldn't compute the evolution of this particular PHI last time. 7603 if (isa<PHINode>(I)) return nullptr; 7604 7605 std::vector<Constant*> Operands(I->getNumOperands()); 7606 7607 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7608 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7609 if (!Operand) { 7610 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7611 if (!Operands[i]) return nullptr; 7612 continue; 7613 } 7614 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7615 Vals[Operand] = C; 7616 if (!C) return nullptr; 7617 Operands[i] = C; 7618 } 7619 7620 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7621 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7622 Operands[1], DL, TLI); 7623 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7624 if (!LI->isVolatile()) 7625 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7626 } 7627 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7628 } 7629 7630 7631 // If every incoming value to PN except the one for BB is a specific Constant, 7632 // return that, else return nullptr. 7633 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7634 Constant *IncomingVal = nullptr; 7635 7636 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7637 if (PN->getIncomingBlock(i) == BB) 7638 continue; 7639 7640 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7641 if (!CurrentVal) 7642 return nullptr; 7643 7644 if (IncomingVal != CurrentVal) { 7645 if (IncomingVal) 7646 return nullptr; 7647 IncomingVal = CurrentVal; 7648 } 7649 } 7650 7651 return IncomingVal; 7652 } 7653 7654 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7655 /// in the header of its containing loop, we know the loop executes a 7656 /// constant number of times, and the PHI node is just a recurrence 7657 /// involving constants, fold it. 7658 Constant * 7659 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7660 const APInt &BEs, 7661 const Loop *L) { 7662 auto I = ConstantEvolutionLoopExitValue.find(PN); 7663 if (I != ConstantEvolutionLoopExitValue.end()) 7664 return I->second; 7665 7666 if (BEs.ugt(MaxBruteForceIterations)) 7667 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7668 7669 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7670 7671 DenseMap<Instruction *, Constant *> CurrentIterVals; 7672 BasicBlock *Header = L->getHeader(); 7673 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7674 7675 BasicBlock *Latch = L->getLoopLatch(); 7676 if (!Latch) 7677 return nullptr; 7678 7679 for (PHINode &PHI : Header->phis()) { 7680 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7681 CurrentIterVals[&PHI] = StartCST; 7682 } 7683 if (!CurrentIterVals.count(PN)) 7684 return RetVal = nullptr; 7685 7686 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7687 7688 // Execute the loop symbolically to determine the exit value. 7689 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7690 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7691 7692 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7693 unsigned IterationNum = 0; 7694 const DataLayout &DL = getDataLayout(); 7695 for (; ; ++IterationNum) { 7696 if (IterationNum == NumIterations) 7697 return RetVal = CurrentIterVals[PN]; // Got exit value! 7698 7699 // Compute the value of the PHIs for the next iteration. 7700 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7701 DenseMap<Instruction *, Constant *> NextIterVals; 7702 Constant *NextPHI = 7703 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7704 if (!NextPHI) 7705 return nullptr; // Couldn't evaluate! 7706 NextIterVals[PN] = NextPHI; 7707 7708 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7709 7710 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7711 // cease to be able to evaluate one of them or if they stop evolving, 7712 // because that doesn't necessarily prevent us from computing PN. 7713 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7714 for (const auto &I : CurrentIterVals) { 7715 PHINode *PHI = dyn_cast<PHINode>(I.first); 7716 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7717 PHIsToCompute.emplace_back(PHI, I.second); 7718 } 7719 // We use two distinct loops because EvaluateExpression may invalidate any 7720 // iterators into CurrentIterVals. 7721 for (const auto &I : PHIsToCompute) { 7722 PHINode *PHI = I.first; 7723 Constant *&NextPHI = NextIterVals[PHI]; 7724 if (!NextPHI) { // Not already computed. 7725 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7726 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7727 } 7728 if (NextPHI != I.second) 7729 StoppedEvolving = false; 7730 } 7731 7732 // If all entries in CurrentIterVals == NextIterVals then we can stop 7733 // iterating, the loop can't continue to change. 7734 if (StoppedEvolving) 7735 return RetVal = CurrentIterVals[PN]; 7736 7737 CurrentIterVals.swap(NextIterVals); 7738 } 7739 } 7740 7741 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7742 Value *Cond, 7743 bool ExitWhen) { 7744 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7745 if (!PN) return getCouldNotCompute(); 7746 7747 // If the loop is canonicalized, the PHI will have exactly two entries. 7748 // That's the only form we support here. 7749 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7750 7751 DenseMap<Instruction *, Constant *> CurrentIterVals; 7752 BasicBlock *Header = L->getHeader(); 7753 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7754 7755 BasicBlock *Latch = L->getLoopLatch(); 7756 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7757 7758 for (PHINode &PHI : Header->phis()) { 7759 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7760 CurrentIterVals[&PHI] = StartCST; 7761 } 7762 if (!CurrentIterVals.count(PN)) 7763 return getCouldNotCompute(); 7764 7765 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7766 // the loop symbolically to determine when the condition gets a value of 7767 // "ExitWhen". 7768 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7769 const DataLayout &DL = getDataLayout(); 7770 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7771 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7772 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7773 7774 // Couldn't symbolically evaluate. 7775 if (!CondVal) return getCouldNotCompute(); 7776 7777 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7778 ++NumBruteForceTripCountsComputed; 7779 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7780 } 7781 7782 // Update all the PHI nodes for the next iteration. 7783 DenseMap<Instruction *, Constant *> NextIterVals; 7784 7785 // Create a list of which PHIs we need to compute. We want to do this before 7786 // calling EvaluateExpression on them because that may invalidate iterators 7787 // into CurrentIterVals. 7788 SmallVector<PHINode *, 8> PHIsToCompute; 7789 for (const auto &I : CurrentIterVals) { 7790 PHINode *PHI = dyn_cast<PHINode>(I.first); 7791 if (!PHI || PHI->getParent() != Header) continue; 7792 PHIsToCompute.push_back(PHI); 7793 } 7794 for (PHINode *PHI : PHIsToCompute) { 7795 Constant *&NextPHI = NextIterVals[PHI]; 7796 if (NextPHI) continue; // Already computed! 7797 7798 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7799 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7800 } 7801 CurrentIterVals.swap(NextIterVals); 7802 } 7803 7804 // Too many iterations were needed to evaluate. 7805 return getCouldNotCompute(); 7806 } 7807 7808 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7809 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7810 ValuesAtScopes[V]; 7811 // Check to see if we've folded this expression at this loop before. 7812 for (auto &LS : Values) 7813 if (LS.first == L) 7814 return LS.second ? LS.second : V; 7815 7816 Values.emplace_back(L, nullptr); 7817 7818 // Otherwise compute it. 7819 const SCEV *C = computeSCEVAtScope(V, L); 7820 for (auto &LS : reverse(ValuesAtScopes[V])) 7821 if (LS.first == L) { 7822 LS.second = C; 7823 break; 7824 } 7825 return C; 7826 } 7827 7828 /// This builds up a Constant using the ConstantExpr interface. That way, we 7829 /// will return Constants for objects which aren't represented by a 7830 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7831 /// Returns NULL if the SCEV isn't representable as a Constant. 7832 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7833 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7834 case scCouldNotCompute: 7835 case scAddRecExpr: 7836 break; 7837 case scConstant: 7838 return cast<SCEVConstant>(V)->getValue(); 7839 case scUnknown: 7840 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7841 case scSignExtend: { 7842 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7843 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7844 return ConstantExpr::getSExt(CastOp, SS->getType()); 7845 break; 7846 } 7847 case scZeroExtend: { 7848 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7849 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7850 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7851 break; 7852 } 7853 case scTruncate: { 7854 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7855 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7856 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7857 break; 7858 } 7859 case scAddExpr: { 7860 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7861 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7862 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7863 unsigned AS = PTy->getAddressSpace(); 7864 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7865 C = ConstantExpr::getBitCast(C, DestPtrTy); 7866 } 7867 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7868 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7869 if (!C2) return nullptr; 7870 7871 // First pointer! 7872 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7873 unsigned AS = C2->getType()->getPointerAddressSpace(); 7874 std::swap(C, C2); 7875 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7876 // The offsets have been converted to bytes. We can add bytes to an 7877 // i8* by GEP with the byte count in the first index. 7878 C = ConstantExpr::getBitCast(C, DestPtrTy); 7879 } 7880 7881 // Don't bother trying to sum two pointers. We probably can't 7882 // statically compute a load that results from it anyway. 7883 if (C2->getType()->isPointerTy()) 7884 return nullptr; 7885 7886 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7887 if (PTy->getElementType()->isStructTy()) 7888 C2 = ConstantExpr::getIntegerCast( 7889 C2, Type::getInt32Ty(C->getContext()), true); 7890 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7891 } else 7892 C = ConstantExpr::getAdd(C, C2); 7893 } 7894 return C; 7895 } 7896 break; 7897 } 7898 case scMulExpr: { 7899 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7900 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7901 // Don't bother with pointers at all. 7902 if (C->getType()->isPointerTy()) return nullptr; 7903 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7904 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7905 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7906 C = ConstantExpr::getMul(C, C2); 7907 } 7908 return C; 7909 } 7910 break; 7911 } 7912 case scUDivExpr: { 7913 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7914 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7915 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7916 if (LHS->getType() == RHS->getType()) 7917 return ConstantExpr::getUDiv(LHS, RHS); 7918 break; 7919 } 7920 case scSMaxExpr: 7921 case scUMaxExpr: 7922 break; // TODO: smax, umax. 7923 } 7924 return nullptr; 7925 } 7926 7927 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7928 if (isa<SCEVConstant>(V)) return V; 7929 7930 // If this instruction is evolved from a constant-evolving PHI, compute the 7931 // exit value from the loop without using SCEVs. 7932 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 7933 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 7934 const Loop *LI = this->LI[I->getParent()]; 7935 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 7936 if (PHINode *PN = dyn_cast<PHINode>(I)) 7937 if (PN->getParent() == LI->getHeader()) { 7938 // Okay, there is no closed form solution for the PHI node. Check 7939 // to see if the loop that contains it has a known backedge-taken 7940 // count. If so, we may be able to force computation of the exit 7941 // value. 7942 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 7943 if (const SCEVConstant *BTCC = 7944 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 7945 7946 // This trivial case can show up in some degenerate cases where 7947 // the incoming IR has not yet been fully simplified. 7948 if (BTCC->getValue()->isZero()) { 7949 Value *InitValue = nullptr; 7950 bool MultipleInitValues = false; 7951 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 7952 if (!LI->contains(PN->getIncomingBlock(i))) { 7953 if (!InitValue) 7954 InitValue = PN->getIncomingValue(i); 7955 else if (InitValue != PN->getIncomingValue(i)) { 7956 MultipleInitValues = true; 7957 break; 7958 } 7959 } 7960 if (!MultipleInitValues && InitValue) 7961 return getSCEV(InitValue); 7962 } 7963 } 7964 // Okay, we know how many times the containing loop executes. If 7965 // this is a constant evolving PHI node, get the final value at 7966 // the specified iteration number. 7967 Constant *RV = 7968 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 7969 if (RV) return getSCEV(RV); 7970 } 7971 } 7972 7973 // Okay, this is an expression that we cannot symbolically evaluate 7974 // into a SCEV. Check to see if it's possible to symbolically evaluate 7975 // the arguments into constants, and if so, try to constant propagate the 7976 // result. This is particularly useful for computing loop exit values. 7977 if (CanConstantFold(I)) { 7978 SmallVector<Constant *, 4> Operands; 7979 bool MadeImprovement = false; 7980 for (Value *Op : I->operands()) { 7981 if (Constant *C = dyn_cast<Constant>(Op)) { 7982 Operands.push_back(C); 7983 continue; 7984 } 7985 7986 // If any of the operands is non-constant and if they are 7987 // non-integer and non-pointer, don't even try to analyze them 7988 // with scev techniques. 7989 if (!isSCEVable(Op->getType())) 7990 return V; 7991 7992 const SCEV *OrigV = getSCEV(Op); 7993 const SCEV *OpV = getSCEVAtScope(OrigV, L); 7994 MadeImprovement |= OrigV != OpV; 7995 7996 Constant *C = BuildConstantFromSCEV(OpV); 7997 if (!C) return V; 7998 if (C->getType() != Op->getType()) 7999 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8000 Op->getType(), 8001 false), 8002 C, Op->getType()); 8003 Operands.push_back(C); 8004 } 8005 8006 // Check to see if getSCEVAtScope actually made an improvement. 8007 if (MadeImprovement) { 8008 Constant *C = nullptr; 8009 const DataLayout &DL = getDataLayout(); 8010 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8011 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8012 Operands[1], DL, &TLI); 8013 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8014 if (!LI->isVolatile()) 8015 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8016 } else 8017 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8018 if (!C) return V; 8019 return getSCEV(C); 8020 } 8021 } 8022 } 8023 8024 // This is some other type of SCEVUnknown, just return it. 8025 return V; 8026 } 8027 8028 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8029 // Avoid performing the look-up in the common case where the specified 8030 // expression has no loop-variant portions. 8031 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8032 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8033 if (OpAtScope != Comm->getOperand(i)) { 8034 // Okay, at least one of these operands is loop variant but might be 8035 // foldable. Build a new instance of the folded commutative expression. 8036 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8037 Comm->op_begin()+i); 8038 NewOps.push_back(OpAtScope); 8039 8040 for (++i; i != e; ++i) { 8041 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8042 NewOps.push_back(OpAtScope); 8043 } 8044 if (isa<SCEVAddExpr>(Comm)) 8045 return getAddExpr(NewOps); 8046 if (isa<SCEVMulExpr>(Comm)) 8047 return getMulExpr(NewOps); 8048 if (isa<SCEVSMaxExpr>(Comm)) 8049 return getSMaxExpr(NewOps); 8050 if (isa<SCEVUMaxExpr>(Comm)) 8051 return getUMaxExpr(NewOps); 8052 llvm_unreachable("Unknown commutative SCEV type!"); 8053 } 8054 } 8055 // If we got here, all operands are loop invariant. 8056 return Comm; 8057 } 8058 8059 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8060 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8061 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8062 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8063 return Div; // must be loop invariant 8064 return getUDivExpr(LHS, RHS); 8065 } 8066 8067 // If this is a loop recurrence for a loop that does not contain L, then we 8068 // are dealing with the final value computed by the loop. 8069 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8070 // First, attempt to evaluate each operand. 8071 // Avoid performing the look-up in the common case where the specified 8072 // expression has no loop-variant portions. 8073 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8074 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8075 if (OpAtScope == AddRec->getOperand(i)) 8076 continue; 8077 8078 // Okay, at least one of these operands is loop variant but might be 8079 // foldable. Build a new instance of the folded commutative expression. 8080 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8081 AddRec->op_begin()+i); 8082 NewOps.push_back(OpAtScope); 8083 for (++i; i != e; ++i) 8084 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8085 8086 const SCEV *FoldedRec = 8087 getAddRecExpr(NewOps, AddRec->getLoop(), 8088 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8089 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8090 // The addrec may be folded to a nonrecurrence, for example, if the 8091 // induction variable is multiplied by zero after constant folding. Go 8092 // ahead and return the folded value. 8093 if (!AddRec) 8094 return FoldedRec; 8095 break; 8096 } 8097 8098 // If the scope is outside the addrec's loop, evaluate it by using the 8099 // loop exit value of the addrec. 8100 if (!AddRec->getLoop()->contains(L)) { 8101 // To evaluate this recurrence, we need to know how many times the AddRec 8102 // loop iterates. Compute this now. 8103 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8104 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8105 8106 // Then, evaluate the AddRec. 8107 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8108 } 8109 8110 return AddRec; 8111 } 8112 8113 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8114 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8115 if (Op == Cast->getOperand()) 8116 return Cast; // must be loop invariant 8117 return getZeroExtendExpr(Op, Cast->getType()); 8118 } 8119 8120 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8121 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8122 if (Op == Cast->getOperand()) 8123 return Cast; // must be loop invariant 8124 return getSignExtendExpr(Op, Cast->getType()); 8125 } 8126 8127 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8128 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8129 if (Op == Cast->getOperand()) 8130 return Cast; // must be loop invariant 8131 return getTruncateExpr(Op, Cast->getType()); 8132 } 8133 8134 llvm_unreachable("Unknown SCEV type!"); 8135 } 8136 8137 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8138 return getSCEVAtScope(getSCEV(V), L); 8139 } 8140 8141 /// Finds the minimum unsigned root of the following equation: 8142 /// 8143 /// A * X = B (mod N) 8144 /// 8145 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8146 /// A and B isn't important. 8147 /// 8148 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8149 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8150 ScalarEvolution &SE) { 8151 uint32_t BW = A.getBitWidth(); 8152 assert(BW == SE.getTypeSizeInBits(B->getType())); 8153 assert(A != 0 && "A must be non-zero."); 8154 8155 // 1. D = gcd(A, N) 8156 // 8157 // The gcd of A and N may have only one prime factor: 2. The number of 8158 // trailing zeros in A is its multiplicity 8159 uint32_t Mult2 = A.countTrailingZeros(); 8160 // D = 2^Mult2 8161 8162 // 2. Check if B is divisible by D. 8163 // 8164 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8165 // is not less than multiplicity of this prime factor for D. 8166 if (SE.GetMinTrailingZeros(B) < Mult2) 8167 return SE.getCouldNotCompute(); 8168 8169 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8170 // modulo (N / D). 8171 // 8172 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8173 // (N / D) in general. The inverse itself always fits into BW bits, though, 8174 // so we immediately truncate it. 8175 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8176 APInt Mod(BW + 1, 0); 8177 Mod.setBit(BW - Mult2); // Mod = N / D 8178 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8179 8180 // 4. Compute the minimum unsigned root of the equation: 8181 // I * (B / D) mod (N / D) 8182 // To simplify the computation, we factor out the divide by D: 8183 // (I * B mod N) / D 8184 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8185 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8186 } 8187 8188 /// Find the roots of the quadratic equation for the given quadratic chrec 8189 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 8190 /// two SCEVCouldNotCompute objects. 8191 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 8192 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8193 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8194 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8195 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8196 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8197 8198 // We currently can only solve this if the coefficients are constants. 8199 if (!LC || !MC || !NC) 8200 return None; 8201 8202 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 8203 const APInt &L = LC->getAPInt(); 8204 const APInt &M = MC->getAPInt(); 8205 const APInt &N = NC->getAPInt(); 8206 APInt Two(BitWidth, 2); 8207 8208 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 8209 8210 // The A coefficient is N/2 8211 APInt A = N.sdiv(Two); 8212 8213 // The B coefficient is M-N/2 8214 APInt B = M; 8215 B -= A; // A is the same as N/2. 8216 8217 // The C coefficient is L. 8218 const APInt& C = L; 8219 8220 // Compute the B^2-4ac term. 8221 APInt SqrtTerm = B; 8222 SqrtTerm *= B; 8223 SqrtTerm -= 4 * (A * C); 8224 8225 if (SqrtTerm.isNegative()) { 8226 // The loop is provably infinite. 8227 return None; 8228 } 8229 8230 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 8231 // integer value or else APInt::sqrt() will assert. 8232 APInt SqrtVal = SqrtTerm.sqrt(); 8233 8234 // Compute the two solutions for the quadratic formula. 8235 // The divisions must be performed as signed divisions. 8236 APInt NegB = -std::move(B); 8237 APInt TwoA = std::move(A); 8238 TwoA <<= 1; 8239 if (TwoA.isNullValue()) 8240 return None; 8241 8242 LLVMContext &Context = SE.getContext(); 8243 8244 ConstantInt *Solution1 = 8245 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 8246 ConstantInt *Solution2 = 8247 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 8248 8249 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 8250 cast<SCEVConstant>(SE.getConstant(Solution2))); 8251 } 8252 8253 ScalarEvolution::ExitLimit 8254 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8255 bool AllowPredicates) { 8256 8257 // This is only used for loops with a "x != y" exit test. The exit condition 8258 // is now expressed as a single expression, V = x-y. So the exit test is 8259 // effectively V != 0. We know and take advantage of the fact that this 8260 // expression only being used in a comparison by zero context. 8261 8262 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8263 // If the value is a constant 8264 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8265 // If the value is already zero, the branch will execute zero times. 8266 if (C->getValue()->isZero()) return C; 8267 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8268 } 8269 8270 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 8271 if (!AddRec && AllowPredicates) 8272 // Try to make this an AddRec using runtime tests, in the first X 8273 // iterations of this loop, where X is the SCEV expression found by the 8274 // algorithm below. 8275 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8276 8277 if (!AddRec || AddRec->getLoop() != L) 8278 return getCouldNotCompute(); 8279 8280 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8281 // the quadratic equation to solve it. 8282 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8283 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 8284 const SCEVConstant *R1 = Roots->first; 8285 const SCEVConstant *R2 = Roots->second; 8286 // Pick the smallest positive root value. 8287 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8288 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8289 if (!CB->getZExtValue()) 8290 std::swap(R1, R2); // R1 is the minimum root now. 8291 8292 // We can only use this value if the chrec ends up with an exact zero 8293 // value at this index. When solving for "X*X != 5", for example, we 8294 // should not accept a root of 2. 8295 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 8296 if (Val->isZero()) 8297 // We found a quadratic root! 8298 return ExitLimit(R1, R1, false, Predicates); 8299 } 8300 } 8301 return getCouldNotCompute(); 8302 } 8303 8304 // Otherwise we can only handle this if it is affine. 8305 if (!AddRec->isAffine()) 8306 return getCouldNotCompute(); 8307 8308 // If this is an affine expression, the execution count of this branch is 8309 // the minimum unsigned root of the following equation: 8310 // 8311 // Start + Step*N = 0 (mod 2^BW) 8312 // 8313 // equivalent to: 8314 // 8315 // Step*N = -Start (mod 2^BW) 8316 // 8317 // where BW is the common bit width of Start and Step. 8318 8319 // Get the initial value for the loop. 8320 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8321 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8322 8323 // For now we handle only constant steps. 8324 // 8325 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8326 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8327 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8328 // We have not yet seen any such cases. 8329 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8330 if (!StepC || StepC->getValue()->isZero()) 8331 return getCouldNotCompute(); 8332 8333 // For positive steps (counting up until unsigned overflow): 8334 // N = -Start/Step (as unsigned) 8335 // For negative steps (counting down to zero): 8336 // N = Start/-Step 8337 // First compute the unsigned distance from zero in the direction of Step. 8338 bool CountDown = StepC->getAPInt().isNegative(); 8339 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8340 8341 // Handle unitary steps, which cannot wraparound. 8342 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8343 // N = Distance (as unsigned) 8344 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8345 APInt MaxBECount = getUnsignedRangeMax(Distance); 8346 8347 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8348 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8349 // case, and see if we can improve the bound. 8350 // 8351 // Explicitly handling this here is necessary because getUnsignedRange 8352 // isn't context-sensitive; it doesn't know that we only care about the 8353 // range inside the loop. 8354 const SCEV *Zero = getZero(Distance->getType()); 8355 const SCEV *One = getOne(Distance->getType()); 8356 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8357 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8358 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8359 // as "unsigned_max(Distance + 1) - 1". 8360 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8361 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8362 } 8363 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8364 } 8365 8366 // If the condition controls loop exit (the loop exits only if the expression 8367 // is true) and the addition is no-wrap we can use unsigned divide to 8368 // compute the backedge count. In this case, the step may not divide the 8369 // distance, but we don't care because if the condition is "missed" the loop 8370 // will have undefined behavior due to wrapping. 8371 if (ControlsExit && AddRec->hasNoSelfWrap() && 8372 loopHasNoAbnormalExits(AddRec->getLoop())) { 8373 const SCEV *Exact = 8374 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8375 const SCEV *Max = 8376 Exact == getCouldNotCompute() 8377 ? Exact 8378 : getConstant(getUnsignedRangeMax(Exact)); 8379 return ExitLimit(Exact, Max, false, Predicates); 8380 } 8381 8382 // Solve the general equation. 8383 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8384 getNegativeSCEV(Start), *this); 8385 const SCEV *M = E == getCouldNotCompute() 8386 ? E 8387 : getConstant(getUnsignedRangeMax(E)); 8388 return ExitLimit(E, M, false, Predicates); 8389 } 8390 8391 ScalarEvolution::ExitLimit 8392 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8393 // Loops that look like: while (X == 0) are very strange indeed. We don't 8394 // handle them yet except for the trivial case. This could be expanded in the 8395 // future as needed. 8396 8397 // If the value is a constant, check to see if it is known to be non-zero 8398 // already. If so, the backedge will execute zero times. 8399 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8400 if (!C->getValue()->isZero()) 8401 return getZero(C->getType()); 8402 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8403 } 8404 8405 // We could implement others, but I really doubt anyone writes loops like 8406 // this, and if they did, they would already be constant folded. 8407 return getCouldNotCompute(); 8408 } 8409 8410 std::pair<BasicBlock *, BasicBlock *> 8411 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8412 // If the block has a unique predecessor, then there is no path from the 8413 // predecessor to the block that does not go through the direct edge 8414 // from the predecessor to the block. 8415 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8416 return {Pred, BB}; 8417 8418 // A loop's header is defined to be a block that dominates the loop. 8419 // If the header has a unique predecessor outside the loop, it must be 8420 // a block that has exactly one successor that can reach the loop. 8421 if (Loop *L = LI.getLoopFor(BB)) 8422 return {L->getLoopPredecessor(), L->getHeader()}; 8423 8424 return {nullptr, nullptr}; 8425 } 8426 8427 /// SCEV structural equivalence is usually sufficient for testing whether two 8428 /// expressions are equal, however for the purposes of looking for a condition 8429 /// guarding a loop, it can be useful to be a little more general, since a 8430 /// front-end may have replicated the controlling expression. 8431 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8432 // Quick check to see if they are the same SCEV. 8433 if (A == B) return true; 8434 8435 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8436 // Not all instructions that are "identical" compute the same value. For 8437 // instance, two distinct alloca instructions allocating the same type are 8438 // identical and do not read memory; but compute distinct values. 8439 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8440 }; 8441 8442 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8443 // two different instructions with the same value. Check for this case. 8444 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8445 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8446 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8447 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8448 if (ComputesEqualValues(AI, BI)) 8449 return true; 8450 8451 // Otherwise assume they may have a different value. 8452 return false; 8453 } 8454 8455 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8456 const SCEV *&LHS, const SCEV *&RHS, 8457 unsigned Depth) { 8458 bool Changed = false; 8459 8460 // If we hit the max recursion limit bail out. 8461 if (Depth >= 3) 8462 return false; 8463 8464 // Canonicalize a constant to the right side. 8465 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8466 // Check for both operands constant. 8467 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8468 if (ConstantExpr::getICmp(Pred, 8469 LHSC->getValue(), 8470 RHSC->getValue())->isNullValue()) 8471 goto trivially_false; 8472 else 8473 goto trivially_true; 8474 } 8475 // Otherwise swap the operands to put the constant on the right. 8476 std::swap(LHS, RHS); 8477 Pred = ICmpInst::getSwappedPredicate(Pred); 8478 Changed = true; 8479 } 8480 8481 // If we're comparing an addrec with a value which is loop-invariant in the 8482 // addrec's loop, put the addrec on the left. Also make a dominance check, 8483 // as both operands could be addrecs loop-invariant in each other's loop. 8484 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8485 const Loop *L = AR->getLoop(); 8486 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8487 std::swap(LHS, RHS); 8488 Pred = ICmpInst::getSwappedPredicate(Pred); 8489 Changed = true; 8490 } 8491 } 8492 8493 // If there's a constant operand, canonicalize comparisons with boundary 8494 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8495 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8496 const APInt &RA = RC->getAPInt(); 8497 8498 bool SimplifiedByConstantRange = false; 8499 8500 if (!ICmpInst::isEquality(Pred)) { 8501 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8502 if (ExactCR.isFullSet()) 8503 goto trivially_true; 8504 else if (ExactCR.isEmptySet()) 8505 goto trivially_false; 8506 8507 APInt NewRHS; 8508 CmpInst::Predicate NewPred; 8509 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8510 ICmpInst::isEquality(NewPred)) { 8511 // We were able to convert an inequality to an equality. 8512 Pred = NewPred; 8513 RHS = getConstant(NewRHS); 8514 Changed = SimplifiedByConstantRange = true; 8515 } 8516 } 8517 8518 if (!SimplifiedByConstantRange) { 8519 switch (Pred) { 8520 default: 8521 break; 8522 case ICmpInst::ICMP_EQ: 8523 case ICmpInst::ICMP_NE: 8524 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8525 if (!RA) 8526 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8527 if (const SCEVMulExpr *ME = 8528 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8529 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8530 ME->getOperand(0)->isAllOnesValue()) { 8531 RHS = AE->getOperand(1); 8532 LHS = ME->getOperand(1); 8533 Changed = true; 8534 } 8535 break; 8536 8537 8538 // The "Should have been caught earlier!" messages refer to the fact 8539 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8540 // should have fired on the corresponding cases, and canonicalized the 8541 // check to trivially_true or trivially_false. 8542 8543 case ICmpInst::ICMP_UGE: 8544 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8545 Pred = ICmpInst::ICMP_UGT; 8546 RHS = getConstant(RA - 1); 8547 Changed = true; 8548 break; 8549 case ICmpInst::ICMP_ULE: 8550 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8551 Pred = ICmpInst::ICMP_ULT; 8552 RHS = getConstant(RA + 1); 8553 Changed = true; 8554 break; 8555 case ICmpInst::ICMP_SGE: 8556 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8557 Pred = ICmpInst::ICMP_SGT; 8558 RHS = getConstant(RA - 1); 8559 Changed = true; 8560 break; 8561 case ICmpInst::ICMP_SLE: 8562 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8563 Pred = ICmpInst::ICMP_SLT; 8564 RHS = getConstant(RA + 1); 8565 Changed = true; 8566 break; 8567 } 8568 } 8569 } 8570 8571 // Check for obvious equality. 8572 if (HasSameValue(LHS, RHS)) { 8573 if (ICmpInst::isTrueWhenEqual(Pred)) 8574 goto trivially_true; 8575 if (ICmpInst::isFalseWhenEqual(Pred)) 8576 goto trivially_false; 8577 } 8578 8579 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8580 // adding or subtracting 1 from one of the operands. 8581 switch (Pred) { 8582 case ICmpInst::ICMP_SLE: 8583 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8584 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8585 SCEV::FlagNSW); 8586 Pred = ICmpInst::ICMP_SLT; 8587 Changed = true; 8588 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8589 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8590 SCEV::FlagNSW); 8591 Pred = ICmpInst::ICMP_SLT; 8592 Changed = true; 8593 } 8594 break; 8595 case ICmpInst::ICMP_SGE: 8596 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8597 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8598 SCEV::FlagNSW); 8599 Pred = ICmpInst::ICMP_SGT; 8600 Changed = true; 8601 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8602 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8603 SCEV::FlagNSW); 8604 Pred = ICmpInst::ICMP_SGT; 8605 Changed = true; 8606 } 8607 break; 8608 case ICmpInst::ICMP_ULE: 8609 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8610 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8611 SCEV::FlagNUW); 8612 Pred = ICmpInst::ICMP_ULT; 8613 Changed = true; 8614 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8615 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8616 Pred = ICmpInst::ICMP_ULT; 8617 Changed = true; 8618 } 8619 break; 8620 case ICmpInst::ICMP_UGE: 8621 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8622 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8623 Pred = ICmpInst::ICMP_UGT; 8624 Changed = true; 8625 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8626 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8627 SCEV::FlagNUW); 8628 Pred = ICmpInst::ICMP_UGT; 8629 Changed = true; 8630 } 8631 break; 8632 default: 8633 break; 8634 } 8635 8636 // TODO: More simplifications are possible here. 8637 8638 // Recursively simplify until we either hit a recursion limit or nothing 8639 // changes. 8640 if (Changed) 8641 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8642 8643 return Changed; 8644 8645 trivially_true: 8646 // Return 0 == 0. 8647 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8648 Pred = ICmpInst::ICMP_EQ; 8649 return true; 8650 8651 trivially_false: 8652 // Return 0 != 0. 8653 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8654 Pred = ICmpInst::ICMP_NE; 8655 return true; 8656 } 8657 8658 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8659 return getSignedRangeMax(S).isNegative(); 8660 } 8661 8662 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8663 return getSignedRangeMin(S).isStrictlyPositive(); 8664 } 8665 8666 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8667 return !getSignedRangeMin(S).isNegative(); 8668 } 8669 8670 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8671 return !getSignedRangeMax(S).isStrictlyPositive(); 8672 } 8673 8674 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8675 return isKnownNegative(S) || isKnownPositive(S); 8676 } 8677 8678 std::pair<const SCEV *, const SCEV *> 8679 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8680 // Compute SCEV on entry of loop L. 8681 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8682 if (Start == getCouldNotCompute()) 8683 return { Start, Start }; 8684 // Compute post increment SCEV for loop L. 8685 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8686 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8687 return { Start, PostInc }; 8688 } 8689 8690 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8691 const SCEV *LHS, const SCEV *RHS) { 8692 // First collect all loops. 8693 SmallPtrSet<const Loop *, 8> LoopsUsed; 8694 getUsedLoops(LHS, LoopsUsed); 8695 getUsedLoops(RHS, LoopsUsed); 8696 8697 if (LoopsUsed.empty()) 8698 return false; 8699 8700 // Domination relationship must be a linear order on collected loops. 8701 #ifndef NDEBUG 8702 for (auto *L1 : LoopsUsed) 8703 for (auto *L2 : LoopsUsed) 8704 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8705 DT.dominates(L2->getHeader(), L1->getHeader())) && 8706 "Domination relationship is not a linear order"); 8707 #endif 8708 8709 const Loop *MDL = *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8710 [&](const Loop *L1, const Loop *L2) { 8711 return DT.dominates(L1->getHeader(), L2->getHeader()); 8712 }); 8713 8714 // Get init and post increment value for LHS. 8715 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 8716 // if LHS contains unknown non-invariant SCEV then bail out. 8717 if (SplitLHS.first == getCouldNotCompute()) 8718 return false; 8719 assert (SplitLHS.first != getCouldNotCompute() && "Unexpected CNC"); 8720 // Get init and post increment value for RHS. 8721 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 8722 // if RHS contains unknown non-invariant SCEV then bail out. 8723 if (SplitRHS.first == getCouldNotCompute()) 8724 return false; 8725 assert (SplitRHS.first != getCouldNotCompute() && "Unexpected CNC"); 8726 // It is possible that init SCEV contains an invariant load but it does 8727 // not dominate MDL and is not available at MDL loop entry, so we should 8728 // check it here. 8729 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 8730 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 8731 return false; 8732 8733 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 8734 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 8735 SplitRHS.second); 8736 } 8737 8738 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 8739 const SCEV *LHS, const SCEV *RHS) { 8740 // Canonicalize the inputs first. 8741 (void)SimplifyICmpOperands(Pred, LHS, RHS); 8742 8743 if (isKnownViaInduction(Pred, LHS, RHS)) 8744 return true; 8745 8746 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 8747 return true; 8748 8749 // Otherwise see what can be done with some simple reasoning. 8750 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 8751 } 8752 8753 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 8754 const SCEVAddRecExpr *LHS, 8755 const SCEV *RHS) { 8756 const Loop *L = LHS->getLoop(); 8757 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 8758 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 8759 } 8760 8761 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 8762 ICmpInst::Predicate Pred, 8763 bool &Increasing) { 8764 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 8765 8766 #ifndef NDEBUG 8767 // Verify an invariant: inverting the predicate should turn a monotonically 8768 // increasing change to a monotonically decreasing one, and vice versa. 8769 bool IncreasingSwapped; 8770 bool ResultSwapped = isMonotonicPredicateImpl( 8771 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 8772 8773 assert(Result == ResultSwapped && "should be able to analyze both!"); 8774 if (ResultSwapped) 8775 assert(Increasing == !IncreasingSwapped && 8776 "monotonicity should flip as we flip the predicate"); 8777 #endif 8778 8779 return Result; 8780 } 8781 8782 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 8783 ICmpInst::Predicate Pred, 8784 bool &Increasing) { 8785 8786 // A zero step value for LHS means the induction variable is essentially a 8787 // loop invariant value. We don't really depend on the predicate actually 8788 // flipping from false to true (for increasing predicates, and the other way 8789 // around for decreasing predicates), all we care about is that *if* the 8790 // predicate changes then it only changes from false to true. 8791 // 8792 // A zero step value in itself is not very useful, but there may be places 8793 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 8794 // as general as possible. 8795 8796 switch (Pred) { 8797 default: 8798 return false; // Conservative answer 8799 8800 case ICmpInst::ICMP_UGT: 8801 case ICmpInst::ICMP_UGE: 8802 case ICmpInst::ICMP_ULT: 8803 case ICmpInst::ICMP_ULE: 8804 if (!LHS->hasNoUnsignedWrap()) 8805 return false; 8806 8807 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 8808 return true; 8809 8810 case ICmpInst::ICMP_SGT: 8811 case ICmpInst::ICMP_SGE: 8812 case ICmpInst::ICMP_SLT: 8813 case ICmpInst::ICMP_SLE: { 8814 if (!LHS->hasNoSignedWrap()) 8815 return false; 8816 8817 const SCEV *Step = LHS->getStepRecurrence(*this); 8818 8819 if (isKnownNonNegative(Step)) { 8820 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 8821 return true; 8822 } 8823 8824 if (isKnownNonPositive(Step)) { 8825 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 8826 return true; 8827 } 8828 8829 return false; 8830 } 8831 8832 } 8833 8834 llvm_unreachable("switch has default clause!"); 8835 } 8836 8837 bool ScalarEvolution::isLoopInvariantPredicate( 8838 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 8839 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 8840 const SCEV *&InvariantRHS) { 8841 8842 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 8843 if (!isLoopInvariant(RHS, L)) { 8844 if (!isLoopInvariant(LHS, L)) 8845 return false; 8846 8847 std::swap(LHS, RHS); 8848 Pred = ICmpInst::getSwappedPredicate(Pred); 8849 } 8850 8851 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8852 if (!ArLHS || ArLHS->getLoop() != L) 8853 return false; 8854 8855 bool Increasing; 8856 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 8857 return false; 8858 8859 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 8860 // true as the loop iterates, and the backedge is control dependent on 8861 // "ArLHS `Pred` RHS" == true then we can reason as follows: 8862 // 8863 // * if the predicate was false in the first iteration then the predicate 8864 // is never evaluated again, since the loop exits without taking the 8865 // backedge. 8866 // * if the predicate was true in the first iteration then it will 8867 // continue to be true for all future iterations since it is 8868 // monotonically increasing. 8869 // 8870 // For both the above possibilities, we can replace the loop varying 8871 // predicate with its value on the first iteration of the loop (which is 8872 // loop invariant). 8873 // 8874 // A similar reasoning applies for a monotonically decreasing predicate, by 8875 // replacing true with false and false with true in the above two bullets. 8876 8877 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 8878 8879 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 8880 return false; 8881 8882 InvariantPred = Pred; 8883 InvariantLHS = ArLHS->getStart(); 8884 InvariantRHS = RHS; 8885 return true; 8886 } 8887 8888 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 8889 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8890 if (HasSameValue(LHS, RHS)) 8891 return ICmpInst::isTrueWhenEqual(Pred); 8892 8893 // This code is split out from isKnownPredicate because it is called from 8894 // within isLoopEntryGuardedByCond. 8895 8896 auto CheckRanges = 8897 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 8898 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 8899 .contains(RangeLHS); 8900 }; 8901 8902 // The check at the top of the function catches the case where the values are 8903 // known to be equal. 8904 if (Pred == CmpInst::ICMP_EQ) 8905 return false; 8906 8907 if (Pred == CmpInst::ICMP_NE) 8908 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 8909 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 8910 isKnownNonZero(getMinusSCEV(LHS, RHS)); 8911 8912 if (CmpInst::isSigned(Pred)) 8913 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 8914 8915 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 8916 } 8917 8918 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 8919 const SCEV *LHS, 8920 const SCEV *RHS) { 8921 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 8922 // Return Y via OutY. 8923 auto MatchBinaryAddToConst = 8924 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 8925 SCEV::NoWrapFlags ExpectedFlags) { 8926 const SCEV *NonConstOp, *ConstOp; 8927 SCEV::NoWrapFlags FlagsPresent; 8928 8929 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 8930 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 8931 return false; 8932 8933 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 8934 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 8935 }; 8936 8937 APInt C; 8938 8939 switch (Pred) { 8940 default: 8941 break; 8942 8943 case ICmpInst::ICMP_SGE: 8944 std::swap(LHS, RHS); 8945 LLVM_FALLTHROUGH; 8946 case ICmpInst::ICMP_SLE: 8947 // X s<= (X + C)<nsw> if C >= 0 8948 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 8949 return true; 8950 8951 // (X + C)<nsw> s<= X if C <= 0 8952 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 8953 !C.isStrictlyPositive()) 8954 return true; 8955 break; 8956 8957 case ICmpInst::ICMP_SGT: 8958 std::swap(LHS, RHS); 8959 LLVM_FALLTHROUGH; 8960 case ICmpInst::ICMP_SLT: 8961 // X s< (X + C)<nsw> if C > 0 8962 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 8963 C.isStrictlyPositive()) 8964 return true; 8965 8966 // (X + C)<nsw> s< X if C < 0 8967 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 8968 return true; 8969 break; 8970 } 8971 8972 return false; 8973 } 8974 8975 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 8976 const SCEV *LHS, 8977 const SCEV *RHS) { 8978 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 8979 return false; 8980 8981 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 8982 // the stack can result in exponential time complexity. 8983 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 8984 8985 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 8986 // 8987 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 8988 // isKnownPredicate. isKnownPredicate is more powerful, but also more 8989 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 8990 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 8991 // use isKnownPredicate later if needed. 8992 return isKnownNonNegative(RHS) && 8993 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 8994 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 8995 } 8996 8997 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 8998 ICmpInst::Predicate Pred, 8999 const SCEV *LHS, const SCEV *RHS) { 9000 // No need to even try if we know the module has no guards. 9001 if (!HasGuards) 9002 return false; 9003 9004 return any_of(*BB, [&](Instruction &I) { 9005 using namespace llvm::PatternMatch; 9006 9007 Value *Condition; 9008 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9009 m_Value(Condition))) && 9010 isImpliedCond(Pred, LHS, RHS, Condition, false); 9011 }); 9012 } 9013 9014 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9015 /// protected by a conditional between LHS and RHS. This is used to 9016 /// to eliminate casts. 9017 bool 9018 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9019 ICmpInst::Predicate Pred, 9020 const SCEV *LHS, const SCEV *RHS) { 9021 // Interpret a null as meaning no loop, where there is obviously no guard 9022 // (interprocedural conditions notwithstanding). 9023 if (!L) return true; 9024 9025 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9026 return true; 9027 9028 BasicBlock *Latch = L->getLoopLatch(); 9029 if (!Latch) 9030 return false; 9031 9032 BranchInst *LoopContinuePredicate = 9033 dyn_cast<BranchInst>(Latch->getTerminator()); 9034 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9035 isImpliedCond(Pred, LHS, RHS, 9036 LoopContinuePredicate->getCondition(), 9037 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9038 return true; 9039 9040 // We don't want more than one activation of the following loops on the stack 9041 // -- that can lead to O(n!) time complexity. 9042 if (WalkingBEDominatingConds) 9043 return false; 9044 9045 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9046 9047 // See if we can exploit a trip count to prove the predicate. 9048 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9049 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9050 if (LatchBECount != getCouldNotCompute()) { 9051 // We know that Latch branches back to the loop header exactly 9052 // LatchBECount times. This means the backdege condition at Latch is 9053 // equivalent to "{0,+,1} u< LatchBECount". 9054 Type *Ty = LatchBECount->getType(); 9055 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9056 const SCEV *LoopCounter = 9057 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9058 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9059 LatchBECount)) 9060 return true; 9061 } 9062 9063 // Check conditions due to any @llvm.assume intrinsics. 9064 for (auto &AssumeVH : AC.assumptions()) { 9065 if (!AssumeVH) 9066 continue; 9067 auto *CI = cast<CallInst>(AssumeVH); 9068 if (!DT.dominates(CI, Latch->getTerminator())) 9069 continue; 9070 9071 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9072 return true; 9073 } 9074 9075 // If the loop is not reachable from the entry block, we risk running into an 9076 // infinite loop as we walk up into the dom tree. These loops do not matter 9077 // anyway, so we just return a conservative answer when we see them. 9078 if (!DT.isReachableFromEntry(L->getHeader())) 9079 return false; 9080 9081 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9082 return true; 9083 9084 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9085 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9086 assert(DTN && "should reach the loop header before reaching the root!"); 9087 9088 BasicBlock *BB = DTN->getBlock(); 9089 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9090 return true; 9091 9092 BasicBlock *PBB = BB->getSinglePredecessor(); 9093 if (!PBB) 9094 continue; 9095 9096 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9097 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9098 continue; 9099 9100 Value *Condition = ContinuePredicate->getCondition(); 9101 9102 // If we have an edge `E` within the loop body that dominates the only 9103 // latch, the condition guarding `E` also guards the backedge. This 9104 // reasoning works only for loops with a single latch. 9105 9106 BasicBlockEdge DominatingEdge(PBB, BB); 9107 if (DominatingEdge.isSingleEdge()) { 9108 // We're constructively (and conservatively) enumerating edges within the 9109 // loop body that dominate the latch. The dominator tree better agree 9110 // with us on this: 9111 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9112 9113 if (isImpliedCond(Pred, LHS, RHS, Condition, 9114 BB != ContinuePredicate->getSuccessor(0))) 9115 return true; 9116 } 9117 } 9118 9119 return false; 9120 } 9121 9122 bool 9123 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9124 ICmpInst::Predicate Pred, 9125 const SCEV *LHS, const SCEV *RHS) { 9126 // Interpret a null as meaning no loop, where there is obviously no guard 9127 // (interprocedural conditions notwithstanding). 9128 if (!L) return false; 9129 9130 // Both LHS and RHS must be available at loop entry. 9131 assert(isAvailableAtLoopEntry(LHS, L) && 9132 "LHS is not available at Loop Entry"); 9133 assert(isAvailableAtLoopEntry(RHS, L) && 9134 "RHS is not available at Loop Entry"); 9135 9136 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9137 return true; 9138 9139 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9140 // the facts (a >= b && a != b) separately. A typical situation is when the 9141 // non-strict comparison is known from ranges and non-equality is known from 9142 // dominating predicates. If we are proving strict comparison, we always try 9143 // to prove non-equality and non-strict comparison separately. 9144 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9145 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9146 bool ProvedNonStrictComparison = false; 9147 bool ProvedNonEquality = false; 9148 9149 if (ProvingStrictComparison) { 9150 ProvedNonStrictComparison = 9151 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9152 ProvedNonEquality = 9153 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9154 if (ProvedNonStrictComparison && ProvedNonEquality) 9155 return true; 9156 } 9157 9158 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9159 auto ProveViaGuard = [&](BasicBlock *Block) { 9160 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9161 return true; 9162 if (ProvingStrictComparison) { 9163 if (!ProvedNonStrictComparison) 9164 ProvedNonStrictComparison = 9165 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9166 if (!ProvedNonEquality) 9167 ProvedNonEquality = 9168 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9169 if (ProvedNonStrictComparison && ProvedNonEquality) 9170 return true; 9171 } 9172 return false; 9173 }; 9174 9175 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9176 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9177 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9178 return true; 9179 if (ProvingStrictComparison) { 9180 if (!ProvedNonStrictComparison) 9181 ProvedNonStrictComparison = 9182 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9183 if (!ProvedNonEquality) 9184 ProvedNonEquality = 9185 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9186 if (ProvedNonStrictComparison && ProvedNonEquality) 9187 return true; 9188 } 9189 return false; 9190 }; 9191 9192 // Starting at the loop predecessor, climb up the predecessor chain, as long 9193 // as there are predecessors that can be found that have unique successors 9194 // leading to the original header. 9195 for (std::pair<BasicBlock *, BasicBlock *> 9196 Pair(L->getLoopPredecessor(), L->getHeader()); 9197 Pair.first; 9198 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9199 9200 if (ProveViaGuard(Pair.first)) 9201 return true; 9202 9203 BranchInst *LoopEntryPredicate = 9204 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9205 if (!LoopEntryPredicate || 9206 LoopEntryPredicate->isUnconditional()) 9207 continue; 9208 9209 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9210 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9211 return true; 9212 } 9213 9214 // Check conditions due to any @llvm.assume intrinsics. 9215 for (auto &AssumeVH : AC.assumptions()) { 9216 if (!AssumeVH) 9217 continue; 9218 auto *CI = cast<CallInst>(AssumeVH); 9219 if (!DT.dominates(CI, L->getHeader())) 9220 continue; 9221 9222 if (ProveViaCond(CI->getArgOperand(0), false)) 9223 return true; 9224 } 9225 9226 return false; 9227 } 9228 9229 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9230 const SCEV *LHS, const SCEV *RHS, 9231 Value *FoundCondValue, 9232 bool Inverse) { 9233 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9234 return false; 9235 9236 auto ClearOnExit = 9237 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9238 9239 // Recursively handle And and Or conditions. 9240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9241 if (BO->getOpcode() == Instruction::And) { 9242 if (!Inverse) 9243 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9244 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9245 } else if (BO->getOpcode() == Instruction::Or) { 9246 if (Inverse) 9247 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9248 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9249 } 9250 } 9251 9252 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9253 if (!ICI) return false; 9254 9255 // Now that we found a conditional branch that dominates the loop or controls 9256 // the loop latch. Check to see if it is the comparison we are looking for. 9257 ICmpInst::Predicate FoundPred; 9258 if (Inverse) 9259 FoundPred = ICI->getInversePredicate(); 9260 else 9261 FoundPred = ICI->getPredicate(); 9262 9263 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9264 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9265 9266 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9267 } 9268 9269 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9270 const SCEV *RHS, 9271 ICmpInst::Predicate FoundPred, 9272 const SCEV *FoundLHS, 9273 const SCEV *FoundRHS) { 9274 // Balance the types. 9275 if (getTypeSizeInBits(LHS->getType()) < 9276 getTypeSizeInBits(FoundLHS->getType())) { 9277 if (CmpInst::isSigned(Pred)) { 9278 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9279 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9280 } else { 9281 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9282 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9283 } 9284 } else if (getTypeSizeInBits(LHS->getType()) > 9285 getTypeSizeInBits(FoundLHS->getType())) { 9286 if (CmpInst::isSigned(FoundPred)) { 9287 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9288 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9289 } else { 9290 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9291 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9292 } 9293 } 9294 9295 // Canonicalize the query to match the way instcombine will have 9296 // canonicalized the comparison. 9297 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9298 if (LHS == RHS) 9299 return CmpInst::isTrueWhenEqual(Pred); 9300 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9301 if (FoundLHS == FoundRHS) 9302 return CmpInst::isFalseWhenEqual(FoundPred); 9303 9304 // Check to see if we can make the LHS or RHS match. 9305 if (LHS == FoundRHS || RHS == FoundLHS) { 9306 if (isa<SCEVConstant>(RHS)) { 9307 std::swap(FoundLHS, FoundRHS); 9308 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9309 } else { 9310 std::swap(LHS, RHS); 9311 Pred = ICmpInst::getSwappedPredicate(Pred); 9312 } 9313 } 9314 9315 // Check whether the found predicate is the same as the desired predicate. 9316 if (FoundPred == Pred) 9317 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9318 9319 // Check whether swapping the found predicate makes it the same as the 9320 // desired predicate. 9321 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9322 if (isa<SCEVConstant>(RHS)) 9323 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9324 else 9325 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9326 RHS, LHS, FoundLHS, FoundRHS); 9327 } 9328 9329 // Unsigned comparison is the same as signed comparison when both the operands 9330 // are non-negative. 9331 if (CmpInst::isUnsigned(FoundPred) && 9332 CmpInst::getSignedPredicate(FoundPred) == Pred && 9333 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9334 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9335 9336 // Check if we can make progress by sharpening ranges. 9337 if (FoundPred == ICmpInst::ICMP_NE && 9338 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9339 9340 const SCEVConstant *C = nullptr; 9341 const SCEV *V = nullptr; 9342 9343 if (isa<SCEVConstant>(FoundLHS)) { 9344 C = cast<SCEVConstant>(FoundLHS); 9345 V = FoundRHS; 9346 } else { 9347 C = cast<SCEVConstant>(FoundRHS); 9348 V = FoundLHS; 9349 } 9350 9351 // The guarding predicate tells us that C != V. If the known range 9352 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9353 // range we consider has to correspond to same signedness as the 9354 // predicate we're interested in folding. 9355 9356 APInt Min = ICmpInst::isSigned(Pred) ? 9357 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9358 9359 if (Min == C->getAPInt()) { 9360 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9361 // This is true even if (Min + 1) wraps around -- in case of 9362 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9363 9364 APInt SharperMin = Min + 1; 9365 9366 switch (Pred) { 9367 case ICmpInst::ICMP_SGE: 9368 case ICmpInst::ICMP_UGE: 9369 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9370 // RHS, we're done. 9371 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9372 getConstant(SharperMin))) 9373 return true; 9374 LLVM_FALLTHROUGH; 9375 9376 case ICmpInst::ICMP_SGT: 9377 case ICmpInst::ICMP_UGT: 9378 // We know from the range information that (V `Pred` Min || 9379 // V == Min). We know from the guarding condition that !(V 9380 // == Min). This gives us 9381 // 9382 // V `Pred` Min || V == Min && !(V == Min) 9383 // => V `Pred` Min 9384 // 9385 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9386 9387 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9388 return true; 9389 LLVM_FALLTHROUGH; 9390 9391 default: 9392 // No change 9393 break; 9394 } 9395 } 9396 } 9397 9398 // Check whether the actual condition is beyond sufficient. 9399 if (FoundPred == ICmpInst::ICMP_EQ) 9400 if (ICmpInst::isTrueWhenEqual(Pred)) 9401 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9402 return true; 9403 if (Pred == ICmpInst::ICMP_NE) 9404 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9405 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9406 return true; 9407 9408 // Otherwise assume the worst. 9409 return false; 9410 } 9411 9412 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9413 const SCEV *&L, const SCEV *&R, 9414 SCEV::NoWrapFlags &Flags) { 9415 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9416 if (!AE || AE->getNumOperands() != 2) 9417 return false; 9418 9419 L = AE->getOperand(0); 9420 R = AE->getOperand(1); 9421 Flags = AE->getNoWrapFlags(); 9422 return true; 9423 } 9424 9425 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9426 const SCEV *Less) { 9427 // We avoid subtracting expressions here because this function is usually 9428 // fairly deep in the call stack (i.e. is called many times). 9429 9430 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9431 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9432 const auto *MAR = cast<SCEVAddRecExpr>(More); 9433 9434 if (LAR->getLoop() != MAR->getLoop()) 9435 return None; 9436 9437 // We look at affine expressions only; not for correctness but to keep 9438 // getStepRecurrence cheap. 9439 if (!LAR->isAffine() || !MAR->isAffine()) 9440 return None; 9441 9442 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9443 return None; 9444 9445 Less = LAR->getStart(); 9446 More = MAR->getStart(); 9447 9448 // fall through 9449 } 9450 9451 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9452 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9453 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9454 return M - L; 9455 } 9456 9457 const SCEV *L, *R; 9458 SCEV::NoWrapFlags Flags; 9459 if (splitBinaryAdd(Less, L, R, Flags)) 9460 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9461 if (R == More) 9462 return -(LC->getAPInt()); 9463 9464 if (splitBinaryAdd(More, L, R, Flags)) 9465 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 9466 if (R == Less) 9467 return LC->getAPInt(); 9468 9469 return None; 9470 } 9471 9472 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9473 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9474 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9475 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9476 return false; 9477 9478 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9479 if (!AddRecLHS) 9480 return false; 9481 9482 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9483 if (!AddRecFoundLHS) 9484 return false; 9485 9486 // We'd like to let SCEV reason about control dependencies, so we constrain 9487 // both the inequalities to be about add recurrences on the same loop. This 9488 // way we can use isLoopEntryGuardedByCond later. 9489 9490 const Loop *L = AddRecFoundLHS->getLoop(); 9491 if (L != AddRecLHS->getLoop()) 9492 return false; 9493 9494 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9495 // 9496 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9497 // ... (2) 9498 // 9499 // Informal proof for (2), assuming (1) [*]: 9500 // 9501 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9502 // 9503 // Then 9504 // 9505 // FoundLHS s< FoundRHS s< INT_MIN - C 9506 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9507 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9508 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9509 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9510 // <=> FoundLHS + C s< FoundRHS + C 9511 // 9512 // [*]: (1) can be proved by ruling out overflow. 9513 // 9514 // [**]: This can be proved by analyzing all the four possibilities: 9515 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9516 // (A s>= 0, B s>= 0). 9517 // 9518 // Note: 9519 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9520 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9521 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9522 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9523 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9524 // C)". 9525 9526 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9527 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9528 if (!LDiff || !RDiff || *LDiff != *RDiff) 9529 return false; 9530 9531 if (LDiff->isMinValue()) 9532 return true; 9533 9534 APInt FoundRHSLimit; 9535 9536 if (Pred == CmpInst::ICMP_ULT) { 9537 FoundRHSLimit = -(*RDiff); 9538 } else { 9539 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9540 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9541 } 9542 9543 // Try to prove (1) or (2), as needed. 9544 return isAvailableAtLoopEntry(FoundRHS, L) && 9545 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9546 getConstant(FoundRHSLimit)); 9547 } 9548 9549 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9550 const SCEV *LHS, const SCEV *RHS, 9551 const SCEV *FoundLHS, 9552 const SCEV *FoundRHS) { 9553 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9554 return true; 9555 9556 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9557 return true; 9558 9559 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9560 FoundLHS, FoundRHS) || 9561 // ~x < ~y --> x > y 9562 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9563 getNotSCEV(FoundRHS), 9564 getNotSCEV(FoundLHS)); 9565 } 9566 9567 /// If Expr computes ~A, return A else return nullptr 9568 static const SCEV *MatchNotExpr(const SCEV *Expr) { 9569 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 9570 if (!Add || Add->getNumOperands() != 2 || 9571 !Add->getOperand(0)->isAllOnesValue()) 9572 return nullptr; 9573 9574 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 9575 if (!AddRHS || AddRHS->getNumOperands() != 2 || 9576 !AddRHS->getOperand(0)->isAllOnesValue()) 9577 return nullptr; 9578 9579 return AddRHS->getOperand(1); 9580 } 9581 9582 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 9583 template<typename MaxExprType> 9584 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 9585 const SCEV *Candidate) { 9586 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 9587 if (!MaxExpr) return false; 9588 9589 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 9590 } 9591 9592 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 9593 template<typename MaxExprType> 9594 static bool IsMinConsistingOf(ScalarEvolution &SE, 9595 const SCEV *MaybeMinExpr, 9596 const SCEV *Candidate) { 9597 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 9598 if (!MaybeMaxExpr) 9599 return false; 9600 9601 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 9602 } 9603 9604 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9605 ICmpInst::Predicate Pred, 9606 const SCEV *LHS, const SCEV *RHS) { 9607 // If both sides are affine addrecs for the same loop, with equal 9608 // steps, and we know the recurrences don't wrap, then we only 9609 // need to check the predicate on the starting values. 9610 9611 if (!ICmpInst::isRelational(Pred)) 9612 return false; 9613 9614 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 9615 if (!LAR) 9616 return false; 9617 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9618 if (!RAR) 9619 return false; 9620 if (LAR->getLoop() != RAR->getLoop()) 9621 return false; 9622 if (!LAR->isAffine() || !RAR->isAffine()) 9623 return false; 9624 9625 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 9626 return false; 9627 9628 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 9629 SCEV::FlagNSW : SCEV::FlagNUW; 9630 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 9631 return false; 9632 9633 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 9634 } 9635 9636 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 9637 /// expression? 9638 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 9639 ICmpInst::Predicate Pred, 9640 const SCEV *LHS, const SCEV *RHS) { 9641 switch (Pred) { 9642 default: 9643 return false; 9644 9645 case ICmpInst::ICMP_SGE: 9646 std::swap(LHS, RHS); 9647 LLVM_FALLTHROUGH; 9648 case ICmpInst::ICMP_SLE: 9649 return 9650 // min(A, ...) <= A 9651 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 9652 // A <= max(A, ...) 9653 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 9654 9655 case ICmpInst::ICMP_UGE: 9656 std::swap(LHS, RHS); 9657 LLVM_FALLTHROUGH; 9658 case ICmpInst::ICMP_ULE: 9659 return 9660 // min(A, ...) <= A 9661 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 9662 // A <= max(A, ...) 9663 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 9664 } 9665 9666 llvm_unreachable("covered switch fell through?!"); 9667 } 9668 9669 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 9670 const SCEV *LHS, const SCEV *RHS, 9671 const SCEV *FoundLHS, 9672 const SCEV *FoundRHS, 9673 unsigned Depth) { 9674 assert(getTypeSizeInBits(LHS->getType()) == 9675 getTypeSizeInBits(RHS->getType()) && 9676 "LHS and RHS have different sizes?"); 9677 assert(getTypeSizeInBits(FoundLHS->getType()) == 9678 getTypeSizeInBits(FoundRHS->getType()) && 9679 "FoundLHS and FoundRHS have different sizes?"); 9680 // We want to avoid hurting the compile time with analysis of too big trees. 9681 if (Depth > MaxSCEVOperationsImplicationDepth) 9682 return false; 9683 // We only want to work with ICMP_SGT comparison so far. 9684 // TODO: Extend to ICMP_UGT? 9685 if (Pred == ICmpInst::ICMP_SLT) { 9686 Pred = ICmpInst::ICMP_SGT; 9687 std::swap(LHS, RHS); 9688 std::swap(FoundLHS, FoundRHS); 9689 } 9690 if (Pred != ICmpInst::ICMP_SGT) 9691 return false; 9692 9693 auto GetOpFromSExt = [&](const SCEV *S) { 9694 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 9695 return Ext->getOperand(); 9696 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 9697 // the constant in some cases. 9698 return S; 9699 }; 9700 9701 // Acquire values from extensions. 9702 auto *OrigFoundLHS = FoundLHS; 9703 LHS = GetOpFromSExt(LHS); 9704 FoundLHS = GetOpFromSExt(FoundLHS); 9705 9706 // Is the SGT predicate can be proved trivially or using the found context. 9707 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 9708 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 9709 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 9710 FoundRHS, Depth + 1); 9711 }; 9712 9713 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 9714 // We want to avoid creation of any new non-constant SCEV. Since we are 9715 // going to compare the operands to RHS, we should be certain that we don't 9716 // need any size extensions for this. So let's decline all cases when the 9717 // sizes of types of LHS and RHS do not match. 9718 // TODO: Maybe try to get RHS from sext to catch more cases? 9719 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 9720 return false; 9721 9722 // Should not overflow. 9723 if (!LHSAddExpr->hasNoSignedWrap()) 9724 return false; 9725 9726 auto *LL = LHSAddExpr->getOperand(0); 9727 auto *LR = LHSAddExpr->getOperand(1); 9728 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 9729 9730 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 9731 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 9732 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 9733 }; 9734 // Try to prove the following rule: 9735 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 9736 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 9737 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 9738 return true; 9739 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 9740 Value *LL, *LR; 9741 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 9742 9743 using namespace llvm::PatternMatch; 9744 9745 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 9746 // Rules for division. 9747 // We are going to perform some comparisons with Denominator and its 9748 // derivative expressions. In general case, creating a SCEV for it may 9749 // lead to a complex analysis of the entire graph, and in particular it 9750 // can request trip count recalculation for the same loop. This would 9751 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 9752 // this, we only want to create SCEVs that are constants in this section. 9753 // So we bail if Denominator is not a constant. 9754 if (!isa<ConstantInt>(LR)) 9755 return false; 9756 9757 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 9758 9759 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 9760 // then a SCEV for the numerator already exists and matches with FoundLHS. 9761 auto *Numerator = getExistingSCEV(LL); 9762 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 9763 return false; 9764 9765 // Make sure that the numerator matches with FoundLHS and the denominator 9766 // is positive. 9767 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 9768 return false; 9769 9770 auto *DTy = Denominator->getType(); 9771 auto *FRHSTy = FoundRHS->getType(); 9772 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 9773 // One of types is a pointer and another one is not. We cannot extend 9774 // them properly to a wider type, so let us just reject this case. 9775 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 9776 // to avoid this check. 9777 return false; 9778 9779 // Given that: 9780 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 9781 auto *WTy = getWiderType(DTy, FRHSTy); 9782 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 9783 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 9784 9785 // Try to prove the following rule: 9786 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 9787 // For example, given that FoundLHS > 2. It means that FoundLHS is at 9788 // least 3. If we divide it by Denominator < 4, we will have at least 1. 9789 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 9790 if (isKnownNonPositive(RHS) && 9791 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 9792 return true; 9793 9794 // Try to prove the following rule: 9795 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 9796 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 9797 // If we divide it by Denominator > 2, then: 9798 // 1. If FoundLHS is negative, then the result is 0. 9799 // 2. If FoundLHS is non-negative, then the result is non-negative. 9800 // Anyways, the result is non-negative. 9801 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 9802 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 9803 if (isKnownNegative(RHS) && 9804 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 9805 return true; 9806 } 9807 } 9808 9809 return false; 9810 } 9811 9812 bool 9813 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 9814 const SCEV *LHS, const SCEV *RHS) { 9815 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 9816 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 9817 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 9818 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 9819 } 9820 9821 bool 9822 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 9823 const SCEV *LHS, const SCEV *RHS, 9824 const SCEV *FoundLHS, 9825 const SCEV *FoundRHS) { 9826 switch (Pred) { 9827 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 9828 case ICmpInst::ICMP_EQ: 9829 case ICmpInst::ICMP_NE: 9830 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 9831 return true; 9832 break; 9833 case ICmpInst::ICMP_SLT: 9834 case ICmpInst::ICMP_SLE: 9835 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 9836 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 9837 return true; 9838 break; 9839 case ICmpInst::ICMP_SGT: 9840 case ICmpInst::ICMP_SGE: 9841 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 9842 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 9843 return true; 9844 break; 9845 case ICmpInst::ICMP_ULT: 9846 case ICmpInst::ICMP_ULE: 9847 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 9848 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 9849 return true; 9850 break; 9851 case ICmpInst::ICMP_UGT: 9852 case ICmpInst::ICMP_UGE: 9853 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 9854 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 9855 return true; 9856 break; 9857 } 9858 9859 // Maybe it can be proved via operations? 9860 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9861 return true; 9862 9863 return false; 9864 } 9865 9866 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 9867 const SCEV *LHS, 9868 const SCEV *RHS, 9869 const SCEV *FoundLHS, 9870 const SCEV *FoundRHS) { 9871 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 9872 // The restriction on `FoundRHS` be lifted easily -- it exists only to 9873 // reduce the compile time impact of this optimization. 9874 return false; 9875 9876 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 9877 if (!Addend) 9878 return false; 9879 9880 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 9881 9882 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 9883 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 9884 ConstantRange FoundLHSRange = 9885 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 9886 9887 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 9888 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 9889 9890 // We can also compute the range of values for `LHS` that satisfy the 9891 // consequent, "`LHS` `Pred` `RHS`": 9892 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 9893 ConstantRange SatisfyingLHSRange = 9894 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 9895 9896 // The antecedent implies the consequent if every value of `LHS` that 9897 // satisfies the antecedent also satisfies the consequent. 9898 return SatisfyingLHSRange.contains(LHSRange); 9899 } 9900 9901 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 9902 bool IsSigned, bool NoWrap) { 9903 assert(isKnownPositive(Stride) && "Positive stride expected!"); 9904 9905 if (NoWrap) return false; 9906 9907 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9908 const SCEV *One = getOne(Stride->getType()); 9909 9910 if (IsSigned) { 9911 APInt MaxRHS = getSignedRangeMax(RHS); 9912 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 9913 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9914 9915 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 9916 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 9917 } 9918 9919 APInt MaxRHS = getUnsignedRangeMax(RHS); 9920 APInt MaxValue = APInt::getMaxValue(BitWidth); 9921 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9922 9923 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 9924 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 9925 } 9926 9927 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 9928 bool IsSigned, bool NoWrap) { 9929 if (NoWrap) return false; 9930 9931 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 9932 const SCEV *One = getOne(Stride->getType()); 9933 9934 if (IsSigned) { 9935 APInt MinRHS = getSignedRangeMin(RHS); 9936 APInt MinValue = APInt::getSignedMinValue(BitWidth); 9937 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 9938 9939 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 9940 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 9941 } 9942 9943 APInt MinRHS = getUnsignedRangeMin(RHS); 9944 APInt MinValue = APInt::getMinValue(BitWidth); 9945 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 9946 9947 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 9948 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 9949 } 9950 9951 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 9952 bool Equality) { 9953 const SCEV *One = getOne(Step->getType()); 9954 Delta = Equality ? getAddExpr(Delta, Step) 9955 : getAddExpr(Delta, getMinusSCEV(Step, One)); 9956 return getUDivExpr(Delta, Step); 9957 } 9958 9959 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 9960 const SCEV *Stride, 9961 const SCEV *End, 9962 unsigned BitWidth, 9963 bool IsSigned) { 9964 9965 assert(!isKnownNonPositive(Stride) && 9966 "Stride is expected strictly positive!"); 9967 // Calculate the maximum backedge count based on the range of values 9968 // permitted by Start, End, and Stride. 9969 const SCEV *MaxBECount; 9970 APInt MinStart = 9971 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 9972 9973 APInt StrideForMaxBECount = 9974 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 9975 9976 // We already know that the stride is positive, so we paper over conservatism 9977 // in our range computation by forcing StrideForMaxBECount to be at least one. 9978 // In theory this is unnecessary, but we expect MaxBECount to be a 9979 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 9980 // is nothing to constant fold it to). 9981 APInt One(BitWidth, 1, IsSigned); 9982 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 9983 9984 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 9985 : APInt::getMaxValue(BitWidth); 9986 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 9987 9988 // Although End can be a MAX expression we estimate MaxEnd considering only 9989 // the case End = RHS of the loop termination condition. This is safe because 9990 // in the other case (End - Start) is zero, leading to a zero maximum backedge 9991 // taken count. 9992 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 9993 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 9994 9995 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 9996 getConstant(StrideForMaxBECount) /* Step */, 9997 false /* Equality */); 9998 9999 return MaxBECount; 10000 } 10001 10002 ScalarEvolution::ExitLimit 10003 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10004 const Loop *L, bool IsSigned, 10005 bool ControlsExit, bool AllowPredicates) { 10006 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10007 10008 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10009 bool PredicatedIV = false; 10010 10011 if (!IV && AllowPredicates) { 10012 // Try to make this an AddRec using runtime tests, in the first X 10013 // iterations of this loop, where X is the SCEV expression found by the 10014 // algorithm below. 10015 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10016 PredicatedIV = true; 10017 } 10018 10019 // Avoid weird loops 10020 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10021 return getCouldNotCompute(); 10022 10023 bool NoWrap = ControlsExit && 10024 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10025 10026 const SCEV *Stride = IV->getStepRecurrence(*this); 10027 10028 bool PositiveStride = isKnownPositive(Stride); 10029 10030 // Avoid negative or zero stride values. 10031 if (!PositiveStride) { 10032 // We can compute the correct backedge taken count for loops with unknown 10033 // strides if we can prove that the loop is not an infinite loop with side 10034 // effects. Here's the loop structure we are trying to handle - 10035 // 10036 // i = start 10037 // do { 10038 // A[i] = i; 10039 // i += s; 10040 // } while (i < end); 10041 // 10042 // The backedge taken count for such loops is evaluated as - 10043 // (max(end, start + stride) - start - 1) /u stride 10044 // 10045 // The additional preconditions that we need to check to prove correctness 10046 // of the above formula is as follows - 10047 // 10048 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10049 // NoWrap flag). 10050 // b) loop is single exit with no side effects. 10051 // 10052 // 10053 // Precondition a) implies that if the stride is negative, this is a single 10054 // trip loop. The backedge taken count formula reduces to zero in this case. 10055 // 10056 // Precondition b) implies that the unknown stride cannot be zero otherwise 10057 // we have UB. 10058 // 10059 // The positive stride case is the same as isKnownPositive(Stride) returning 10060 // true (original behavior of the function). 10061 // 10062 // We want to make sure that the stride is truly unknown as there are edge 10063 // cases where ScalarEvolution propagates no wrap flags to the 10064 // post-increment/decrement IV even though the increment/decrement operation 10065 // itself is wrapping. The computed backedge taken count may be wrong in 10066 // such cases. This is prevented by checking that the stride is not known to 10067 // be either positive or non-positive. For example, no wrap flags are 10068 // propagated to the post-increment IV of this loop with a trip count of 2 - 10069 // 10070 // unsigned char i; 10071 // for(i=127; i<128; i+=129) 10072 // A[i] = i; 10073 // 10074 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10075 !loopHasNoSideEffects(L)) 10076 return getCouldNotCompute(); 10077 } else if (!Stride->isOne() && 10078 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10079 // Avoid proven overflow cases: this will ensure that the backedge taken 10080 // count will not generate any unsigned overflow. Relaxed no-overflow 10081 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10082 // undefined behaviors like the case of C language. 10083 return getCouldNotCompute(); 10084 10085 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10086 : ICmpInst::ICMP_ULT; 10087 const SCEV *Start = IV->getStart(); 10088 const SCEV *End = RHS; 10089 // When the RHS is not invariant, we do not know the end bound of the loop and 10090 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10091 // calculate the MaxBECount, given the start, stride and max value for the end 10092 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10093 // checked above). 10094 if (!isLoopInvariant(RHS, L)) { 10095 const SCEV *MaxBECount = computeMaxBECountForLT( 10096 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10097 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10098 false /*MaxOrZero*/, Predicates); 10099 } 10100 // If the backedge is taken at least once, then it will be taken 10101 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10102 // is the LHS value of the less-than comparison the first time it is evaluated 10103 // and End is the RHS. 10104 const SCEV *BECountIfBackedgeTaken = 10105 computeBECount(getMinusSCEV(End, Start), Stride, false); 10106 // If the loop entry is guarded by the result of the backedge test of the 10107 // first loop iteration, then we know the backedge will be taken at least 10108 // once and so the backedge taken count is as above. If not then we use the 10109 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10110 // as if the backedge is taken at least once max(End,Start) is End and so the 10111 // result is as above, and if not max(End,Start) is Start so we get a backedge 10112 // count of zero. 10113 const SCEV *BECount; 10114 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10115 BECount = BECountIfBackedgeTaken; 10116 else { 10117 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10118 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10119 } 10120 10121 const SCEV *MaxBECount; 10122 bool MaxOrZero = false; 10123 if (isa<SCEVConstant>(BECount)) 10124 MaxBECount = BECount; 10125 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10126 // If we know exactly how many times the backedge will be taken if it's 10127 // taken at least once, then the backedge count will either be that or 10128 // zero. 10129 MaxBECount = BECountIfBackedgeTaken; 10130 MaxOrZero = true; 10131 } else { 10132 MaxBECount = computeMaxBECountForLT( 10133 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10134 } 10135 10136 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10137 !isa<SCEVCouldNotCompute>(BECount)) 10138 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10139 10140 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10141 } 10142 10143 ScalarEvolution::ExitLimit 10144 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10145 const Loop *L, bool IsSigned, 10146 bool ControlsExit, bool AllowPredicates) { 10147 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10148 // We handle only IV > Invariant 10149 if (!isLoopInvariant(RHS, L)) 10150 return getCouldNotCompute(); 10151 10152 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10153 if (!IV && AllowPredicates) 10154 // Try to make this an AddRec using runtime tests, in the first X 10155 // iterations of this loop, where X is the SCEV expression found by the 10156 // algorithm below. 10157 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10158 10159 // Avoid weird loops 10160 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10161 return getCouldNotCompute(); 10162 10163 bool NoWrap = ControlsExit && 10164 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10165 10166 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10167 10168 // Avoid negative or zero stride values 10169 if (!isKnownPositive(Stride)) 10170 return getCouldNotCompute(); 10171 10172 // Avoid proven overflow cases: this will ensure that the backedge taken count 10173 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10174 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10175 // behaviors like the case of C language. 10176 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10177 return getCouldNotCompute(); 10178 10179 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10180 : ICmpInst::ICMP_UGT; 10181 10182 const SCEV *Start = IV->getStart(); 10183 const SCEV *End = RHS; 10184 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10185 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10186 10187 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10188 10189 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10190 : getUnsignedRangeMax(Start); 10191 10192 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10193 : getUnsignedRangeMin(Stride); 10194 10195 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10196 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10197 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10198 10199 // Although End can be a MIN expression we estimate MinEnd considering only 10200 // the case End = RHS. This is safe because in the other case (Start - End) 10201 // is zero, leading to a zero maximum backedge taken count. 10202 APInt MinEnd = 10203 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10204 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10205 10206 10207 const SCEV *MaxBECount = getCouldNotCompute(); 10208 if (isa<SCEVConstant>(BECount)) 10209 MaxBECount = BECount; 10210 else 10211 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 10212 getConstant(MinStride), false); 10213 10214 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10215 MaxBECount = BECount; 10216 10217 return ExitLimit(BECount, MaxBECount, false, Predicates); 10218 } 10219 10220 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10221 ScalarEvolution &SE) const { 10222 if (Range.isFullSet()) // Infinite loop. 10223 return SE.getCouldNotCompute(); 10224 10225 // If the start is a non-zero constant, shift the range to simplify things. 10226 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10227 if (!SC->getValue()->isZero()) { 10228 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10229 Operands[0] = SE.getZero(SC->getType()); 10230 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10231 getNoWrapFlags(FlagNW)); 10232 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10233 return ShiftedAddRec->getNumIterationsInRange( 10234 Range.subtract(SC->getAPInt()), SE); 10235 // This is strange and shouldn't happen. 10236 return SE.getCouldNotCompute(); 10237 } 10238 10239 // The only time we can solve this is when we have all constant indices. 10240 // Otherwise, we cannot determine the overflow conditions. 10241 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10242 return SE.getCouldNotCompute(); 10243 10244 // Okay at this point we know that all elements of the chrec are constants and 10245 // that the start element is zero. 10246 10247 // First check to see if the range contains zero. If not, the first 10248 // iteration exits. 10249 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10250 if (!Range.contains(APInt(BitWidth, 0))) 10251 return SE.getZero(getType()); 10252 10253 if (isAffine()) { 10254 // If this is an affine expression then we have this situation: 10255 // Solve {0,+,A} in Range === Ax in Range 10256 10257 // We know that zero is in the range. If A is positive then we know that 10258 // the upper value of the range must be the first possible exit value. 10259 // If A is negative then the lower of the range is the last possible loop 10260 // value. Also note that we already checked for a full range. 10261 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10262 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10263 10264 // The exit value should be (End+A)/A. 10265 APInt ExitVal = (End + A).udiv(A); 10266 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10267 10268 // Evaluate at the exit value. If we really did fall out of the valid 10269 // range, then we computed our trip count, otherwise wrap around or other 10270 // things must have happened. 10271 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10272 if (Range.contains(Val->getValue())) 10273 return SE.getCouldNotCompute(); // Something strange happened 10274 10275 // Ensure that the previous value is in the range. This is a sanity check. 10276 assert(Range.contains( 10277 EvaluateConstantChrecAtConstant(this, 10278 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10279 "Linear scev computation is off in a bad way!"); 10280 return SE.getConstant(ExitValue); 10281 } else if (isQuadratic()) { 10282 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 10283 // quadratic equation to solve it. To do this, we must frame our problem in 10284 // terms of figuring out when zero is crossed, instead of when 10285 // Range.getUpper() is crossed. 10286 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 10287 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 10288 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 10289 10290 // Next, solve the constructed addrec 10291 if (auto Roots = 10292 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 10293 const SCEVConstant *R1 = Roots->first; 10294 const SCEVConstant *R2 = Roots->second; 10295 // Pick the smallest positive root value. 10296 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 10297 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 10298 if (!CB->getZExtValue()) 10299 std::swap(R1, R2); // R1 is the minimum root now. 10300 10301 // Make sure the root is not off by one. The returned iteration should 10302 // not be in the range, but the previous one should be. When solving 10303 // for "X*X < 5", for example, we should not return a root of 2. 10304 ConstantInt *R1Val = 10305 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 10306 if (Range.contains(R1Val->getValue())) { 10307 // The next iteration must be out of the range... 10308 ConstantInt *NextVal = 10309 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 10310 10311 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10312 if (!Range.contains(R1Val->getValue())) 10313 return SE.getConstant(NextVal); 10314 return SE.getCouldNotCompute(); // Something strange happened 10315 } 10316 10317 // If R1 was not in the range, then it is a good return value. Make 10318 // sure that R1-1 WAS in the range though, just in case. 10319 ConstantInt *NextVal = 10320 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 10321 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 10322 if (Range.contains(R1Val->getValue())) 10323 return R1; 10324 return SE.getCouldNotCompute(); // Something strange happened 10325 } 10326 } 10327 } 10328 10329 return SE.getCouldNotCompute(); 10330 } 10331 10332 const SCEVAddRecExpr * 10333 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10334 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10335 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10336 // but in this case we cannot guarantee that the value returned will be an 10337 // AddRec because SCEV does not have a fixed point where it stops 10338 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10339 // may happen if we reach arithmetic depth limit while simplifying. So we 10340 // construct the returned value explicitly. 10341 SmallVector<const SCEV *, 3> Ops; 10342 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10343 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10344 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10345 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10346 // We know that the last operand is not a constant zero (otherwise it would 10347 // have been popped out earlier). This guarantees us that if the result has 10348 // the same last operand, then it will also not be popped out, meaning that 10349 // the returned value will be an AddRec. 10350 const SCEV *Last = getOperand(getNumOperands() - 1); 10351 assert(!Last->isZero() && "Recurrency with zero step?"); 10352 Ops.push_back(Last); 10353 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10354 SCEV::FlagAnyWrap)); 10355 } 10356 10357 // Return true when S contains at least an undef value. 10358 static inline bool containsUndefs(const SCEV *S) { 10359 return SCEVExprContains(S, [](const SCEV *S) { 10360 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10361 return isa<UndefValue>(SU->getValue()); 10362 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 10363 return isa<UndefValue>(SC->getValue()); 10364 return false; 10365 }); 10366 } 10367 10368 namespace { 10369 10370 // Collect all steps of SCEV expressions. 10371 struct SCEVCollectStrides { 10372 ScalarEvolution &SE; 10373 SmallVectorImpl<const SCEV *> &Strides; 10374 10375 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10376 : SE(SE), Strides(S) {} 10377 10378 bool follow(const SCEV *S) { 10379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10380 Strides.push_back(AR->getStepRecurrence(SE)); 10381 return true; 10382 } 10383 10384 bool isDone() const { return false; } 10385 }; 10386 10387 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10388 struct SCEVCollectTerms { 10389 SmallVectorImpl<const SCEV *> &Terms; 10390 10391 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10392 10393 bool follow(const SCEV *S) { 10394 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10395 isa<SCEVSignExtendExpr>(S)) { 10396 if (!containsUndefs(S)) 10397 Terms.push_back(S); 10398 10399 // Stop recursion: once we collected a term, do not walk its operands. 10400 return false; 10401 } 10402 10403 // Keep looking. 10404 return true; 10405 } 10406 10407 bool isDone() const { return false; } 10408 }; 10409 10410 // Check if a SCEV contains an AddRecExpr. 10411 struct SCEVHasAddRec { 10412 bool &ContainsAddRec; 10413 10414 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10415 ContainsAddRec = false; 10416 } 10417 10418 bool follow(const SCEV *S) { 10419 if (isa<SCEVAddRecExpr>(S)) { 10420 ContainsAddRec = true; 10421 10422 // Stop recursion: once we collected a term, do not walk its operands. 10423 return false; 10424 } 10425 10426 // Keep looking. 10427 return true; 10428 } 10429 10430 bool isDone() const { return false; } 10431 }; 10432 10433 // Find factors that are multiplied with an expression that (possibly as a 10434 // subexpression) contains an AddRecExpr. In the expression: 10435 // 10436 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10437 // 10438 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10439 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10440 // parameters as they form a product with an induction variable. 10441 // 10442 // This collector expects all array size parameters to be in the same MulExpr. 10443 // It might be necessary to later add support for collecting parameters that are 10444 // spread over different nested MulExpr. 10445 struct SCEVCollectAddRecMultiplies { 10446 SmallVectorImpl<const SCEV *> &Terms; 10447 ScalarEvolution &SE; 10448 10449 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10450 : Terms(T), SE(SE) {} 10451 10452 bool follow(const SCEV *S) { 10453 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10454 bool HasAddRec = false; 10455 SmallVector<const SCEV *, 0> Operands; 10456 for (auto Op : Mul->operands()) { 10457 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10458 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10459 Operands.push_back(Op); 10460 } else if (Unknown) { 10461 HasAddRec = true; 10462 } else { 10463 bool ContainsAddRec; 10464 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10465 visitAll(Op, ContiansAddRec); 10466 HasAddRec |= ContainsAddRec; 10467 } 10468 } 10469 if (Operands.size() == 0) 10470 return true; 10471 10472 if (!HasAddRec) 10473 return false; 10474 10475 Terms.push_back(SE.getMulExpr(Operands)); 10476 // Stop recursion: once we collected a term, do not walk its operands. 10477 return false; 10478 } 10479 10480 // Keep looking. 10481 return true; 10482 } 10483 10484 bool isDone() const { return false; } 10485 }; 10486 10487 } // end anonymous namespace 10488 10489 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10490 /// two places: 10491 /// 1) The strides of AddRec expressions. 10492 /// 2) Unknowns that are multiplied with AddRec expressions. 10493 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10494 SmallVectorImpl<const SCEV *> &Terms) { 10495 SmallVector<const SCEV *, 4> Strides; 10496 SCEVCollectStrides StrideCollector(*this, Strides); 10497 visitAll(Expr, StrideCollector); 10498 10499 DEBUG({ 10500 dbgs() << "Strides:\n"; 10501 for (const SCEV *S : Strides) 10502 dbgs() << *S << "\n"; 10503 }); 10504 10505 for (const SCEV *S : Strides) { 10506 SCEVCollectTerms TermCollector(Terms); 10507 visitAll(S, TermCollector); 10508 } 10509 10510 DEBUG({ 10511 dbgs() << "Terms:\n"; 10512 for (const SCEV *T : Terms) 10513 dbgs() << *T << "\n"; 10514 }); 10515 10516 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10517 visitAll(Expr, MulCollector); 10518 } 10519 10520 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10521 SmallVectorImpl<const SCEV *> &Terms, 10522 SmallVectorImpl<const SCEV *> &Sizes) { 10523 int Last = Terms.size() - 1; 10524 const SCEV *Step = Terms[Last]; 10525 10526 // End of recursion. 10527 if (Last == 0) { 10528 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10529 SmallVector<const SCEV *, 2> Qs; 10530 for (const SCEV *Op : M->operands()) 10531 if (!isa<SCEVConstant>(Op)) 10532 Qs.push_back(Op); 10533 10534 Step = SE.getMulExpr(Qs); 10535 } 10536 10537 Sizes.push_back(Step); 10538 return true; 10539 } 10540 10541 for (const SCEV *&Term : Terms) { 10542 // Normalize the terms before the next call to findArrayDimensionsRec. 10543 const SCEV *Q, *R; 10544 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10545 10546 // Bail out when GCD does not evenly divide one of the terms. 10547 if (!R->isZero()) 10548 return false; 10549 10550 Term = Q; 10551 } 10552 10553 // Remove all SCEVConstants. 10554 Terms.erase( 10555 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10556 Terms.end()); 10557 10558 if (Terms.size() > 0) 10559 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10560 return false; 10561 10562 Sizes.push_back(Step); 10563 return true; 10564 } 10565 10566 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10567 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10568 for (const SCEV *T : Terms) 10569 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 10570 return true; 10571 return false; 10572 } 10573 10574 // Return the number of product terms in S. 10575 static inline int numberOfTerms(const SCEV *S) { 10576 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10577 return Expr->getNumOperands(); 10578 return 1; 10579 } 10580 10581 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10582 if (isa<SCEVConstant>(T)) 10583 return nullptr; 10584 10585 if (isa<SCEVUnknown>(T)) 10586 return T; 10587 10588 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10589 SmallVector<const SCEV *, 2> Factors; 10590 for (const SCEV *Op : M->operands()) 10591 if (!isa<SCEVConstant>(Op)) 10592 Factors.push_back(Op); 10593 10594 return SE.getMulExpr(Factors); 10595 } 10596 10597 return T; 10598 } 10599 10600 /// Return the size of an element read or written by Inst. 10601 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10602 Type *Ty; 10603 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10604 Ty = Store->getValueOperand()->getType(); 10605 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10606 Ty = Load->getType(); 10607 else 10608 return nullptr; 10609 10610 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10611 return getSizeOfExpr(ETy, Ty); 10612 } 10613 10614 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 10615 SmallVectorImpl<const SCEV *> &Sizes, 10616 const SCEV *ElementSize) { 10617 if (Terms.size() < 1 || !ElementSize) 10618 return; 10619 10620 // Early return when Terms do not contain parameters: we do not delinearize 10621 // non parametric SCEVs. 10622 if (!containsParameters(Terms)) 10623 return; 10624 10625 DEBUG({ 10626 dbgs() << "Terms:\n"; 10627 for (const SCEV *T : Terms) 10628 dbgs() << *T << "\n"; 10629 }); 10630 10631 // Remove duplicates. 10632 array_pod_sort(Terms.begin(), Terms.end()); 10633 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 10634 10635 // Put larger terms first. 10636 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 10637 return numberOfTerms(LHS) > numberOfTerms(RHS); 10638 }); 10639 10640 // Try to divide all terms by the element size. If term is not divisible by 10641 // element size, proceed with the original term. 10642 for (const SCEV *&Term : Terms) { 10643 const SCEV *Q, *R; 10644 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 10645 if (!Q->isZero()) 10646 Term = Q; 10647 } 10648 10649 SmallVector<const SCEV *, 4> NewTerms; 10650 10651 // Remove constant factors. 10652 for (const SCEV *T : Terms) 10653 if (const SCEV *NewT = removeConstantFactors(*this, T)) 10654 NewTerms.push_back(NewT); 10655 10656 DEBUG({ 10657 dbgs() << "Terms after sorting:\n"; 10658 for (const SCEV *T : NewTerms) 10659 dbgs() << *T << "\n"; 10660 }); 10661 10662 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 10663 Sizes.clear(); 10664 return; 10665 } 10666 10667 // The last element to be pushed into Sizes is the size of an element. 10668 Sizes.push_back(ElementSize); 10669 10670 DEBUG({ 10671 dbgs() << "Sizes:\n"; 10672 for (const SCEV *S : Sizes) 10673 dbgs() << *S << "\n"; 10674 }); 10675 } 10676 10677 void ScalarEvolution::computeAccessFunctions( 10678 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 10679 SmallVectorImpl<const SCEV *> &Sizes) { 10680 // Early exit in case this SCEV is not an affine multivariate function. 10681 if (Sizes.empty()) 10682 return; 10683 10684 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 10685 if (!AR->isAffine()) 10686 return; 10687 10688 const SCEV *Res = Expr; 10689 int Last = Sizes.size() - 1; 10690 for (int i = Last; i >= 0; i--) { 10691 const SCEV *Q, *R; 10692 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 10693 10694 DEBUG({ 10695 dbgs() << "Res: " << *Res << "\n"; 10696 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 10697 dbgs() << "Res divided by Sizes[i]:\n"; 10698 dbgs() << "Quotient: " << *Q << "\n"; 10699 dbgs() << "Remainder: " << *R << "\n"; 10700 }); 10701 10702 Res = Q; 10703 10704 // Do not record the last subscript corresponding to the size of elements in 10705 // the array. 10706 if (i == Last) { 10707 10708 // Bail out if the remainder is too complex. 10709 if (isa<SCEVAddRecExpr>(R)) { 10710 Subscripts.clear(); 10711 Sizes.clear(); 10712 return; 10713 } 10714 10715 continue; 10716 } 10717 10718 // Record the access function for the current subscript. 10719 Subscripts.push_back(R); 10720 } 10721 10722 // Also push in last position the remainder of the last division: it will be 10723 // the access function of the innermost dimension. 10724 Subscripts.push_back(Res); 10725 10726 std::reverse(Subscripts.begin(), Subscripts.end()); 10727 10728 DEBUG({ 10729 dbgs() << "Subscripts:\n"; 10730 for (const SCEV *S : Subscripts) 10731 dbgs() << *S << "\n"; 10732 }); 10733 } 10734 10735 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 10736 /// sizes of an array access. Returns the remainder of the delinearization that 10737 /// is the offset start of the array. The SCEV->delinearize algorithm computes 10738 /// the multiples of SCEV coefficients: that is a pattern matching of sub 10739 /// expressions in the stride and base of a SCEV corresponding to the 10740 /// computation of a GCD (greatest common divisor) of base and stride. When 10741 /// SCEV->delinearize fails, it returns the SCEV unchanged. 10742 /// 10743 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 10744 /// 10745 /// void foo(long n, long m, long o, double A[n][m][o]) { 10746 /// 10747 /// for (long i = 0; i < n; i++) 10748 /// for (long j = 0; j < m; j++) 10749 /// for (long k = 0; k < o; k++) 10750 /// A[i][j][k] = 1.0; 10751 /// } 10752 /// 10753 /// the delinearization input is the following AddRec SCEV: 10754 /// 10755 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 10756 /// 10757 /// From this SCEV, we are able to say that the base offset of the access is %A 10758 /// because it appears as an offset that does not divide any of the strides in 10759 /// the loops: 10760 /// 10761 /// CHECK: Base offset: %A 10762 /// 10763 /// and then SCEV->delinearize determines the size of some of the dimensions of 10764 /// the array as these are the multiples by which the strides are happening: 10765 /// 10766 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 10767 /// 10768 /// Note that the outermost dimension remains of UnknownSize because there are 10769 /// no strides that would help identifying the size of the last dimension: when 10770 /// the array has been statically allocated, one could compute the size of that 10771 /// dimension by dividing the overall size of the array by the size of the known 10772 /// dimensions: %m * %o * 8. 10773 /// 10774 /// Finally delinearize provides the access functions for the array reference 10775 /// that does correspond to A[i][j][k] of the above C testcase: 10776 /// 10777 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 10778 /// 10779 /// The testcases are checking the output of a function pass: 10780 /// DelinearizationPass that walks through all loads and stores of a function 10781 /// asking for the SCEV of the memory access with respect to all enclosing 10782 /// loops, calling SCEV->delinearize on that and printing the results. 10783 void ScalarEvolution::delinearize(const SCEV *Expr, 10784 SmallVectorImpl<const SCEV *> &Subscripts, 10785 SmallVectorImpl<const SCEV *> &Sizes, 10786 const SCEV *ElementSize) { 10787 // First step: collect parametric terms. 10788 SmallVector<const SCEV *, 4> Terms; 10789 collectParametricTerms(Expr, Terms); 10790 10791 if (Terms.empty()) 10792 return; 10793 10794 // Second step: find subscript sizes. 10795 findArrayDimensions(Terms, Sizes, ElementSize); 10796 10797 if (Sizes.empty()) 10798 return; 10799 10800 // Third step: compute the access functions for each subscript. 10801 computeAccessFunctions(Expr, Subscripts, Sizes); 10802 10803 if (Subscripts.empty()) 10804 return; 10805 10806 DEBUG({ 10807 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 10808 dbgs() << "ArrayDecl[UnknownSize]"; 10809 for (const SCEV *S : Sizes) 10810 dbgs() << "[" << *S << "]"; 10811 10812 dbgs() << "\nArrayRef"; 10813 for (const SCEV *S : Subscripts) 10814 dbgs() << "[" << *S << "]"; 10815 dbgs() << "\n"; 10816 }); 10817 } 10818 10819 //===----------------------------------------------------------------------===// 10820 // SCEVCallbackVH Class Implementation 10821 //===----------------------------------------------------------------------===// 10822 10823 void ScalarEvolution::SCEVCallbackVH::deleted() { 10824 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10825 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 10826 SE->ConstantEvolutionLoopExitValue.erase(PN); 10827 SE->eraseValueFromMap(getValPtr()); 10828 // this now dangles! 10829 } 10830 10831 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 10832 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 10833 10834 // Forget all the expressions associated with users of the old value, 10835 // so that future queries will recompute the expressions using the new 10836 // value. 10837 Value *Old = getValPtr(); 10838 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 10839 SmallPtrSet<User *, 8> Visited; 10840 while (!Worklist.empty()) { 10841 User *U = Worklist.pop_back_val(); 10842 // Deleting the Old value will cause this to dangle. Postpone 10843 // that until everything else is done. 10844 if (U == Old) 10845 continue; 10846 if (!Visited.insert(U).second) 10847 continue; 10848 if (PHINode *PN = dyn_cast<PHINode>(U)) 10849 SE->ConstantEvolutionLoopExitValue.erase(PN); 10850 SE->eraseValueFromMap(U); 10851 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 10852 } 10853 // Delete the Old value. 10854 if (PHINode *PN = dyn_cast<PHINode>(Old)) 10855 SE->ConstantEvolutionLoopExitValue.erase(PN); 10856 SE->eraseValueFromMap(Old); 10857 // this now dangles! 10858 } 10859 10860 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 10861 : CallbackVH(V), SE(se) {} 10862 10863 //===----------------------------------------------------------------------===// 10864 // ScalarEvolution Class Implementation 10865 //===----------------------------------------------------------------------===// 10866 10867 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 10868 AssumptionCache &AC, DominatorTree &DT, 10869 LoopInfo &LI) 10870 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 10871 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 10872 LoopDispositions(64), BlockDispositions(64) { 10873 // To use guards for proving predicates, we need to scan every instruction in 10874 // relevant basic blocks, and not just terminators. Doing this is a waste of 10875 // time if the IR does not actually contain any calls to 10876 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 10877 // 10878 // This pessimizes the case where a pass that preserves ScalarEvolution wants 10879 // to _add_ guards to the module when there weren't any before, and wants 10880 // ScalarEvolution to optimize based on those guards. For now we prefer to be 10881 // efficient in lieu of being smart in that rather obscure case. 10882 10883 auto *GuardDecl = F.getParent()->getFunction( 10884 Intrinsic::getName(Intrinsic::experimental_guard)); 10885 HasGuards = GuardDecl && !GuardDecl->use_empty(); 10886 } 10887 10888 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 10889 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 10890 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 10891 ValueExprMap(std::move(Arg.ValueExprMap)), 10892 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 10893 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 10894 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 10895 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 10896 PredicatedBackedgeTakenCounts( 10897 std::move(Arg.PredicatedBackedgeTakenCounts)), 10898 ConstantEvolutionLoopExitValue( 10899 std::move(Arg.ConstantEvolutionLoopExitValue)), 10900 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 10901 LoopDispositions(std::move(Arg.LoopDispositions)), 10902 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 10903 BlockDispositions(std::move(Arg.BlockDispositions)), 10904 UnsignedRanges(std::move(Arg.UnsignedRanges)), 10905 SignedRanges(std::move(Arg.SignedRanges)), 10906 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 10907 UniquePreds(std::move(Arg.UniquePreds)), 10908 SCEVAllocator(std::move(Arg.SCEVAllocator)), 10909 LoopUsers(std::move(Arg.LoopUsers)), 10910 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 10911 FirstUnknown(Arg.FirstUnknown) { 10912 Arg.FirstUnknown = nullptr; 10913 } 10914 10915 ScalarEvolution::~ScalarEvolution() { 10916 // Iterate through all the SCEVUnknown instances and call their 10917 // destructors, so that they release their references to their values. 10918 for (SCEVUnknown *U = FirstUnknown; U;) { 10919 SCEVUnknown *Tmp = U; 10920 U = U->Next; 10921 Tmp->~SCEVUnknown(); 10922 } 10923 FirstUnknown = nullptr; 10924 10925 ExprValueMap.clear(); 10926 ValueExprMap.clear(); 10927 HasRecMap.clear(); 10928 10929 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 10930 // that a loop had multiple computable exits. 10931 for (auto &BTCI : BackedgeTakenCounts) 10932 BTCI.second.clear(); 10933 for (auto &BTCI : PredicatedBackedgeTakenCounts) 10934 BTCI.second.clear(); 10935 10936 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 10937 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 10938 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 10939 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 10940 } 10941 10942 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 10943 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 10944 } 10945 10946 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 10947 const Loop *L) { 10948 // Print all inner loops first 10949 for (Loop *I : *L) 10950 PrintLoopInfo(OS, SE, I); 10951 10952 OS << "Loop "; 10953 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10954 OS << ": "; 10955 10956 SmallVector<BasicBlock *, 8> ExitBlocks; 10957 L->getExitBlocks(ExitBlocks); 10958 if (ExitBlocks.size() != 1) 10959 OS << "<multiple exits> "; 10960 10961 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10962 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 10963 } else { 10964 OS << "Unpredictable backedge-taken count. "; 10965 } 10966 10967 OS << "\n" 10968 "Loop "; 10969 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10970 OS << ": "; 10971 10972 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 10973 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 10974 if (SE->isBackedgeTakenCountMaxOrZero(L)) 10975 OS << ", actual taken count either this or zero."; 10976 } else { 10977 OS << "Unpredictable max backedge-taken count. "; 10978 } 10979 10980 OS << "\n" 10981 "Loop "; 10982 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10983 OS << ": "; 10984 10985 SCEVUnionPredicate Pred; 10986 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 10987 if (!isa<SCEVCouldNotCompute>(PBT)) { 10988 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 10989 OS << " Predicates:\n"; 10990 Pred.print(OS, 4); 10991 } else { 10992 OS << "Unpredictable predicated backedge-taken count. "; 10993 } 10994 OS << "\n"; 10995 10996 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 10997 OS << "Loop "; 10998 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 10999 OS << ": "; 11000 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11001 } 11002 } 11003 11004 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11005 switch (LD) { 11006 case ScalarEvolution::LoopVariant: 11007 return "Variant"; 11008 case ScalarEvolution::LoopInvariant: 11009 return "Invariant"; 11010 case ScalarEvolution::LoopComputable: 11011 return "Computable"; 11012 } 11013 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11014 } 11015 11016 void ScalarEvolution::print(raw_ostream &OS) const { 11017 // ScalarEvolution's implementation of the print method is to print 11018 // out SCEV values of all instructions that are interesting. Doing 11019 // this potentially causes it to create new SCEV objects though, 11020 // which technically conflicts with the const qualifier. This isn't 11021 // observable from outside the class though, so casting away the 11022 // const isn't dangerous. 11023 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11024 11025 OS << "Classifying expressions for: "; 11026 F.printAsOperand(OS, /*PrintType=*/false); 11027 OS << "\n"; 11028 for (Instruction &I : instructions(F)) 11029 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11030 OS << I << '\n'; 11031 OS << " --> "; 11032 const SCEV *SV = SE.getSCEV(&I); 11033 SV->print(OS); 11034 if (!isa<SCEVCouldNotCompute>(SV)) { 11035 OS << " U: "; 11036 SE.getUnsignedRange(SV).print(OS); 11037 OS << " S: "; 11038 SE.getSignedRange(SV).print(OS); 11039 } 11040 11041 const Loop *L = LI.getLoopFor(I.getParent()); 11042 11043 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11044 if (AtUse != SV) { 11045 OS << " --> "; 11046 AtUse->print(OS); 11047 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11048 OS << " U: "; 11049 SE.getUnsignedRange(AtUse).print(OS); 11050 OS << " S: "; 11051 SE.getSignedRange(AtUse).print(OS); 11052 } 11053 } 11054 11055 if (L) { 11056 OS << "\t\t" "Exits: "; 11057 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11058 if (!SE.isLoopInvariant(ExitValue, L)) { 11059 OS << "<<Unknown>>"; 11060 } else { 11061 OS << *ExitValue; 11062 } 11063 11064 bool First = true; 11065 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11066 if (First) { 11067 OS << "\t\t" "LoopDispositions: { "; 11068 First = false; 11069 } else { 11070 OS << ", "; 11071 } 11072 11073 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11074 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11075 } 11076 11077 for (auto *InnerL : depth_first(L)) { 11078 if (InnerL == L) 11079 continue; 11080 if (First) { 11081 OS << "\t\t" "LoopDispositions: { "; 11082 First = false; 11083 } else { 11084 OS << ", "; 11085 } 11086 11087 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11088 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11089 } 11090 11091 OS << " }"; 11092 } 11093 11094 OS << "\n"; 11095 } 11096 11097 OS << "Determining loop execution counts for: "; 11098 F.printAsOperand(OS, /*PrintType=*/false); 11099 OS << "\n"; 11100 for (Loop *I : LI) 11101 PrintLoopInfo(OS, &SE, I); 11102 } 11103 11104 ScalarEvolution::LoopDisposition 11105 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11106 auto &Values = LoopDispositions[S]; 11107 for (auto &V : Values) { 11108 if (V.getPointer() == L) 11109 return V.getInt(); 11110 } 11111 Values.emplace_back(L, LoopVariant); 11112 LoopDisposition D = computeLoopDisposition(S, L); 11113 auto &Values2 = LoopDispositions[S]; 11114 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11115 if (V.getPointer() == L) { 11116 V.setInt(D); 11117 break; 11118 } 11119 } 11120 return D; 11121 } 11122 11123 ScalarEvolution::LoopDisposition 11124 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11125 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11126 case scConstant: 11127 return LoopInvariant; 11128 case scTruncate: 11129 case scZeroExtend: 11130 case scSignExtend: 11131 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11132 case scAddRecExpr: { 11133 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11134 11135 // If L is the addrec's loop, it's computable. 11136 if (AR->getLoop() == L) 11137 return LoopComputable; 11138 11139 // Add recurrences are never invariant in the function-body (null loop). 11140 if (!L) 11141 return LoopVariant; 11142 11143 // Everything that is not defined at loop entry is variant. 11144 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11145 return LoopVariant; 11146 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11147 " dominate the contained loop's header?"); 11148 11149 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11150 if (AR->getLoop()->contains(L)) 11151 return LoopInvariant; 11152 11153 // This recurrence is variant w.r.t. L if any of its operands 11154 // are variant. 11155 for (auto *Op : AR->operands()) 11156 if (!isLoopInvariant(Op, L)) 11157 return LoopVariant; 11158 11159 // Otherwise it's loop-invariant. 11160 return LoopInvariant; 11161 } 11162 case scAddExpr: 11163 case scMulExpr: 11164 case scUMaxExpr: 11165 case scSMaxExpr: { 11166 bool HasVarying = false; 11167 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11168 LoopDisposition D = getLoopDisposition(Op, L); 11169 if (D == LoopVariant) 11170 return LoopVariant; 11171 if (D == LoopComputable) 11172 HasVarying = true; 11173 } 11174 return HasVarying ? LoopComputable : LoopInvariant; 11175 } 11176 case scUDivExpr: { 11177 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11178 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11179 if (LD == LoopVariant) 11180 return LoopVariant; 11181 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11182 if (RD == LoopVariant) 11183 return LoopVariant; 11184 return (LD == LoopInvariant && RD == LoopInvariant) ? 11185 LoopInvariant : LoopComputable; 11186 } 11187 case scUnknown: 11188 // All non-instruction values are loop invariant. All instructions are loop 11189 // invariant if they are not contained in the specified loop. 11190 // Instructions are never considered invariant in the function body 11191 // (null loop) because they are defined within the "loop". 11192 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11193 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11194 return LoopInvariant; 11195 case scCouldNotCompute: 11196 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11197 } 11198 llvm_unreachable("Unknown SCEV kind!"); 11199 } 11200 11201 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11202 return getLoopDisposition(S, L) == LoopInvariant; 11203 } 11204 11205 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11206 return getLoopDisposition(S, L) == LoopComputable; 11207 } 11208 11209 ScalarEvolution::BlockDisposition 11210 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11211 auto &Values = BlockDispositions[S]; 11212 for (auto &V : Values) { 11213 if (V.getPointer() == BB) 11214 return V.getInt(); 11215 } 11216 Values.emplace_back(BB, DoesNotDominateBlock); 11217 BlockDisposition D = computeBlockDisposition(S, BB); 11218 auto &Values2 = BlockDispositions[S]; 11219 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11220 if (V.getPointer() == BB) { 11221 V.setInt(D); 11222 break; 11223 } 11224 } 11225 return D; 11226 } 11227 11228 ScalarEvolution::BlockDisposition 11229 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11230 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11231 case scConstant: 11232 return ProperlyDominatesBlock; 11233 case scTruncate: 11234 case scZeroExtend: 11235 case scSignExtend: 11236 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11237 case scAddRecExpr: { 11238 // This uses a "dominates" query instead of "properly dominates" query 11239 // to test for proper dominance too, because the instruction which 11240 // produces the addrec's value is a PHI, and a PHI effectively properly 11241 // dominates its entire containing block. 11242 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11243 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11244 return DoesNotDominateBlock; 11245 11246 // Fall through into SCEVNAryExpr handling. 11247 LLVM_FALLTHROUGH; 11248 } 11249 case scAddExpr: 11250 case scMulExpr: 11251 case scUMaxExpr: 11252 case scSMaxExpr: { 11253 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11254 bool Proper = true; 11255 for (const SCEV *NAryOp : NAry->operands()) { 11256 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11257 if (D == DoesNotDominateBlock) 11258 return DoesNotDominateBlock; 11259 if (D == DominatesBlock) 11260 Proper = false; 11261 } 11262 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11263 } 11264 case scUDivExpr: { 11265 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11266 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11267 BlockDisposition LD = getBlockDisposition(LHS, BB); 11268 if (LD == DoesNotDominateBlock) 11269 return DoesNotDominateBlock; 11270 BlockDisposition RD = getBlockDisposition(RHS, BB); 11271 if (RD == DoesNotDominateBlock) 11272 return DoesNotDominateBlock; 11273 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11274 ProperlyDominatesBlock : DominatesBlock; 11275 } 11276 case scUnknown: 11277 if (Instruction *I = 11278 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11279 if (I->getParent() == BB) 11280 return DominatesBlock; 11281 if (DT.properlyDominates(I->getParent(), BB)) 11282 return ProperlyDominatesBlock; 11283 return DoesNotDominateBlock; 11284 } 11285 return ProperlyDominatesBlock; 11286 case scCouldNotCompute: 11287 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11288 } 11289 llvm_unreachable("Unknown SCEV kind!"); 11290 } 11291 11292 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11293 return getBlockDisposition(S, BB) >= DominatesBlock; 11294 } 11295 11296 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11297 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11298 } 11299 11300 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11301 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11302 } 11303 11304 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11305 auto IsS = [&](const SCEV *X) { return S == X; }; 11306 auto ContainsS = [&](const SCEV *X) { 11307 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11308 }; 11309 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11310 } 11311 11312 void 11313 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11314 ValuesAtScopes.erase(S); 11315 LoopDispositions.erase(S); 11316 BlockDispositions.erase(S); 11317 UnsignedRanges.erase(S); 11318 SignedRanges.erase(S); 11319 ExprValueMap.erase(S); 11320 HasRecMap.erase(S); 11321 MinTrailingZerosCache.erase(S); 11322 11323 for (auto I = PredicatedSCEVRewrites.begin(); 11324 I != PredicatedSCEVRewrites.end();) { 11325 std::pair<const SCEV *, const Loop *> Entry = I->first; 11326 if (Entry.first == S) 11327 PredicatedSCEVRewrites.erase(I++); 11328 else 11329 ++I; 11330 } 11331 11332 auto RemoveSCEVFromBackedgeMap = 11333 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11334 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11335 BackedgeTakenInfo &BEInfo = I->second; 11336 if (BEInfo.hasOperand(S, this)) { 11337 BEInfo.clear(); 11338 Map.erase(I++); 11339 } else 11340 ++I; 11341 } 11342 }; 11343 11344 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11345 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11346 } 11347 11348 void 11349 ScalarEvolution::getUsedLoops(const SCEV *S, 11350 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11351 struct FindUsedLoops { 11352 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11353 : LoopsUsed(LoopsUsed) {} 11354 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11355 bool follow(const SCEV *S) { 11356 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11357 LoopsUsed.insert(AR->getLoop()); 11358 return true; 11359 } 11360 11361 bool isDone() const { return false; } 11362 }; 11363 11364 FindUsedLoops F(LoopsUsed); 11365 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11366 } 11367 11368 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11369 SmallPtrSet<const Loop *, 8> LoopsUsed; 11370 getUsedLoops(S, LoopsUsed); 11371 for (auto *L : LoopsUsed) 11372 LoopUsers[L].push_back(S); 11373 } 11374 11375 void ScalarEvolution::verify() const { 11376 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11377 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11378 11379 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11380 11381 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11382 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11383 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11384 11385 const SCEV *visitConstant(const SCEVConstant *Constant) { 11386 return SE.getConstant(Constant->getAPInt()); 11387 } 11388 11389 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11390 return SE.getUnknown(Expr->getValue()); 11391 } 11392 11393 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11394 return SE.getCouldNotCompute(); 11395 } 11396 }; 11397 11398 SCEVMapper SCM(SE2); 11399 11400 while (!LoopStack.empty()) { 11401 auto *L = LoopStack.pop_back_val(); 11402 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11403 11404 auto *CurBECount = SCM.visit( 11405 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11406 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11407 11408 if (CurBECount == SE2.getCouldNotCompute() || 11409 NewBECount == SE2.getCouldNotCompute()) { 11410 // NB! This situation is legal, but is very suspicious -- whatever pass 11411 // change the loop to make a trip count go from could not compute to 11412 // computable or vice-versa *should have* invalidated SCEV. However, we 11413 // choose not to assert here (for now) since we don't want false 11414 // positives. 11415 continue; 11416 } 11417 11418 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11419 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11420 // not propagate undef aggressively). This means we can (and do) fail 11421 // verification in cases where a transform makes the trip count of a loop 11422 // go from "undef" to "undef+1" (say). The transform is fine, since in 11423 // both cases the loop iterates "undef" times, but SCEV thinks we 11424 // increased the trip count of the loop by 1 incorrectly. 11425 continue; 11426 } 11427 11428 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11429 SE.getTypeSizeInBits(NewBECount->getType())) 11430 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11431 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11432 SE.getTypeSizeInBits(NewBECount->getType())) 11433 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11434 11435 auto *ConstantDelta = 11436 dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount)); 11437 11438 if (ConstantDelta && ConstantDelta->getAPInt() != 0) { 11439 dbgs() << "Trip Count Changed!\n"; 11440 dbgs() << "Old: " << *CurBECount << "\n"; 11441 dbgs() << "New: " << *NewBECount << "\n"; 11442 dbgs() << "Delta: " << *ConstantDelta << "\n"; 11443 std::abort(); 11444 } 11445 } 11446 } 11447 11448 bool ScalarEvolution::invalidate( 11449 Function &F, const PreservedAnalyses &PA, 11450 FunctionAnalysisManager::Invalidator &Inv) { 11451 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11452 // of its dependencies is invalidated. 11453 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11454 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11455 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11456 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11457 Inv.invalidate<LoopAnalysis>(F, PA); 11458 } 11459 11460 AnalysisKey ScalarEvolutionAnalysis::Key; 11461 11462 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11463 FunctionAnalysisManager &AM) { 11464 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11465 AM.getResult<AssumptionAnalysis>(F), 11466 AM.getResult<DominatorTreeAnalysis>(F), 11467 AM.getResult<LoopAnalysis>(F)); 11468 } 11469 11470 PreservedAnalyses 11471 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11472 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11473 return PreservedAnalyses::all(); 11474 } 11475 11476 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11477 "Scalar Evolution Analysis", false, true) 11478 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11479 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11480 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11481 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11482 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11483 "Scalar Evolution Analysis", false, true) 11484 11485 char ScalarEvolutionWrapperPass::ID = 0; 11486 11487 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11488 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11489 } 11490 11491 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11492 SE.reset(new ScalarEvolution( 11493 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 11494 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11495 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11496 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11497 return false; 11498 } 11499 11500 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11501 11502 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11503 SE->print(OS); 11504 } 11505 11506 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11507 if (!VerifySCEV) 11508 return; 11509 11510 SE->verify(); 11511 } 11512 11513 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11514 AU.setPreservesAll(); 11515 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11516 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11517 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11518 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11519 } 11520 11521 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11522 const SCEV *RHS) { 11523 FoldingSetNodeID ID; 11524 assert(LHS->getType() == RHS->getType() && 11525 "Type mismatch between LHS and RHS"); 11526 // Unique this node based on the arguments 11527 ID.AddInteger(SCEVPredicate::P_Equal); 11528 ID.AddPointer(LHS); 11529 ID.AddPointer(RHS); 11530 void *IP = nullptr; 11531 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11532 return S; 11533 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11534 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11535 UniquePreds.InsertNode(Eq, IP); 11536 return Eq; 11537 } 11538 11539 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11540 const SCEVAddRecExpr *AR, 11541 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11542 FoldingSetNodeID ID; 11543 // Unique this node based on the arguments 11544 ID.AddInteger(SCEVPredicate::P_Wrap); 11545 ID.AddPointer(AR); 11546 ID.AddInteger(AddedFlags); 11547 void *IP = nullptr; 11548 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11549 return S; 11550 auto *OF = new (SCEVAllocator) 11551 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 11552 UniquePreds.InsertNode(OF, IP); 11553 return OF; 11554 } 11555 11556 namespace { 11557 11558 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 11559 public: 11560 11561 /// Rewrites \p S in the context of a loop L and the SCEV predication 11562 /// infrastructure. 11563 /// 11564 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 11565 /// equivalences present in \p Pred. 11566 /// 11567 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 11568 /// \p NewPreds such that the result will be an AddRecExpr. 11569 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 11570 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11571 SCEVUnionPredicate *Pred) { 11572 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 11573 return Rewriter.visit(S); 11574 } 11575 11576 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11577 if (Pred) { 11578 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 11579 for (auto *Pred : ExprPreds) 11580 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 11581 if (IPred->getLHS() == Expr) 11582 return IPred->getRHS(); 11583 } 11584 return convertToAddRecWithPreds(Expr); 11585 } 11586 11587 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 11588 const SCEV *Operand = visit(Expr->getOperand()); 11589 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11590 if (AR && AR->getLoop() == L && AR->isAffine()) { 11591 // This couldn't be folded because the operand didn't have the nuw 11592 // flag. Add the nusw flag as an assumption that we could make. 11593 const SCEV *Step = AR->getStepRecurrence(SE); 11594 Type *Ty = Expr->getType(); 11595 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 11596 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 11597 SE.getSignExtendExpr(Step, Ty), L, 11598 AR->getNoWrapFlags()); 11599 } 11600 return SE.getZeroExtendExpr(Operand, Expr->getType()); 11601 } 11602 11603 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 11604 const SCEV *Operand = visit(Expr->getOperand()); 11605 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 11606 if (AR && AR->getLoop() == L && AR->isAffine()) { 11607 // This couldn't be folded because the operand didn't have the nsw 11608 // flag. Add the nssw flag as an assumption that we could make. 11609 const SCEV *Step = AR->getStepRecurrence(SE); 11610 Type *Ty = Expr->getType(); 11611 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 11612 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 11613 SE.getSignExtendExpr(Step, Ty), L, 11614 AR->getNoWrapFlags()); 11615 } 11616 return SE.getSignExtendExpr(Operand, Expr->getType()); 11617 } 11618 11619 private: 11620 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 11621 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 11622 SCEVUnionPredicate *Pred) 11623 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 11624 11625 bool addOverflowAssumption(const SCEVPredicate *P) { 11626 if (!NewPreds) { 11627 // Check if we've already made this assumption. 11628 return Pred && Pred->implies(P); 11629 } 11630 NewPreds->insert(P); 11631 return true; 11632 } 11633 11634 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 11635 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11636 auto *A = SE.getWrapPredicate(AR, AddedFlags); 11637 return addOverflowAssumption(A); 11638 } 11639 11640 // If \p Expr represents a PHINode, we try to see if it can be represented 11641 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 11642 // to add this predicate as a runtime overflow check, we return the AddRec. 11643 // If \p Expr does not meet these conditions (is not a PHI node, or we 11644 // couldn't create an AddRec for it, or couldn't add the predicate), we just 11645 // return \p Expr. 11646 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 11647 if (!VersionUnknown) 11648 return Expr; 11649 if (!isa<PHINode>(Expr->getValue())) 11650 return Expr; 11651 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 11652 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 11653 if (!PredicatedRewrite) 11654 return Expr; 11655 for (auto *P : PredicatedRewrite->second){ 11656 // Wrap predicates from outer loops are not supported. 11657 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 11658 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 11659 if (L != AR->getLoop()) 11660 return Expr; 11661 } 11662 if (!addOverflowAssumption(P)) 11663 return Expr; 11664 } 11665 return PredicatedRewrite->first; 11666 } 11667 11668 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 11669 SCEVUnionPredicate *Pred; 11670 const Loop *L; 11671 }; 11672 11673 } // end anonymous namespace 11674 11675 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 11676 SCEVUnionPredicate &Preds) { 11677 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 11678 } 11679 11680 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 11681 const SCEV *S, const Loop *L, 11682 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 11683 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 11684 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 11685 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 11686 11687 if (!AddRec) 11688 return nullptr; 11689 11690 // Since the transformation was successful, we can now transfer the SCEV 11691 // predicates. 11692 for (auto *P : TransformPreds) 11693 Preds.insert(P); 11694 11695 return AddRec; 11696 } 11697 11698 /// SCEV predicates 11699 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 11700 SCEVPredicateKind Kind) 11701 : FastID(ID), Kind(Kind) {} 11702 11703 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 11704 const SCEV *LHS, const SCEV *RHS) 11705 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 11706 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 11707 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 11708 } 11709 11710 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 11711 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 11712 11713 if (!Op) 11714 return false; 11715 11716 return Op->LHS == LHS && Op->RHS == RHS; 11717 } 11718 11719 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 11720 11721 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 11722 11723 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 11724 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 11725 } 11726 11727 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 11728 const SCEVAddRecExpr *AR, 11729 IncrementWrapFlags Flags) 11730 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 11731 11732 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 11733 11734 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 11735 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 11736 11737 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 11738 } 11739 11740 bool SCEVWrapPredicate::isAlwaysTrue() const { 11741 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 11742 IncrementWrapFlags IFlags = Flags; 11743 11744 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 11745 IFlags = clearFlags(IFlags, IncrementNSSW); 11746 11747 return IFlags == IncrementAnyWrap; 11748 } 11749 11750 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 11751 OS.indent(Depth) << *getExpr() << " Added Flags: "; 11752 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 11753 OS << "<nusw>"; 11754 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 11755 OS << "<nssw>"; 11756 OS << "\n"; 11757 } 11758 11759 SCEVWrapPredicate::IncrementWrapFlags 11760 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 11761 ScalarEvolution &SE) { 11762 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 11763 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 11764 11765 // We can safely transfer the NSW flag as NSSW. 11766 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 11767 ImpliedFlags = IncrementNSSW; 11768 11769 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 11770 // If the increment is positive, the SCEV NUW flag will also imply the 11771 // WrapPredicate NUSW flag. 11772 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 11773 if (Step->getValue()->getValue().isNonNegative()) 11774 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 11775 } 11776 11777 return ImpliedFlags; 11778 } 11779 11780 /// Union predicates don't get cached so create a dummy set ID for it. 11781 SCEVUnionPredicate::SCEVUnionPredicate() 11782 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 11783 11784 bool SCEVUnionPredicate::isAlwaysTrue() const { 11785 return all_of(Preds, 11786 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 11787 } 11788 11789 ArrayRef<const SCEVPredicate *> 11790 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 11791 auto I = SCEVToPreds.find(Expr); 11792 if (I == SCEVToPreds.end()) 11793 return ArrayRef<const SCEVPredicate *>(); 11794 return I->second; 11795 } 11796 11797 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 11798 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 11799 return all_of(Set->Preds, 11800 [this](const SCEVPredicate *I) { return this->implies(I); }); 11801 11802 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 11803 if (ScevPredsIt == SCEVToPreds.end()) 11804 return false; 11805 auto &SCEVPreds = ScevPredsIt->second; 11806 11807 return any_of(SCEVPreds, 11808 [N](const SCEVPredicate *I) { return I->implies(N); }); 11809 } 11810 11811 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 11812 11813 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 11814 for (auto Pred : Preds) 11815 Pred->print(OS, Depth); 11816 } 11817 11818 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 11819 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 11820 for (auto Pred : Set->Preds) 11821 add(Pred); 11822 return; 11823 } 11824 11825 if (implies(N)) 11826 return; 11827 11828 const SCEV *Key = N->getExpr(); 11829 assert(Key && "Only SCEVUnionPredicate doesn't have an " 11830 " associated expression!"); 11831 11832 SCEVToPreds[Key].push_back(N); 11833 Preds.push_back(N); 11834 } 11835 11836 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 11837 Loop &L) 11838 : SE(SE), L(L) {} 11839 11840 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 11841 const SCEV *Expr = SE.getSCEV(V); 11842 RewriteEntry &Entry = RewriteMap[Expr]; 11843 11844 // If we already have an entry and the version matches, return it. 11845 if (Entry.second && Generation == Entry.first) 11846 return Entry.second; 11847 11848 // We found an entry but it's stale. Rewrite the stale entry 11849 // according to the current predicate. 11850 if (Entry.second) 11851 Expr = Entry.second; 11852 11853 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 11854 Entry = {Generation, NewSCEV}; 11855 11856 return NewSCEV; 11857 } 11858 11859 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 11860 if (!BackedgeCount) { 11861 SCEVUnionPredicate BackedgePred; 11862 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 11863 addPredicate(BackedgePred); 11864 } 11865 return BackedgeCount; 11866 } 11867 11868 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 11869 if (Preds.implies(&Pred)) 11870 return; 11871 Preds.add(&Pred); 11872 updateGeneration(); 11873 } 11874 11875 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 11876 return Preds; 11877 } 11878 11879 void PredicatedScalarEvolution::updateGeneration() { 11880 // If the generation number wrapped recompute everything. 11881 if (++Generation == 0) { 11882 for (auto &II : RewriteMap) { 11883 const SCEV *Rewritten = II.second.second; 11884 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 11885 } 11886 } 11887 } 11888 11889 void PredicatedScalarEvolution::setNoOverflow( 11890 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11891 const SCEV *Expr = getSCEV(V); 11892 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11893 11894 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 11895 11896 // Clear the statically implied flags. 11897 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 11898 addPredicate(*SE.getWrapPredicate(AR, Flags)); 11899 11900 auto II = FlagsMap.insert({V, Flags}); 11901 if (!II.second) 11902 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 11903 } 11904 11905 bool PredicatedScalarEvolution::hasNoOverflow( 11906 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 11907 const SCEV *Expr = getSCEV(V); 11908 const auto *AR = cast<SCEVAddRecExpr>(Expr); 11909 11910 Flags = SCEVWrapPredicate::clearFlags( 11911 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 11912 11913 auto II = FlagsMap.find(V); 11914 11915 if (II != FlagsMap.end()) 11916 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 11917 11918 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 11919 } 11920 11921 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 11922 const SCEV *Expr = this->getSCEV(V); 11923 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 11924 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 11925 11926 if (!New) 11927 return nullptr; 11928 11929 for (auto *P : NewPreds) 11930 Preds.add(P); 11931 11932 updateGeneration(); 11933 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 11934 return New; 11935 } 11936 11937 PredicatedScalarEvolution::PredicatedScalarEvolution( 11938 const PredicatedScalarEvolution &Init) 11939 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 11940 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 11941 for (const auto &I : Init.FlagsMap) 11942 FlagsMap.insert(I); 11943 } 11944 11945 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 11946 // For each block. 11947 for (auto *BB : L.getBlocks()) 11948 for (auto &I : *BB) { 11949 if (!SE.isSCEVable(I.getType())) 11950 continue; 11951 11952 auto *Expr = SE.getSCEV(&I); 11953 auto II = RewriteMap.find(Expr); 11954 11955 if (II == RewriteMap.end()) 11956 continue; 11957 11958 // Don't print things that are not interesting. 11959 if (II->second.second == Expr) 11960 continue; 11961 11962 OS.indent(Depth) << "[PSE]" << I << ":\n"; 11963 OS.indent(Depth + 2) << *Expr << "\n"; 11964 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 11965 } 11966 } 11967